diff --git a/lightly/__init__.py b/lightly/__init__.py index 8b2d3a8f8..9d01fdb91 100644 --- a/lightly/__init__.py +++ b/lightly/__init__.py @@ -82,11 +82,11 @@ if os.getenv("LIGHTLY_DID_VERSION_CHECK", "False") == "False": os.environ["LIGHTLY_DID_VERSION_CHECK"] = "True" - import multiprocessing + # import multiprocessing - if multiprocessing.current_process().name == "MainProcess": - from lightly.api import _version_checking + # if multiprocessing.current_process().name == "MainProcess": + # from lightly_api.api import _version_checking - _version_checking.check_is_latest_version_in_background( - current_version=__version__ - ) + # _version_checking.check_is_latest_version_in_background( + # current_version=__version__ + # ) diff --git a/lightly/active_learning/__init__.py b/lightly/active_learning/__init__.py deleted file mode 100644 index 124841cb2..000000000 --- a/lightly/active_learning/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -import warnings - - -def raise_active_learning_deprecation_warning(): - warnings.warn( - "Using active learning via the lightly package is deprecated and will be removed soon. " - "Please use the Lightly Solution instead. " - "See https://docs.lightly.ai for more information and tutorials on doing active learning.", - DeprecationWarning, - stacklevel=2, - ) diff --git a/lightly/active_learning/config/__init__.py b/lightly/active_learning/config/__init__.py deleted file mode 100644 index 914442723..000000000 --- a/lightly/active_learning/config/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -""" Collection of Selection Configurations """ - -# Copyright (c) 2020. Lightly AG and its affiliates. -# All Rights Reserved - -from lightly.active_learning.config.selection_config import SelectionConfig diff --git a/lightly/active_learning/config/selection_config.py b/lightly/active_learning/config/selection_config.py deleted file mode 100644 index 6293b0335..000000000 --- a/lightly/active_learning/config/selection_config.py +++ /dev/null @@ -1,54 +0,0 @@ -import warnings -from datetime import datetime - -from lightly.active_learning import raise_active_learning_deprecation_warning -from lightly.openapi_generated.swagger_client.models.sampling_method import ( - SamplingMethod, -) - - -class SelectionConfig: - """Configuration class for a selection. - - Attributes: - method: - The method to use for selection, one of CORESET, RANDOM, CORAL, ACTIVE_LEARNING - n_samples: - The maximum number of samples to be chosen by the selection - including the samples in the preselected tag. One of the stopping - conditions. - min_distance: - The minimum distance of samples in the chosen set, one of the - stopping conditions. - name: - The name of this selection, defaults to a name consisting of all - other attributes and the datetime. A new tag will be created in the - web-app under this name. - - Examples: - >>> # select 100 images with CORESET selection - >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=100) - >>> - >>> # give your selection a name - >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=100, name='my-selection') - >>> - >>> # use minimum distance between samples as stopping criterion - >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=-1, min_distance=0.1) - - """ - - def __init__( - self, - method: SamplingMethod = SamplingMethod.CORESET, - n_samples: int = 32, - min_distance: float = -1, - name: str = None, - ): - raise_active_learning_deprecation_warning() - self.method = method - self.n_samples = n_samples - self.min_distance = min_distance - if name is None: - date_time = datetime.now().strftime("%m_%d_%Y__%H_%M_%S") - name = f"{self.method}_{self.n_samples}_{self.min_distance}_{date_time}" - self.name = name diff --git a/lightly/api/__init__.py b/lightly/api/__init__.py deleted file mode 100644 index a5387bf9c..000000000 --- a/lightly/api/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -""" The lightly.api module provides access to the Lightly API.""" - -# Copyright (c) 2020. Lightly AG and its affiliates. -# All Rights Reserved -from lightly.api import patch as _patch -from lightly.api.api_workflow_artifacts import ArtifactNotExist -from lightly.api.api_workflow_client import ApiWorkflowClient -from lightly.openapi_generated.swagger_client.api_client import ( - Configuration as _Configuration, -) - -# Make ApiWorkflowClient and swagger classes picklable. -_patch.make_swagger_configuration_picklable( - configuration_cls=_Configuration, -) diff --git a/lightly/api/_version_checking.py b/lightly/api/_version_checking.py deleted file mode 100644 index 3f370732a..000000000 --- a/lightly/api/_version_checking.py +++ /dev/null @@ -1,73 +0,0 @@ -from threading import Thread - -from lightly.api import utils -from lightly.api.swagger_api_client import LightlySwaggerApiClient -from lightly.openapi_generated.swagger_client.api import VersioningApi -from lightly.utils import version_compare - -# Default timeout for API version verification requests in seconds. -DEFAULT_TIMEOUT_SEC = 2 - - -def is_latest_version(current_version: str) -> bool: - """Returns True if package version is latest released version.""" - latest_version = get_latest_version(current_version) - return version_compare.version_compare(current_version, latest_version) >= 0 - - -def is_compatible_version(current_version: str) -> bool: - """Returns True if package version is compatible with API.""" - minimum_version = get_minimum_compatible_version() - return version_compare.version_compare(current_version, minimum_version) >= 0 - - -def get_latest_version( - current_version: str, timeout_sec: float = DEFAULT_TIMEOUT_SEC -) -> str: - """Returns the latest package version.""" - versioning_api = _get_versioning_api() - version_number: str = versioning_api.get_latest_pip_version( - current_version=current_version, - _request_timeout=timeout_sec, - ) - return version_number - - -def get_minimum_compatible_version( - timeout_sec: float = DEFAULT_TIMEOUT_SEC, -) -> str: - """Returns minimum package version that is compatible with the API.""" - versioning_api = _get_versioning_api() - version_number: str = versioning_api.get_minimum_compatible_pip_version( - _request_timeout=timeout_sec - ) - return version_number - - -def check_is_latest_version_in_background(current_version: str) -> None: - """Checks if the current version is the latest version in a background thread.""" - - def _check_version_in_background(current_version: str) -> None: - try: - is_latest_version(current_version=current_version) - except Exception: - # Ignore failed check. - pass - - thread = Thread( - target=_check_version_in_background, - kwargs=dict(current_version=current_version), - daemon=True, - ) - thread.start() - - -def _get_versioning_api() -> VersioningApi: - configuration = utils.get_api_client_configuration( - raise_if_no_token_specified=False, - ) - # Set retries to 0 to avoid waiting for retries in case of a timeout. - configuration.retries = 0 - api_client = LightlySwaggerApiClient(configuration=configuration) - versioning_api = VersioningApi(api_client=api_client) - return versioning_api diff --git a/lightly/api/api_workflow_artifacts.py b/lightly/api/api_workflow_artifacts.py deleted file mode 100644 index 6bea0447e..000000000 --- a/lightly/api/api_workflow_artifacts.py +++ /dev/null @@ -1,489 +0,0 @@ -import os -import warnings - -from lightly.api import download -from lightly.openapi_generated.swagger_client.models import ( - DockerRunArtifactData, - DockerRunArtifactType, - DockerRunData, -) - - -class ArtifactNotExist(Exception): - pass - - -class _ArtifactsMixin: - def download_compute_worker_run_artifacts( - self, - run: DockerRunData, - output_dir: str, - timeout: int = 60, - ) -> None: - """Downloads all artifacts from a run. - - Args: - run: - Run from which to download artifacts. - output_dir: - Output directory where artifacts will be saved. - timeout: - Timeout in seconds after which an artifact download is interrupted. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download artifacts - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_artifacts(run=run, output_dir="my_run/artifacts") - - """ - if run.artifacts is None: - return - for artifact in run.artifacts: - self._download_compute_worker_run_artifact( - run_id=run.id, - artifact_id=artifact.id, - output_path=os.path.join(output_dir, artifact.file_name), - timeout=timeout, - ) - - def download_compute_worker_run_checkpoint( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Downloads the last training checkpoint from a run. - - See our docs for more information regarding checkpoints: - https://docs.lightly.ai/docs/train-a-self-supervised-model#checkpoints - - Args: - run: - Run from which to download the checkpoint. - output_path: - Path where checkpoint will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no checkpoint artifact or the checkpoint has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download checkpoint - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_checkpoint(run=run, output_path="my_checkpoint.ckpt") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.CHECKPOINT, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_report_pdf( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the report in pdf format from a run. - - Args: - run: - Run from which to download the report. - output_path: - Path where report will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no report artifact or the report has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download report - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_report_pdf(run=run, output_path="report.pdf") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.REPORT_PDF, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_report_json( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the report in json format from a run. - - DEPRECATED: This method is deprecated and will be removed in the future. Use - download_compute_worker_run_report_v2_json to download the new report_v2.json - instead. - - Args: - run: - Run from which to download the report. - output_path: - Path where report will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no report artifact or the report has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download checkpoint - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_report_json(run=run, output_path="report.json") - - """ - warnings.warn( - DeprecationWarning( - "This method downloads the deprecated report.json file and will be " - "removed in the future. Use download_compute_worker_run_report_v2_json " - "to download the new report_v2.json file instead." - ) - ) - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.REPORT_JSON, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_report_v2_json( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the report in json format from a run. - - Args: - run: - Run from which to download the report. - output_path: - Path where report will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no report artifact or the report has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download checkpoint - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_report_v2_json(run=run, output_path="report_v2.json") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.REPORT_V2_JSON, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_log( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the log file from a run. - - Args: - run: - Run from which to download the log file. - output_path: - Path where log file will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no log artifact or the log file has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download log file - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_log(run=run, output_path="log.txt") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.LOG, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_memory_log( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the memory consumption log file from a run. - - Args: - run: - Run from which to download the memory log file. - output_path: - Path where memory log file will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no memory log artifact or the memory log file has not yet - been uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download memory log file - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_memory_log(run=run, output_path="memlog.txt") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.MEMLOG, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_corruptness_check_information( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the corruptness check information file from a run. - - Args: - run: - Run from which to download the file. - output_path: - Path where the file will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no corruptness check information artifact or the file - has not yet been uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download corruptness check information file - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_corruptness_check_information(run=run, output_path="corruptness_check_information.json") - >>> - >>> # print all corrupt samples and corruptions - >>> with open("corruptness_check_information.json", 'r') as f: - >>> corruptness_check_information = json.load(f) - >>> for sample_name, error in corruptness_check_information["corrupt_samples"].items(): - >>> print(f"Sample '{sample_name}' is corrupt because of the error '{error}'.") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.CORRUPTNESS_CHECK_INFORMATION, - output_path=output_path, - timeout=timeout, - ) - - def download_compute_worker_run_sequence_information( - self, - run: DockerRunData, - output_path: str, - timeout: int = 60, - ) -> None: - """Download the sequence information from a run. - - Args: - run: - Run from which to download the the file. - output_path: - Path where the file will be saved. - timeout: - Timeout in seconds after which download is interrupted. - - Raises: - ArtifactNotExist: - If the run has no sequence information artifact or the file has not yet - been uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # download sequence information file - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> client.download_compute_worker_run_sequence_information(run=run, output_path="sequence_information.json") - - """ - self._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.SEQUENCE_INFORMATION, - output_path=output_path, - timeout=timeout, - ) - - def _download_compute_worker_run_artifact_by_type( - self, - run: DockerRunData, - artifact_type: str, - output_path: str, - timeout: int, - ) -> None: - artifact = self._get_artifact_by_type(artifact_type, run) - self._download_compute_worker_run_artifact( - run_id=run.id, - artifact_id=artifact.id, - output_path=output_path, - timeout=timeout, - ) - - def _get_artifact_by_type( - self, artifact_type: str, run: DockerRunData - ) -> DockerRunArtifactData: - if run.artifacts is None: - raise ArtifactNotExist(f"Run has no artifacts.") - try: - artifact = next(art for art in run.artifacts if art.type == artifact_type) - except StopIteration: - raise ArtifactNotExist( - f"No artifact with type '{artifact_type}' in artifacts." - ) - return artifact - - def _download_compute_worker_run_artifact( - self, - run_id: str, - artifact_id: str, - output_path: str, - timeout: int, - ) -> None: - read_url = self._compute_worker_api.get_docker_run_artifact_read_url_by_id( - run_id=run_id, - artifact_id=artifact_id, - ) - download.download_and_write_file( - url=read_url, - output_path=output_path, - request_kwargs=dict(timeout=timeout), - ) - - def get_compute_worker_run_checkpoint_url( - self, - run: DockerRunData, - ) -> str: - """Gets the download url of the last training checkpoint from a run. - - See our docs for more information regarding checkpoints: - https://docs.lightly.ai/docs/train-a-self-supervised-model#checkpoints - - Args: - run: - Run from which to download the checkpoint. - - Returns: - The url from which the checkpoint can be downloaded. - - Raises: - ArtifactNotExist: - If the run has no checkpoint artifact or the checkpoint has not yet been - uploaded. - - Examples: - >>> # schedule run - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> - >>> # wait until run completed - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): - >>> pass - >>> - >>> # get checkpoint read_url - >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) - >>> checkpoint_read_url = client.get_compute_worker_run_checkpoint_url(run=run) - - """ - artifact = self._get_artifact_by_type( - artifact_type=DockerRunArtifactType.CHECKPOINT, run=run - ) - read_url = self._compute_worker_api.get_docker_run_artifact_read_url_by_id( - run_id=run.id, artifact_id=artifact.id - ) - return read_url diff --git a/lightly/api/api_workflow_client.py b/lightly/api/api_workflow_client.py deleted file mode 100644 index 7033ef803..000000000 --- a/lightly/api/api_workflow_client.py +++ /dev/null @@ -1,293 +0,0 @@ -import os -import platform -import warnings -from io import IOBase -from typing import * - -import requests -from requests import Response -from urllib3.exceptions import HTTPError - -from lightly.__init__ import __version__ -from lightly.api import _version_checking, utils -from lightly.api.api_workflow_artifacts import _ArtifactsMixin -from lightly.api.api_workflow_collaboration import _CollaborationMixin -from lightly.api.api_workflow_compute_worker import _ComputeWorkerMixin -from lightly.api.api_workflow_datasets import _DatasetsMixin -from lightly.api.api_workflow_datasources import _DatasourcesMixin -from lightly.api.api_workflow_download_dataset import _DownloadDatasetMixin -from lightly.api.api_workflow_export import _ExportDatasetMixin -from lightly.api.api_workflow_predictions import _PredictionsMixin -from lightly.api.api_workflow_selection import _SelectionMixin -from lightly.api.api_workflow_tags import _TagsMixin -from lightly.api.api_workflow_upload_embeddings import _UploadEmbeddingsMixin -from lightly.api.api_workflow_upload_metadata import _UploadCustomMetadataMixin -from lightly.api.swagger_api_client import LightlySwaggerApiClient -from lightly.api.utils import DatasourceType -from lightly.openapi_generated.swagger_client.api import ( - CollaborationApi, - DatasetsApi, - DatasourcesApi, - DockerApi, - EmbeddingsApi, - JobsApi, - MappingsApi, - MetaDataConfigurationsApi, - PredictionsApi, - QuotaApi, - SamplesApi, - SamplingsApi, - ScoresApi, - TagsApi, -) -from lightly.openapi_generated.swagger_client.models import Creator, DatasetData -from lightly.openapi_generated.swagger_client.rest import ApiException -from lightly.utils import reordering - -# Env variable for server side encryption on S3 -LIGHTLY_S3_SSE_KMS_KEY = "LIGHTLY_S3_SSE_KMS_KEY" - - -class ApiWorkflowClient( - _UploadEmbeddingsMixin, - _SelectionMixin, - _DownloadDatasetMixin, - _DatasetsMixin, - _UploadCustomMetadataMixin, - _TagsMixin, - _DatasourcesMixin, - _ComputeWorkerMixin, - _CollaborationMixin, - _PredictionsMixin, - _ArtifactsMixin, - _ExportDatasetMixin, -): - """Provides a uniform interface to communicate with the Lightly API. - - The APIWorkflowClient is used to communicate with the Lightly API. The client - can run also more complex workflows which include multiple API calls at once. - - The client can be used in combination with the active learning agent. - - Args: - token: - The token of the user. If it is not passed in during initialization, the token - will be read from the environment variable LIGHTLY_TOKEN. - For further information on how to get a token, - see: https://docs.lightly.ai/docs/install-lightly#api-token - dataset_id: - The id of the dataset. If it is not set, but used by a workflow, the last - modfied dataset is taken by default. - embedding_id: - The id of the embedding to use. If it is not set, but used by a workflow, - the newest embedding is taken by default - creator: - Creator passed to API requests. - """ - - def __init__( - self, - token: Optional[str] = None, - dataset_id: Optional[str] = None, - embedding_id: Optional[str] = None, - creator: str = Creator.USER_PIP, - ): - try: - if not _version_checking.is_compatible_version(__version__): - warnings.warn( - UserWarning( - ( - f"Incompatible version of lightly pip package. " - f"Please upgrade to the latest version " - f"to be able to access the api." - ) - ) - ) - except ( - # Error if version compare fails. - ValueError, - # Any error by API client if status not in [200, 299]. - ApiException, - # Any error by urllib3 from within API client. Happens for failed requests - # that are not handled by API client. For example if there is no internet - # connection or a timeout. - HTTPError, - ): - pass - - configuration = utils.get_api_client_configuration(token=token) - self.api_client = LightlySwaggerApiClient(configuration=configuration) - self.api_client.user_agent = f"Lightly/{__version__} ({platform.system()}/{platform.release()}; {platform.platform()}; {platform.processor()};) python/{platform.python_version()}" - - self.token = configuration.api_key["ApiKeyAuth"] - if dataset_id is not None: - self._dataset_id = dataset_id - if embedding_id is not None: - self.embedding_id = embedding_id - self._creator = creator - - self._collaboration_api = CollaborationApi(api_client=self.api_client) - self._compute_worker_api = DockerApi(api_client=self.api_client) - self._datasets_api = DatasetsApi(api_client=self.api_client) - self._datasources_api = DatasourcesApi(api_client=self.api_client) - self._selection_api = SamplingsApi(api_client=self.api_client) - self._jobs_api = JobsApi(api_client=self.api_client) - self._tags_api = TagsApi(api_client=self.api_client) - self._embeddings_api = EmbeddingsApi(api_client=self.api_client) - self._mappings_api = MappingsApi(api_client=self.api_client) - self._scores_api = ScoresApi(api_client=self.api_client) - self._samples_api = SamplesApi(api_client=self.api_client) - self._quota_api = QuotaApi(api_client=self.api_client) - self._metadata_configurations_api = MetaDataConfigurationsApi( - api_client=self.api_client - ) - self._predictions_api = PredictionsApi(api_client=self.api_client) - - @property - def dataset_id(self) -> str: - """The current dataset ID. - - Future requests with the client will automatically use this dataset ID. - If the dataset ID is set, it is returned. Otherwise, the ID of the - last modified dataset is selected. - """ - try: - return self._dataset_id - except AttributeError: - all_datasets: List[DatasetData] = self.get_datasets() - datasets_sorted = sorted( - all_datasets, key=lambda dataset: dataset.last_modified_at - ) - last_modified_dataset = datasets_sorted[-1] - self._dataset_id = last_modified_dataset.id - warnings.warn( - UserWarning( - f"Dataset has not been specified, " - f"taking the last modified dataset {last_modified_dataset.name} as default dataset." - ) - ) - return self._dataset_id - - @dataset_id.setter - def dataset_id(self, dataset_id: str) -> None: - """Sets the current dataset ID for the client. - - Args: - dataset_id: - The new dataset id. - - Raises: - ValueError if the dataset does not exist. - """ - if not self.dataset_exists(dataset_id): - raise ValueError( - f"A dataset with the id {dataset_id} does not exist on the web" - f"platform." - ) - self._dataset_id = dataset_id - - def _order_list_by_filenames( - self, filenames_for_list: List[str], list_to_order: List[object] - ) -> List[object]: - """Orders a list such that it is in the order of the filenames specified on the server. - - Args: - filenames_for_list: - The filenames of samples in a specific order - list_to_order: - Some values belonging to the samples - - Returns: - The list reordered. - The same reorder applied on the filenames_for_list would put them - in the order of the filenames in self.filenames_on_server. - every filename in self.filenames_on_server must be in the - filenames_for_list. - - """ - filenames_on_server = self.get_filenames() - list_ordered = reordering.sort_items_by_keys( - filenames_for_list, list_to_order, filenames_on_server - ) - return list_ordered - - def get_filenames(self) -> List[str]: - """Downloads the list of filenames from the server. - - This is an expensive operation, especially for large datasets. - - Returns: - Names of files in the current dataset. - - :meta private: # Skip docstring generation - """ - filenames_on_server = list( - utils.paginate_endpoint( - self._mappings_api.get_sample_mappings_by_dataset_id, - page_size=25000, - dataset_id=self.dataset_id, - field="fileName", - ) - ) - return filenames_on_server - - def upload_file_with_signed_url( - self, - file: Union[IOBase, None], - signed_write_url: str, - headers: Optional[Dict] = None, - session: Optional[requests.Session] = None, - ) -> Response: - """Uploads a file to a url via a put request. - - This method cannot upload 0 bytes files due to a limitation of the requests - library. Set file to None to upload an empty file. - - Args: - file: - The file to upload. If None, an empty file is uploaded. - signed_write_url: - The url to upload the file to. As no authorization is used, - the url must be a signed write url. - headers: - Specific headers for the request. Defaults to None. - session: - Optional requests session used to upload the file. - - Returns: - The response of the put request. - - :meta private: # Skip docstring generation - """ - - # check to see if server side encryption for S3 is desired - # see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html - # see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html - lightly_s3_sse_kms_key = os.environ.get(LIGHTLY_S3_SSE_KMS_KEY, "").strip() - # Only set s3 related headers when we are talking with s3 - if ( - utils.get_signed_url_destination(signed_write_url) == DatasourceType.S3 - and lightly_s3_sse_kms_key - ): - if headers is None: - headers = {} - # don't override previously set SSE - if "x-amz-server-side-encryption" not in headers: - if lightly_s3_sse_kms_key.lower() == "true": - # enable SSE with the key of amazon - headers["x-amz-server-side-encryption"] = "AES256" - else: - # enable SSE with specific customer KMS key - headers["x-amz-server-side-encryption"] = "aws:kms" - headers[ - "x-amz-server-side-encryption-aws-kms-key-id" - ] = lightly_s3_sse_kms_key - - # start requests session and make put request - sess = session or requests - if headers is not None: - response = sess.put(signed_write_url, data=file, headers=headers) - else: - response = sess.put(signed_write_url, data=file) - response.raise_for_status() - return response diff --git a/lightly/api/api_workflow_collaboration.py b/lightly/api/api_workflow_collaboration.py deleted file mode 100644 index 82258d9fb..000000000 --- a/lightly/api/api_workflow_collaboration.py +++ /dev/null @@ -1,78 +0,0 @@ -from typing import List - -from lightly.openapi_generated.swagger_client.models import ( - SharedAccessConfigCreateRequest, - SharedAccessConfigData, - SharedAccessType, -) - - -class _CollaborationMixin: - def share_dataset_only_with(self, dataset_id: str, user_emails: List[str]) -> None: - """Shares a dataset with a list of users. - - This method overwrites the list of users that have had access to the dataset - before. If you want to add someone new to the list, make sure you first fetch - the list of users with access and include them in the `user_emails` - parameter. - - Args: - dataset_id: - ID of the dataset to be shared. - user_emails: - List of email addresses of users who will get access to the dataset. - - Examples: - >>> # share a dataset with a user - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=["user@something.com"]) - >>> - >>> # share dataset with a user while keep sharing it with previous users - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> user_emails = client.get_shared_users(dataset_id="MY_DATASET_ID") - >>> user_emails.append("additional_user2@something.com") - >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=user_emails) - >>> - >>> # revoke access to all users - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=[]) - """ - body = SharedAccessConfigCreateRequest( - access_type=SharedAccessType.WRITE, users=user_emails, creator=self._creator - ) - self._collaboration_api.create_or_update_shared_access_config_by_dataset_id( - shared_access_config_create_request=body, dataset_id=dataset_id - ) - - def get_shared_users(self, dataset_id: str) -> List[str]: - """Fetches a list of users that have access to the dataset. - - Args: - dataset_id: - Dataset ID. - - Returns: - List of email addresses of users that have write access to the dataset. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.get_shared_users(dataset_id="MY_DATASET_ID") - >>> ["user@something.com"] - """ - - access_configs: List[ - SharedAccessConfigData - ] = self._collaboration_api.get_shared_access_configs_by_dataset_id( - dataset_id=dataset_id - ) - user_emails = [] - - # iterate through configs and find first WRITE config - # we use the same hard rule in the frontend to communicate with the API - # as we currently only support WRITE access - for access_config in access_configs: - if access_config.access_type == SharedAccessType.WRITE: - user_emails.extend(access_config.users) - break - - return user_emails diff --git a/lightly/api/api_workflow_compute_worker.py b/lightly/api/api_workflow_compute_worker.py deleted file mode 100644 index 5ae64516e..000000000 --- a/lightly/api/api_workflow_compute_worker.py +++ /dev/null @@ -1,704 +0,0 @@ -import copy -import dataclasses -import difflib -import json -import time -from functools import partial -from typing import Any, Callable, Dict, Iterator, List, Optional, Type, TypeVar, Union - -from lightly.api import utils -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.models import ( - CreateDockerWorkerRegistryEntryRequest, - DockerRunData, - DockerRunScheduledCreateRequest, - DockerRunScheduledData, - DockerRunScheduledPriority, - DockerRunScheduledState, - DockerRunState, - DockerWorkerConfigOmniVXCreateRequest, - DockerWorkerConfigV3Lightly, - DockerWorkerConfigV4, - DockerWorkerConfigV4Docker, - DockerWorkerRegistryEntryData, - DockerWorkerType, - SelectionConfigV4, - SelectionConfigV4Entry, - SelectionConfigV4EntryInput, - SelectionConfigV4EntryStrategy, - TagData, -) -from lightly.openapi_generated.swagger_client.rest import ApiException - -STATE_SCHEDULED_ID_NOT_FOUND = "CANCELED_OR_NOT_EXISTING" - - -class InvalidConfigurationError(RuntimeError): - pass - - -@dataclasses.dataclass -class ComputeWorkerRunInfo: - """Information about a Lightly Worker run. - - Attributes: - state: - The state of the Lightly Worker run. - message: - The last message of the Lightly Worker run. - """ - - state: Union[ - DockerRunState, DockerRunScheduledState.OPEN, STATE_SCHEDULED_ID_NOT_FOUND - ] - message: str - - def in_end_state(self) -> bool: - """Checks whether the Lightly Worker run has ended.""" - return self.state in [ - DockerRunState.COMPLETED, - DockerRunState.ABORTED, - DockerRunState.FAILED, - DockerRunState.CRASHED, - STATE_SCHEDULED_ID_NOT_FOUND, - ] - - def ended_successfully(self) -> bool: - """Checkes whether the Lightly Worker run ended successfully or failed. - - Returns: - A boolean value indicating if the Lightly Worker run was successful. - True if the run was successful. - - Raises: - ValueError: - If the Lightly Worker run is still in progress. - """ - if not self.in_end_state(): - raise ValueError("Lightly Worker run is still in progress.") - return self.state == DockerRunState.COMPLETED - - -class _ComputeWorkerMixin: - def register_compute_worker( - self, name: str = "Default", labels: Optional[List[str]] = None - ) -> str: - """Registers a new Lightly Worker. - - The ID of the registered worker will be returned. If a worker with the same - name already exists, the ID of the existing worker is returned. - - Args: - name: - The name of the Lightly Worker. - labels: - The labels of the Lightly Worker. - See our docs for more information regarding the labels parameter: - https://docs.lightly.ai/docs/assign-scheduled-runs-to-specific-workers - - Returns: - ID of the registered Lightly Worker. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> worker_id = client.register_compute_worker(name="my-worker", labels=["worker-label"]) - >>> worker_id - '64709eac61e9ce68180a6529' - """ - if labels is None: - labels = [] - request = CreateDockerWorkerRegistryEntryRequest( - name=name, - worker_type=DockerWorkerType.FULL, - labels=labels, - creator=self._creator, - ) - response = self._compute_worker_api.register_docker_worker(request) - return response.id - - def get_compute_worker_ids(self) -> List[str]: - """Fetches the IDs of all registered Lightly Workers. - - Returns: - A list of worker IDs. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> worker_ids = client.get_compute_worker_ids() - >>> worker_ids - ['64709eac61e9ce68180a6529', '64709f8f61e9ce68180a652a'] - """ - entries = self._compute_worker_api.get_docker_worker_registry_entries() - return [entry.id for entry in entries] - - def get_compute_workers(self) -> List[DockerWorkerRegistryEntryData]: - """Fetches details of all registered Lightly Workers. - - Returns: - A list of Lightly Worker details. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> workers = client.get_compute_workers() - >>> workers - [{'created_at': 1685102336056, - 'docker_version': '2.6.0', - 'id': '64709eac61e9ce68180a6529', - 'labels': [], - ... - }] - """ - entries: list[ - DockerWorkerRegistryEntryData - ] = self._compute_worker_api.get_docker_worker_registry_entries() - return entries - - def delete_compute_worker(self, worker_id: str) -> None: - """Removes a Lightly Worker. - - Args: - worker_id: - ID of the worker to be removed. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> worker_ids = client.get_compute_worker_ids() - >>> worker_ids - ['64709eac61e9ce68180a6529'] - >>> client.delete_compute_worker(worker_id="64709eac61e9ce68180a6529") - >>> client.get_compute_worker_ids() - [] - """ - self._compute_worker_api.delete_docker_worker_registry_entry_by_id(worker_id) - - def create_compute_worker_config( - self, - worker_config: Optional[Dict[str, Any]] = None, - lightly_config: Optional[Dict[str, Any]] = None, - selection_config: Optional[Union[Dict[str, Any], SelectionConfigV4]] = None, - ) -> str: - """Creates a new configuration for a Lightly Worker run. - - See our docs for more information regarding the different configurations: - https://docs.lightly.ai/docs/all-configuration-options - - Args: - worker_config: - Lightly Worker configuration. - lightly_config: - Lightly configuration. - selection_config: - Selection configuration. - - Returns: - The ID of the created config. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> selection_config = { - ... "n_samples": 3, - ... "strategies": [ - ... { - ... "input": {"type": "RANDOM", "random_seed": 42}, - ... "strategy": {"type": "WEIGHTS"}, - ... } - ... ], - ... } - >>> config_id = client.create_compute_worker_config( - ... selection_config=selection_config, - ... ) - - :meta private: # Skip docstring generation - """ - if isinstance(selection_config, dict): - selection = selection_config_from_dict(cfg=selection_config) - else: - selection = selection_config - - if worker_config is not None: - worker_config_cc = _config_to_camel_case(cfg=worker_config) - deserialize_worker_config = _get_deserialize( - api_client=self.api_client, - klass=DockerWorkerConfigV4Docker, - ) - docker = deserialize_worker_config(worker_config_cc) - _validate_config(cfg=worker_config, obj=docker) - else: - docker = None - - if lightly_config is not None: - lightly_config_cc = _config_to_camel_case(cfg=lightly_config) - deserialize_lightly_config = _get_deserialize( - api_client=self.api_client, - klass=DockerWorkerConfigV3Lightly, - ) - lightly = deserialize_lightly_config(lightly_config_cc) - _validate_config(cfg=lightly_config, obj=lightly) - else: - lightly = None - - config = DockerWorkerConfigV4( - worker_type=DockerWorkerType.FULL, - docker=docker, - lightly=lightly, - selection=selection, - ) - request = DockerWorkerConfigOmniVXCreateRequest.from_dict( - { - "version": "V4", - "config": config.to_dict(by_alias=True), - "creator": self._creator, - } - ) - response = self._compute_worker_api.create_docker_worker_config_vx(request) - return response.id - - def schedule_compute_worker_run( - self, - worker_config: Optional[Dict[str, Any]] = None, - lightly_config: Optional[Dict[str, Any]] = None, - selection_config: Optional[Union[Dict[str, Any], SelectionConfigV4]] = None, - priority: str = DockerRunScheduledPriority.MID, - runs_on: Optional[List[str]] = None, - ) -> str: - """Schedules a run with the given configurations. - - See our docs for more information regarding the different configurations: - https://docs.lightly.ai/docs/all-configuration-options - - Args: - worker_config: - Lightly Worker configuration. - lightly_config: - Lightly configuration. - selection_config: - Selection configuration. - runs_on: - The required labels the Lightly Worker must have to take the job. - See our docs for more information regarding the runs_on paramter: - https://docs.lightly.ai/docs/assign-scheduled-runs-to-specific-workers - - Returns: - The id of the scheduled run. - - Raises: - ApiException: - If the API call returns a status code other than 200. - 400: Missing or invalid parameters - 402: Insufficient plan - 403: Not authorized for this resource or invalid token - 404: Resource (dataset or config) not found - 422: Missing or invalid file in datasource - InvalidConfigError: - If one of the configurations is invalid. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> selection_config = {...} - >>> worker_labels = ["worker-label"] - >>> run_id = client.schedule_compute_worker_run( - ... selection_config=selection_config, runs_on=worker_labels - ... ) - """ - if runs_on is None: - runs_on = [] - config_id = self.create_compute_worker_config( - worker_config=worker_config, - lightly_config=lightly_config, - selection_config=selection_config, - ) - request = DockerRunScheduledCreateRequest( - config_id=config_id, - priority=priority, - runs_on=runs_on, - creator=self._creator, - ) - response = self._compute_worker_api.create_docker_run_scheduled_by_dataset_id( - docker_run_scheduled_create_request=request, - dataset_id=self.dataset_id, - ) - return response.id - - def get_compute_worker_runs_iter( - self, - dataset_id: Optional[str] = None, - ) -> Iterator[DockerRunData]: - """Returns an iterator over all Lightly Worker runs for the user. - - Args: - dataset_id: - Target dataset ID. Optional. If set, only runs with the given dataset - will be returned. - - Returns: - Runs iterator. - - """ - if dataset_id is not None: - return utils.paginate_endpoint( - self._compute_worker_api.get_docker_runs_query_by_dataset_id, - dataset_id=dataset_id, - ) - else: - return utils.paginate_endpoint( - self._compute_worker_api.get_docker_runs, - ) - - def get_compute_worker_runs( - self, - dataset_id: Optional[str] = None, - ) -> List[DockerRunData]: - """Fetches all Lightly Worker runs for the user. - - Args: - dataset_id: - Target dataset ID. Optional. If set, only runs with the given dataset - will be returned. - - Returns: - Runs sorted by creation time from the oldest to the latest. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.get_compute_worker_runs() - [{'artifacts': [...], - 'config_id': '6470a16461e9ce68180a6530', - 'created_at': 1679479418110, - 'dataset_id': '6470a36361e9ce68180a6531', - 'docker_version': '2.6.0', - ... - }] - """ - runs: List[DockerRunData] = list(self.get_compute_worker_runs_iter(dataset_id)) - sorted_runs = sorted(runs, key=lambda run: run.created_at or -1) - return sorted_runs - - def get_compute_worker_run(self, run_id: str) -> DockerRunData: - """Fetches a Lightly Worker run. - - Args: - run_id: Run ID. - - Returns: - Details of the Lightly Worker run. - - Raises: - ApiException: - If no run with the given ID exists. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.get_compute_worker_run(run_id="6470a20461e9ce68180a6530") - {'artifacts': [...], - 'config_id': '6470a16461e9ce68180a6530', - 'created_at': 1679479418110, - 'dataset_id': '6470a36361e9ce68180a6531', - 'docker_version': '2.6.0', - ... - } - """ - return self._compute_worker_api.get_docker_run_by_id(run_id=run_id) - - def get_compute_worker_run_from_scheduled_run( - self, - scheduled_run_id: str, - ) -> DockerRunData: - """Fetches a Lightly Worker run given its scheduled run ID. - - Args: - scheduled_run_id: Scheduled run ID. - - Returns: - Details of the Lightly Worker run. - - Raises: - ApiException: - If no run with the given scheduled run ID exists or if the scheduled - run is not yet picked up by a worker. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.get_compute_worker_run_from_scheduled_run(scheduled_run_id="646f338a8a5613b57d8b73a1") - {'artifacts': [...], - 'config_id': '6470a16461e9ce68180a6530', - 'created_at': 1679479418110, - 'dataset_id': '6470a36361e9ce68180a6531', - 'docker_version': '2.6.0', - ... - } - """ - return self._compute_worker_api.get_docker_run_by_scheduled_id( - scheduled_id=scheduled_run_id - ) - - def get_scheduled_compute_worker_runs( - self, - state: Optional[str] = None, - ) -> List[DockerRunScheduledData]: - """Returns a list of scheduled Lightly Worker runs with the current dataset. - - Args: - state: - DockerRunScheduledState value. If specified, then only runs in the given - state are returned. If omitted, then runs which have not yet finished - (neither 'DONE' nor 'CANCELED') are returned. Valid states are 'OPEN', - 'LOCKED', 'DONE', and 'CANCELED'. - - Returns: - A list of scheduled Lightly Worker runs. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.get_scheduled_compute_worker_runs(state="OPEN") - [{'config_id': '646f34608a5613b57d8b73cc', - 'created_at': 1685009508254, - 'dataset_id': '6470a36361e9ce68180a6531', - 'id': '646f338a8a5613b57d8b73a1', - 'last_modified_at': 1685009542667, - 'owner': '643d050b8bcb91967ded65df', - 'priority': 'MID', - 'runs_on': ['worker-label'], - 'state': 'OPEN'}] - """ - if state is not None: - return self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( - dataset_id=self.dataset_id, - state=state, - ) - return self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( - dataset_id=self.dataset_id, - ) - - def _get_scheduled_run_by_id(self, scheduled_run_id: str) -> DockerRunScheduledData: - """Returns the schedule run data given the id of the scheduled run. - - TODO (MALTE, 09/2022): Have a proper API endpoint for doing this. - Args: - scheduled_run_id: - The ID with which the run was scheduled. - - Returns: - Defails of the scheduled run. - - """ - try: - run: DockerRunScheduledData = next( - run - for run in utils.retry( - lambda: self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( - self.dataset_id - ) - ) - if run.id == scheduled_run_id - ) - return run - except StopIteration: - raise ApiException( - f"No scheduled run found for run with scheduled_run_id='{scheduled_run_id}'." - ) - - def get_compute_worker_run_info( - self, scheduled_run_id: str - ) -> ComputeWorkerRunInfo: - """Returns information about the Lightly Worker run. - - Args: - scheduled_run_id: - ID of the scheduled run. - - Returns: - Details of the Lightly Worker run. - - Examples: - >>> # Scheduled a Lightly Worker run and get its state - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> run_info = client.get_compute_worker_run_info(scheduled_run_id) - >>> print(run_info) - - """ - """ - Because we currently (09/2022) have different Database entries for a ScheduledRun and DockerRun, - the logic is more complicated and covers three cases. - """ - try: - # Case 1: DockerRun exists. - docker_run: DockerRunData = ( - self._compute_worker_api.get_docker_run_by_scheduled_id( - scheduled_id=scheduled_run_id - ) - ) - info = ComputeWorkerRunInfo( - state=docker_run.state, message=docker_run.message - ) - except ApiException: - try: - # Case 2: DockerRun does NOT exist, but ScheduledRun exists. - _ = self._get_scheduled_run_by_id(scheduled_run_id) - info = ComputeWorkerRunInfo( - state=DockerRunScheduledState.OPEN, - message="Waiting for pickup by Lightly Worker. " - "Make sure to start a Lightly Worker connected to your " - "user token to process the job.", - ) - except ApiException: - # Case 3: NEITHER the DockerRun NOR the ScheduledRun exist. - info = ComputeWorkerRunInfo( - state=STATE_SCHEDULED_ID_NOT_FOUND, - message=f"Could not find a job for the given run_id: '{scheduled_run_id}'. " - "The scheduled run does not exist or was canceled before " - "being picked up by a Lightly Worker.", - ) - return info - - def compute_worker_run_info_generator( - self, scheduled_run_id: str - ) -> Iterator[ComputeWorkerRunInfo]: - """Pulls information about a Lightly Worker run continuously. - - Polls the Lightly Worker status every 30s. - If the status changed, an update pops up. - If the Lightly Worker run finished, the generator stops. - - Args: - scheduled_run_id: - The id with which the run was scheduled. - - Returns: - Generator of information about the Lightly Worker run status. - - Examples: - >>> # Scheduled a Lightly Worker run and monitor its state - >>> scheduled_run_id = client.schedule_compute_worker_run(...) - >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id): - >>> print(f"Lightly Worker run is now in state='{run_info.state}' with message='{run_info.message}'") - >>> - - """ - last_run_info = None - while True: - run_info = self.get_compute_worker_run_info( - scheduled_run_id=scheduled_run_id - ) - - # Only yield new run_info - if run_info != last_run_info: - yield run_info - - # Break if the scheduled run is in one of the end states. - if run_info.in_end_state(): - break - - # Wait before polling the state again - time.sleep(30) # Keep this at 30s or larger to prevent rate limiting. - - last_run_info = run_info - - def get_compute_worker_run_tags(self, run_id: str) -> List[TagData]: - """Returns all tags from a run with the current dataset. - - Only returns tags for runs made with Lightly Worker version >=2.4.2. - - Args: - run_id: - Run ID from which to return tags. - - Returns: - List of tags created by the run. The tags are ordered by creation date from - newest to oldest. - - Examples: - >>> # Get filenames from last run. - >>> - >>> from lightly.api import ApiWorkflowClient - >>> client = ApiWorkflowClient( - >>> token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" - >>> ) - >>> tags = client.get_compute_worker_run_tags(run_id="MY_LAST_RUN_ID") - >>> filenames = client.export_filenames_by_tag_name(tag_name=tags[0].name) - - """ - tags = self._compute_worker_api.get_docker_run_tags(run_id=run_id) - tags_in_dataset = [tag for tag in tags if tag.dataset_id == self.dataset_id] - return tags_in_dataset - - -def selection_config_from_dict(cfg: Dict[str, Any]) -> SelectionConfigV4: - """Recursively converts selection config from dict to a SelectionConfigV4 instance.""" - strategies = [] - for entry in cfg.get("strategies", []): - new_entry = copy.deepcopy(entry) - new_entry["input"] = SelectionConfigV4EntryInput(**entry["input"]) - new_entry["strategy"] = SelectionConfigV4EntryStrategy(**entry["strategy"]) - strategies.append(SelectionConfigV4Entry(**new_entry)) - new_cfg = copy.deepcopy(cfg) - new_cfg["strategies"] = strategies - return SelectionConfigV4(**new_cfg) - - -_T = TypeVar("_T") - - -def _get_deserialize( - api_client: ApiClient, - klass: Type[_T], -) -> Callable[[Dict[str, Any]], _T]: - """Returns the deserializer of the ApiClient class for class klass. - - TODO(Philipp, 02/23): We should replace this by our own deserializer which - accepts snake case strings as input. - - The deserializer takes a dictionary and and returns an instance of klass. - - """ - deserialize = getattr(api_client, "_ApiClient__deserialize") - return partial(deserialize, klass=klass) - - -def _config_to_camel_case(cfg: Dict[str, Any]) -> Dict[str, Any]: - """Converts all keys in the cfg dictionary to camelCase.""" - cfg_camel_case = {} - for key, value in cfg.items(): - key_camel_case = _snake_to_camel_case(key) - if isinstance(value, dict): - cfg_camel_case[key_camel_case] = _config_to_camel_case(value) - else: - cfg_camel_case[key_camel_case] = value - return cfg_camel_case - - -def _snake_to_camel_case(snake: str) -> str: - """Converts the snake_case input to camelCase.""" - components = snake.split("_") - return components[0] + "".join(component.title() for component in components[1:]) - - -def _validate_config( - cfg: Optional[Dict[str, Any]], - obj: Any, -) -> None: - """Validates that all keys in cfg are legitimate configuration options. - - Recursively checks if the keys in the cfg dictionary match the attributes of - the DockerWorkerConfigV2Docker/DockerWorkerConfigV2Lightly instances. If not, - suggests a best match. - - Raises: - InvalidConfigurationError: If obj is not a valid config. - - """ - - if cfg is None: - return - - for key, item in cfg.items(): - if not hasattr(obj, key): - possible_options = list(obj.__fields__.keys()) - closest_match = difflib.get_close_matches( - word=key, possibilities=possible_options, n=1, cutoff=0.0 - )[0] - error_msg = ( - f"Option '{key}' does not exist! Did you mean '{closest_match}'?" - ) - raise InvalidConfigurationError(error_msg) - if isinstance(item, dict): - _validate_config(item, getattr(obj, key)) diff --git a/lightly/api/api_workflow_datasets.py b/lightly/api/api_workflow_datasets.py deleted file mode 100644 index 2d670e76c..000000000 --- a/lightly/api/api_workflow_datasets.py +++ /dev/null @@ -1,508 +0,0 @@ -import warnings -from itertools import chain -from typing import Iterator, List, Optional, Set - -from lightly.api import utils -from lightly.openapi_generated.swagger_client.models import ( - CreateEntityResponse, - DatasetCreateRequest, - DatasetData, - DatasetType, -) -from lightly.openapi_generated.swagger_client.rest import ApiException - - -class _DatasetsMixin: - @property - def dataset_type(self) -> str: - """Returns the dataset type of the current dataset.""" - dataset = self._get_current_dataset() - return dataset.type #  type: ignore - - def _get_current_dataset(self) -> DatasetData: - """Returns the dataset with id == self.dataset_id.""" - return self.get_dataset_by_id(dataset_id=self.dataset_id) - - def dataset_exists(self, dataset_id: str) -> bool: - """Checks if a dataset exists. - - Args: - dataset_id: Dataset ID. - - Returns: - True if the dataset exists and False otherwise. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> dataset_id = client.dataset_id - >>> client.dataset_exists(dataset_id=dataset_id) - True - """ - try: - self.get_dataset_by_id(dataset_id) - return True - except ApiException as exception: - if exception.status == 404: # Not Found - return False - raise exception - - def dataset_name_exists( - self, dataset_name: str, shared: Optional[bool] = False - ) -> bool: - """Checks if a dataset with the given name exists. - - There can be multiple datasets with the same name accessible to the current - user. This can happen if either: - * A dataset has been explicitly shared with the user - * The user has access to team datasets - The `shared` flag controls whether these datasets are checked. - - Args: - dataset_name: - Name of the dataset. - shared: - * If False (default), checks only datasets owned by the user. - * If True, checks datasets which have been shared with the user, - including team datasets. Excludes user's own datasets. - * If None, checks all datasets the users has access to. - - Returns: - A boolean value indicating whether any dataset with the given name exists. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> client.dataset_name_exists(dataset_name="your-dataset-name") - True - """ - return bool(self.get_datasets_by_name(dataset_name=dataset_name, shared=shared)) - - def get_dataset_by_id(self, dataset_id: str) -> DatasetData: - """Fetches a dataset by ID. - - Args: - dataset_id: Dataset ID. - - Returns: - The dataset with the given dataset id. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> dataset_id = client.dataset_id - >>> client.get_dataset_by_id(dataset_id=dataset_id) - {'created_at': 1685009504596, - 'datasource_processed_until_timestamp': 1685009513, - 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], - 'id': '646f34608a5613b57d8b73c9', - 'img_type': 'full', - 'type': 'Images', - ...} - """ - dataset: DatasetData = self._datasets_api.get_dataset_by_id(dataset_id) - return dataset - - def get_datasets_by_name( - self, - dataset_name: str, - shared: Optional[bool] = False, - ) -> List[DatasetData]: - """Fetches datasets by name. - - There can be multiple datasets with the same name accessible to the current - user. This can happen if either: - * A dataset has been explicitly shared with the user - * The user has access to team datasets - The `shared` flag controls whether these datasets are returned. - - Args: - dataset_name: - Name of the target dataset. - shared: - * If False (default), returns only datasets owned by the user. In this - case at most one dataset will be returned. - * If True, returns datasets which have been shared with the user, - including team datasets. Excludes user's own datasets. Can return - multiple datasets. - * If None, returns all datasets the users has access to. Can return - multiple datasets. - - Returns: - A list of datasets that match the name. If no datasets with the name exist, - an empty list is returned. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> client.get_datasets_by_name(dataset_name="your-dataset-name") - [{'created_at': 1685009504596, - 'datasource_processed_until_timestamp': 1685009513, - 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], - 'id': '646f34608a5613b57d8b73c9', - 'img_type': 'full', - 'type': 'Images', - ...}] - >>> - >>> # Non-existent dataset - >>> client.get_datasets_by_name(dataset_name="random-name") - [] - """ - datasets: List[DatasetData] = [] - if not shared or shared is None: - datasets.extend( - list( - utils.paginate_endpoint( - self._datasets_api.get_datasets_query_by_name, - dataset_name=dataset_name, - exact=True, - shared=False, - ) - ) - ) - if shared or shared is None: - datasets.extend( - list( - utils.paginate_endpoint( - self._datasets_api.get_datasets_query_by_name, - dataset_name=dataset_name, - exact=True, - shared=True, - ) - ) - ) - datasets.extend( - list( - utils.paginate_endpoint( - self._datasets_api.get_datasets_query_by_name, - dataset_name=dataset_name, - exact=True, - get_assets_of_team=True, - ) - ) - ) - - # De-duplicate datasets because results from shared=True and - # those from get_assets_of_team=True might overlap - dataset_ids: Set[str] = set() - filtered_datasets: List[DatasetData] = [] - for dataset in datasets: - if dataset.id not in dataset_ids: - dataset_ids.add(dataset.id) - filtered_datasets.append(dataset) - - return filtered_datasets - - def get_datasets_iter( - self, shared: Optional[bool] = False - ) -> Iterator[DatasetData]: - """Returns an iterator over all datasets owned by the current user. - - There can be multiple datasets with the same name accessible to the current - user. This can happen if either: - * A dataset has been explicitly shared with the user - * The user has access to team datasets - The `shared` flag controls whether these datasets are returned. - - Args: - shared: - * If False (default), returns only datasets owned by the user. In this - case at most one dataset will be returned. - * If True, returns datasets which have been shared with the user, - including team datasets. Excludes user's own datasets. Can return - multiple datasets. - * If None, returns all datasets the users has access to. Can return - multiple datasets. - - Returns: - An iterator over datasets owned by the current user. - """ - dataset_iterable: Iterator[DatasetData] = (_ for _ in ()) - if not shared or shared is None: - dataset_iterable = utils.paginate_endpoint( - self._datasets_api.get_datasets, - shared=False, - ) - if shared or shared is None: - dataset_iterable = chain( - dataset_iterable, - utils.paginate_endpoint( - self._datasets_api.get_datasets, - shared=True, - ), - ) - dataset_iterable = chain( - dataset_iterable, - utils.paginate_endpoint( - self._datasets_api.get_datasets, - get_assets_of_team=True, - ), - ) - - # De-duplicate datasets because results from shared=True and - # those from get_assets_of_team=True might overlap - dataset_ids: Set[str] = set() - for dataset in dataset_iterable: - if dataset.id not in dataset_ids: - dataset_ids.add(dataset.id) - yield dataset - - def get_datasets(self, shared: Optional[bool] = False) -> List[DatasetData]: - """Returns all datasets owned by the current user. - - There can be multiple datasets with the same name accessible to the current - user. This can happen if either: - * A dataset has been explicitly shared with the user - * The user has access to team datasets - The `shared` flag controls whether these datasets are returned. - - Args: - shared: - * If False (default), returns only datasets owned by the user. In this - case at most one dataset will be returned. - * If True, returns datasets which have been shared with the user, - including team datasets. Excludes user's own datasets. Can return - multiple datasets. - * If None, returns all datasets the users has access to. Can return - multiple datasets. - - Returns: - A list of datasets owned by the current user. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> client.get_datasets() - [{'created_at': 1685009504596, - 'datasource_processed_until_timestamp': 1685009513, - 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], - 'id': '646f34608a5613b57d8b73c9', - 'img_type': 'full', - 'type': 'Images', - ...}] - """ - return list(self.get_datasets_iter(shared)) - - def get_all_datasets(self) -> List[DatasetData]: - """Returns all datasets the user has access to. - - DEPRECATED in favour of get_datasets(shared=None) and will be removed in the - future. - """ - warnings.warn( - "get_all_datasets() is deprecated in favour of get_datasets(shared=None) " - "and will be removed in the future.", - DeprecationWarning, - ) - owned_datasets = self.get_datasets(shared=None) - return owned_datasets - - def set_dataset_id_by_name( - self, dataset_name: str, shared: Optional[bool] = False - ) -> None: - """Sets the dataset ID in the API client given the name of the desired dataset. - - There can be multiple datasets with the same name accessible to the current - user. This can happen if either: - * A dataset has been explicitly shared with the user - * The user has access to team datasets - The `shared` flag controls whether these datasets are also checked. If multiple - datasets with the given name are found, the API client uses the ID of the first - dataset and prints a warning message. - - Args: - dataset_name: - The name of the target dataset. - shared: - * If False (default), checks only datasets owned by the user. - * If True, returns datasets which have been shared with the user, - including team datasets. Excludes user's own datasets. There can be - multiple candidate datasets. - * If None, returns all datasets the users has access to. There can be - multiple candidate datasets. - - Raises: - ValueError: - If no dataset with the given name exists. - - Examples: - >>> # A new session. Dataset "old-dataset" was created before. - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.set_dataset_id_by_name("old-dataset") - """ - datasets = self.get_datasets_by_name(dataset_name=dataset_name, shared=shared) - if not datasets: - raise ValueError( - f"A dataset with the name '{dataset_name}' does not exist on the " - f"Lightly Platform. Please create it first." - ) - self._dataset_id = datasets[0].id - if len(datasets) > 1: - msg = ( - f"Found {len(datasets)} datasets with the name '{dataset_name}'. Their " - f"ids are {[dataset.id for dataset in datasets]}. " - f"The dataset_id of the client was set to '{self._dataset_id}'. " - ) - if shared or shared is None: - msg += ( - f"We noticed that you set shared={shared} which also retrieves " - f"datasets shared with you. Set shared=False to only consider " - "datasets you own." - ) - warnings.warn(msg) - - def create_dataset( - self, - dataset_name: str, - dataset_type: str = DatasetType.IMAGES, - ) -> None: - """Creates a dataset on the Lightly Platform. - - The dataset_id of the created dataset is stored in the client.dataset_id - attribute and all further requests with the client will use the created dataset - by default. - - Args: - dataset_name: - The name of the dataset to be created. - dataset_type: - The type of the dataset. We recommend to use the API provided constants - `DatasetType.IMAGES` and `DatasetType.VIDEOS`. - - Raises: - ValueError: If a dataset with dataset_name already exists. - - Examples: - >>> from lightly.api import ApiWorkflowClient - >>> from lightly.openapi_generated.swagger_client.models import DatasetType - >>> - >>> client = ApiWorkflowClient(token="YOUR_TOKEN") - >>> client.create_dataset('your-dataset-name', dataset_type=DatasetType.IMAGES) - >>> - >>> # or to work with videos - >>> client.create_dataset('your-dataset-name', dataset_type=DatasetType.VIDEOS) - >>> - >>> # retrieving dataset_id of the created dataset - >>> dataset_id = client.dataset_id - >>> - >>> # future client requests use the created dataset by default - >>> client.dataset_type - 'Videos' - """ - - if self.dataset_name_exists(dataset_name=dataset_name): - raise ValueError( - f"A dataset with the name '{dataset_name}' already exists! Please use " - f"the `set_dataset_id_by_name()` method instead if you intend to reuse " - f"an existing dataset." - ) - self._create_dataset_without_check_existing( - dataset_name=dataset_name, - dataset_type=dataset_type, - ) - - def _create_dataset_without_check_existing( - self, dataset_name: str, dataset_type: str - ) -> None: - """Creates a dataset on the Lightly Platform. - - No checking if a dataset with such a name already exists is performed. - - Args: - dataset_name: - The name of the dataset to be created. - dataset_type: - The type of the dataset. We recommend to use the API provided - constants `DatasetType.IMAGES` and `DatasetType.VIDEOS`. - - """ - body = DatasetCreateRequest( - name=dataset_name, type=dataset_type, creator=self._creator - ) - response: CreateEntityResponse = self._datasets_api.create_dataset( - dataset_create_request=body - ) - self._dataset_id = response.id - - def create_new_dataset_with_unique_name( - self, - dataset_basename: str, - dataset_type: str = DatasetType.IMAGES, - ) -> None: - """Creates a new dataset on the Lightly Platform. - - If a dataset with the specified name already exists, - the name is suffixed by a counter value. - - Args: - dataset_basename: - The name of the dataset to be created. - dataset_type: - The type of the dataset. We recommend to use the API provided - constants `DatasetType.IMAGES` and `DatasetType.VIDEOS`. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Create a dataset with a brand new name. - >>> client.create_new_dataset_with_unique_name("new-dataset") - >>> client.get_dataset_by_id(client.dataset_id) - {'id': '6470abef4f0eb7e635c30954', - 'name': 'new-dataset', - ...} - >>> - >>> # Create another dataset with the same name. This time, the - >>> # new dataset should have a suffix `_1`. - >>> client.create_new_dataset_with_unique_name("new-dataset") - >>> client.get_dataset_by_id(client.dataset_id) - {'id': '6470ac194f0eb7e635c30990', - 'name': 'new-dataset_1', - ...} - - """ - if not self.dataset_name_exists(dataset_name=dataset_basename): - self._create_dataset_without_check_existing( - dataset_name=dataset_basename, - dataset_type=dataset_type, - ) - else: - existing_datasets = list( - utils.paginate_endpoint( - self._datasets_api.get_datasets_query_by_name, - dataset_name=dataset_basename, - exact=False, - shared=False, - ) - ) - existing_dataset_names = {dataset.name for dataset in existing_datasets} - counter = 1 - dataset_name = f"{dataset_basename}_{counter}" - while dataset_name in existing_dataset_names: - counter += 1 - dataset_name = f"{dataset_basename}_{counter}" - self._create_dataset_without_check_existing( - dataset_name=dataset_name, - dataset_type=dataset_type, - ) - - def delete_dataset_by_id(self, dataset_id: str) -> None: - """Deletes a dataset on the Lightly Platform. - - Args: - dataset_id: - The ID of the dataset to be deleted. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) - >>> dataset_id = client.dataset_id - >>> client.dataset_exists(dataset_id=dataset_id) - True - >>> - >>> # Delete the dataset - >>> client.delete_dataset_by_id(dataset_id=dataset_id) - >>> client.dataset_exists(dataset_id=dataset_id) - False - """ - self._datasets_api.delete_dataset_by_id(dataset_id=dataset_id) - del self._dataset_id diff --git a/lightly/api/api_workflow_datasources.py b/lightly/api/api_workflow_datasources.py deleted file mode 100644 index 5c2033766..000000000 --- a/lightly/api/api_workflow_datasources.py +++ /dev/null @@ -1,912 +0,0 @@ -import time -import warnings -from typing import Dict, Iterator, List, Optional, Set, Tuple, Union - -import tqdm - -from lightly.openapi_generated.swagger_client.models import ( - DatasourceConfig, - DatasourceProcessedUntilTimestampRequest, - DatasourceProcessedUntilTimestampResponse, - DatasourcePurpose, - DatasourceRawSamplesData, -) -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data_row import ( - DatasourceRawSamplesDataRow, -) - - -class _DatasourcesMixin: - def download_raw_samples( - self, - from_: int = 0, - to: Optional[int] = None, - relevant_filenames_file_name: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - ) -> List[Tuple[str, str]]: - """Downloads filenames and read urls from the datasource. - - Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) - will be downloaded. - - Args: - from_: - Unix timestamp from which on samples are downloaded. Defaults to the - very beginning (timestamp 0). - to: - Unix timestamp up to and including which samples are downloaded. - Defaults to the current timestamp. - relevant_filenames_file_name: - Path to the relevant filenames text file in the cloud bucket. - The path is relative to the datasource root. Optional. - use_redirected_read_url: - Flag for redirected read urls. When this flag is true, - RedirectedReadUrls are returned instead of ReadUrls, meaning that the - returned URLs have unlimited access to the file. - Defaults to False. When S3DelegatedAccess is configured, this flag has - no effect because RedirectedReadUrls are always returned. - progress_bar: - Tqdm progress bar to show how many samples have already been - retrieved. - - Returns: - A list of (filename, url) tuples where each tuple represents a sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_raw_samples() - [('image-1.png', 'https://......'), ('image-2.png', 'https://......')] - - :meta private: # Skip docstring generation - """ - return self._download_raw_files( - download_function=self._datasources_api.get_list_of_raw_samples_from_datasource_by_dataset_id, - from_=from_, - to=to, - relevant_filenames_file_name=relevant_filenames_file_name, - use_redirected_read_url=use_redirected_read_url, - progress_bar=progress_bar, - ) - - def download_raw_predictions( - self, - task_name: str, - from_: int = 0, - to: Optional[int] = None, - relevant_filenames_file_name: Optional[str] = None, - run_id: Optional[str] = None, - relevant_filenames_artifact_id: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - ) -> List[Tuple[str, str]]: - """Downloads all prediction filenames and read urls from the datasource. - - See `download_raw_predictions_iter` for details. - - :meta private: # Skip docstring generation - """ - return list( - self.download_raw_predictions_iter( - task_name=task_name, - from_=from_, - to=to, - relevant_filenames_file_name=relevant_filenames_file_name, - run_id=run_id, - relevant_filenames_artifact_id=relevant_filenames_artifact_id, - use_redirected_read_url=use_redirected_read_url, - progress_bar=progress_bar, - ) - ) - - def download_raw_predictions_iter( - self, - task_name: str, - from_: int = 0, - to: Optional[int] = None, - relevant_filenames_file_name: Optional[str] = None, - run_id: Optional[str] = None, - relevant_filenames_artifact_id: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - ) -> Iterator[Tuple[str, str]]: - """Downloads prediction filenames and read urls from the datasource. - - Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) - will be downloaded. - - Args: - task_name: - Name of the prediction task. - from_: - Unix timestamp from which on samples are downloaded. Defaults to the - very beginning (timestamp 0). - to: - Unix timestamp up to and including which samples are downloaded. - Defaults to the current timestamp. - relevant_filenames_file_name: - Path to the relevant filenames text file in the cloud bucket. - The path is relative to the datasource root. Optional. - run_id: - Run ID. Optional. Should be given along with - `relevant_filenames_artifact_id` to download relevant files only. - relevant_filenames_artifact_id: - ID of the relevant filename artifact. Optional. Should be given along - with `run_id` to download relevant files only. Note that this is - different from `relevant_filenames_file_name`. - use_redirected_read_url: - Flag for redirected read urls. When this flag is true, - RedirectedReadUrls are returned instead of ReadUrls, meaning that the - returned URLs have unlimited access to the file. - Defaults to False. When S3DelegatedAccess is configured, this flag has - no effect because RedirectedReadUrls are always returned. - progress_bar: - Tqdm progress bar to show how many prediction files have already been - retrieved. - - Returns: - An iterator of (filename, url) tuples where each tuple represents a sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> task_name = "object-detection" - >>> client.set_dataset_id_by_name("my-dataset") - >>> list(client.download_raw_predictions(task_name=task_name)) - [('.lightly/predictions/object-detection/image-1.json', 'https://......'), - ('.lightly/predictions/object-detection/image-2.json', 'https://......')] - - :meta private: # Skip docstring generation - """ - if run_id is not None and relevant_filenames_artifact_id is None: - raise ValueError( - "'relevant_filenames_artifact_id' should not be `None` when 'run_id' " - "is specified." - ) - if run_id is None and relevant_filenames_artifact_id is not None: - raise ValueError( - "'run_id' should not be `None` when 'relevant_filenames_artifact_id' " - "is specified." - ) - relevant_filenames_kwargs = {} - if run_id is not None and relevant_filenames_artifact_id is not None: - relevant_filenames_kwargs["relevant_filenames_run_id"] = run_id - relevant_filenames_kwargs[ - "relevant_filenames_artifact_id" - ] = relevant_filenames_artifact_id - - yield from self._download_raw_files_iter( - download_function=self._datasources_api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id, - from_=from_, - to=to, - relevant_filenames_file_name=relevant_filenames_file_name, - use_redirected_read_url=use_redirected_read_url, - task_name=task_name, - progress_bar=progress_bar, - **relevant_filenames_kwargs, - ) - - def download_raw_metadata( - self, - from_: int = 0, - to: Optional[int] = None, - run_id: Optional[str] = None, - relevant_filenames_artifact_id: Optional[str] = None, - relevant_filenames_file_name: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - ) -> List[Tuple[str, str]]: - """Downloads all metadata filenames and read urls from the datasource. - - See `download_raw_metadata_iter` for details. - - :meta private: # Skip docstring generation - """ - return list( - self.download_raw_metadata_iter( - from_=from_, - to=to, - run_id=run_id, - relevant_filenames_artifact_id=relevant_filenames_artifact_id, - relevant_filenames_file_name=relevant_filenames_file_name, - use_redirected_read_url=use_redirected_read_url, - progress_bar=progress_bar, - ) - ) - - def download_raw_metadata_iter( - self, - from_: int = 0, - to: Optional[int] = None, - run_id: Optional[str] = None, - relevant_filenames_artifact_id: Optional[str] = None, - relevant_filenames_file_name: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - ) -> Iterator[Tuple[str, str]]: - """Downloads all metadata filenames and read urls from the datasource. - - Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) - will be downloaded. - - Args: - from_: - Unix timestamp from which on samples are downloaded. Defaults to the - very beginning (timestamp 0). - to: - Unix timestamp up to and including which samples are downloaded. - Defaults to the current timestamp. - relevant_filenames_file_name: - Path to the relevant filenames text file in the cloud bucket. - The path is relative to the datasource root. Optional. - run_id: - Run ID. Optional. Should be given along with - `relevant_filenames_artifact_id` to download relevant files only. - relevant_filenames_artifact_id: - ID of the relevant filename artifact. Optional. Should be given along - with `run_id` to download relevant files only. Note that this is - different from `relevant_filenames_file_name`. - use_redirected_read_url: - Flag for redirected read urls. When this flag is true, - RedirectedReadUrls are returned instead of ReadUrls, meaning that the - returned URLs have unlimited access to the file. - Defaults to False. When S3DelegatedAccess is configured, this flag has - no effect because RedirectedReadUrls are always returned. - progress_bar: - Tqdm progress bar to show how many metadata files have already been - retrieved. - - Returns: - An iterator of (filename, url) tuples where each tuple represents a sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> list(client.download_raw_metadata_iter()) - [('.lightly/metadata/object-detection/image-1.json', 'https://......'), - ('.lightly/metadata/object-detection/image-2.json', 'https://......')] - - :meta private: # Skip docstring generation - """ - if run_id is not None and relevant_filenames_artifact_id is None: - raise ValueError( - "'relevant_filenames_artifact_id' should not be `None` when 'run_id' " - "is specified." - ) - if run_id is None and relevant_filenames_artifact_id is not None: - raise ValueError( - "'run_id' should not be `None` when 'relevant_filenames_artifact_id' " - "is specified." - ) - relevant_filenames_kwargs = {} - if run_id is not None and relevant_filenames_artifact_id is not None: - relevant_filenames_kwargs["relevant_filenames_run_id"] = run_id - relevant_filenames_kwargs[ - "relevant_filenames_artifact_id" - ] = relevant_filenames_artifact_id - - yield from self._download_raw_files_iter( - download_function=self._datasources_api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id, - from_=from_, - to=to, - relevant_filenames_file_name=relevant_filenames_file_name, - use_redirected_read_url=use_redirected_read_url, - progress_bar=progress_bar, - **relevant_filenames_kwargs, - ) - - def download_new_raw_samples( - self, - use_redirected_read_url: bool = False, - ) -> List[Tuple[str, str]]: - """Downloads filenames and read urls of unprocessed samples from the datasource. - - All samples after the timestamp of `ApiWorkflowClient.get_processed_until_timestamp()` are - fetched. After downloading the samples, the timestamp is updated to the current time. - This function can be repeatedly called to retrieve new samples from the datasource. - - Args: - use_redirected_read_url: - Flag for redirected read urls. When this flag is true, - RedirectedReadUrls are returned instead of ReadUrls, meaning that the - returned URLs have unlimited access to the file. - Defaults to False. When S3DelegatedAccess is configured, this flag has - no effect because RedirectedReadUrls are always returned. - - Returns: - A list of (filename, url) tuples where each tuple represents a sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_new_raw_samples() - [('image-3.png', 'https://......'), ('image-4.png', 'https://......')] - """ - from_ = self.get_processed_until_timestamp() - - if from_ != 0: - # We already processed samples at some point. - # Add 1 because the samples with timestamp == from_ - # have already been processed - from_ += 1 - - to = int(time.time()) - data = self.download_raw_samples( - from_=from_, - to=to, - relevant_filenames_file_name=None, - use_redirected_read_url=use_redirected_read_url, - ) - self.update_processed_until_timestamp(timestamp=to) - return data - - def get_processed_until_timestamp(self) -> int: - """Returns the timestamp until which samples have been processed. - - Returns: - Unix timestamp of last processed sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_processed_until_timestamp() - 1684750513 - - :meta private: # Skip docstring generation - """ - response: DatasourceProcessedUntilTimestampResponse = self._datasources_api.get_datasource_processed_until_timestamp_by_dataset_id( - dataset_id=self.dataset_id - ) - timestamp = int(response.processed_until_timestamp) - return timestamp - - def update_processed_until_timestamp(self, timestamp: int) -> None: - """Sets the timestamp until which samples have been processed. - - Args: - timestamp: - Unix timestamp of last processed sample. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset. - >>> # All samples are processed at this moment. - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_new_raw_samples() - [] - >>> - >>> # Set timestamp to an earlier moment to reprocess samples - >>> client.update_processed_until_timestamp(1684749813) - >>> client.download_new_raw_samples() - [('image-3.png', 'https://......'), ('image-4.png', 'https://......')] - """ - body = DatasourceProcessedUntilTimestampRequest( - processed_until_timestamp=timestamp - ) - self._datasources_api.update_datasource_processed_until_timestamp_by_dataset_id( - dataset_id=self.dataset_id, - datasource_processed_until_timestamp_request=body, - ) - - def get_datasource(self) -> DatasourceConfig: - """Returns the datasource of the current dataset. - - Returns: - Datasource data of the datasource of the current dataset. - - Raises: - ApiException if no datasource was configured. - - """ - return self._datasources_api.get_datasource_by_dataset_id(self.dataset_id) - - def set_azure_config( - self, - container_name: str, - account_name: str, - sas_token: str, - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the Azure configuration for the datasource of the current dataset. - - See our docs for a detailed explanation on how to setup Lightly with - Azure: https://docs.lightly.ai/docs/azure - - Args: - container_name: - Container name of the dataset, for example: "my-container/path/to/my/data". - account_name: - Azure account name. - sas_token: - Secure Access Signature token. - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigAzure once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "AZURE", - "fullPath": container_name, - "thumbSuffix": thumbnail_suffix, - "accountName": account_name, - "accountKey": sas_token, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def set_gcs_config( - self, - resource_path: str, - project_id: str, - credentials: str, - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the Google Cloud Storage configuration for the datasource of the - current dataset. - - See our docs for a detailed explanation on how to setup Lightly with - Google Cloud Storage: https://docs.lightly.ai/docs/google-cloud-storage - - Args: - resource_path: - GCS url of your dataset, for example: "gs://my_bucket/path/to/my/data" - project_id: - GCS project id. - credentials: - Content of the credentials JSON file stringified which you - download from Google Cloud Platform. - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigGCS once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "GCS", - "fullPath": resource_path, - "thumbSuffix": thumbnail_suffix, - "gcsProjectId": project_id, - "gcsCredentials": credentials, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def set_local_config( - self, - relative_path: str = "", - web_server_location: Optional[str] = "http://localhost:3456", - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the local configuration for the datasource of the current dataset. - - Find a detailed explanation on how to setup Lightly with a local file - server in our docs: https://docs.lightly.ai/getting_started/dataset_creation/dataset_creation_local_server.html - - Args: - relative_path: - Relative path from the mount root, for example: "path/to/my/data". - web_server_location: - Location of your local file server. Defaults to "http://localhost:3456". - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigLocal once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "LOCAL", - "webServerLocation": web_server_location, - "fullPath": relative_path, - "thumbSuffix": thumbnail_suffix, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def set_s3_config( - self, - resource_path: str, - region: str, - access_key: str, - secret_access_key: str, - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the S3 configuration for the datasource of the current dataset. - - See our docs for a detailed explanation on how to setup Lightly with - AWS S3: https://docs.lightly.ai/docs/aws-s3 - - Args: - resource_path: - S3 url of your dataset, for example "s3://my_bucket/path/to/my/data". - region: - S3 region where the dataset bucket is located, for example "eu-central-1". - access_key: - S3 access key. - secret_access_key: - Secret for the S3 access key. - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigS3 once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "S3", - "fullPath": resource_path, - "thumbSuffix": thumbnail_suffix, - "s3Region": region, - "s3AccessKeyId": access_key, - "s3SecretAccessKey": secret_access_key, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def set_s3_delegated_access_config( - self, - resource_path: str, - region: str, - role_arn: str, - external_id: str, - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the S3 configuration for the datasource of the current dataset. - - See our docs for a detailed explanation on how to setup Lightly with - AWS S3 and delegated access: https://docs.lightly.ai/docs/aws-s3#delegated-access - - Args: - resource_path: - S3 url of your dataset, for example "s3://my_bucket/path/to/my/data". - region: - S3 region where the dataset bucket is located, for example "eu-central-1". - role_arn: - Unique ARN identifier of the role. - external_id: - External ID of the role. - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigS3 once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "S3DelegatedAccess", - "fullPath": resource_path, - "thumbSuffix": thumbnail_suffix, - "s3Region": region, - "s3ARN": role_arn, - "s3ExternalId": external_id, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def set_obs_config( - self, - resource_path: str, - obs_endpoint: str, - obs_access_key_id: str, - obs_secret_access_key: str, - thumbnail_suffix: Optional[ - str - ] = ".lightly/thumbnails/[filename]_thumb.[extension]", - purpose: str = DatasourcePurpose.INPUT_OUTPUT, - ) -> None: - """Sets the Telekom OBS configuration for the datasource of the current dataset. - - Args: - resource_path: - OBS url of your dataset. For example, "obs://my_bucket/path/to/my/data". - obs_endpoint: - OBS endpoint. - obs_access_key_id: - OBS access key id. - obs_secret_access_key: - OBS secret access key. - thumbnail_suffix: - Where to save thumbnails of the images in the dataset, for - example ".lightly/thumbnails/[filename]_thumb.[extension]". - Set to None to disable thumbnails and use the full images from the - datasource instead. - purpose: - Datasource purpose, determines if datasource is read only (INPUT) - or can be written to as well (LIGHTLY, INPUT_OUTPUT). - - """ - # TODO: Use DatasourceConfigOBS once we switch/update the api generator. - self._datasources_api.update_datasource_by_dataset_id( - datasource_config=DatasourceConfig.from_dict( - { - "type": "OBS", - "fullPath": resource_path, - "thumbSuffix": thumbnail_suffix, - "obsEndpoint": obs_endpoint, - "obsAccessKeyId": obs_access_key_id, - "obsSecretAccessKey": obs_secret_access_key, - "purpose": purpose, - } - ), - dataset_id=self.dataset_id, - ) - - def get_prediction_read_url( - self, - filename: str, - ) -> str: - """Returns a read-url for .lightly/predictions/{filename}. - - Args: - filename: - Filename for which to get the read-url. - - Returns: - A read-url to the file. Note that a URL will be returned even if the file does not - exist. - - :meta private: # Skip docstring generation - """ - return self._datasources_api.get_prediction_file_read_url_from_datasource_by_dataset_id( - dataset_id=self.dataset_id, - file_name=filename, - ) - - def get_metadata_read_url( - self, - filename: str, - ) -> str: - """Returns a read-url for .lightly/metadata/{filename}. - - Args: - filename: - Filename for which to get the read-url. - - Returns: - A read-url to the file. Note that a URL will be returned even if the file does not - exist. - - :meta private: # Skip docstring generation - """ - return self._datasources_api.get_metadata_file_read_url_from_datasource_by_dataset_id( - dataset_id=self.dataset_id, - file_name=filename, - ) - - def get_custom_embedding_read_url( - self, - filename: str, - ) -> str: - """Returns a read-url for .lightly/embeddings/{filename}. - - Args: - filename: - Filename for which to get the read-url. - - Returns: - A read-url to the file. Note that a URL will be returned even if the file does not - exist. - - :meta private: # Skip docstring generation - """ - return self._datasources_api.get_custom_embedding_file_read_url_from_datasource_by_dataset_id( - dataset_id=self.dataset_id, - file_name=filename, - ) - - def list_datasource_permissions( - self, - ) -> Dict[str, Union[bool, Dict[str, str]]]: - """Lists granted access permissions for the datasource set up with a dataset. - - Returns a string dictionary, with each permission mapped to a boolean value, - see the example below. An additional ``errors`` key is present if any permission - errors have been encountered. Permission errors are stored in a dictionary where - permission names are keys and error messages are values. - - >>> from lightly.api import ApiWorkflowClient - >>> client = ApiWorkflowClient( - ... token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" - ... ) - >>> client.list_datasource_permissions() - { - 'can_read': True, - 'can_write': True, - 'can_list': False, - 'can_overwrite': True, - 'errors': {'can_list': 'error message'} - } - - """ - return self._datasources_api.verify_datasource_by_dataset_id( - dataset_id=self.dataset_id, - ).to_dict() - - def _download_raw_files( - self, - download_function: Union[ - "DatasourcesApi.get_list_of_raw_samples_from_datasource_by_dataset_id", - "DatasourcesApi.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", - "DatasourcesApi.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", - ], - from_: int = 0, - to: Optional[int] = None, - relevant_filenames_file_name: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - **kwargs, - ) -> List[Tuple[str, str]]: - return list( - self._download_raw_files_iter( - download_function=download_function, - from_=from_, - to=to, - relevant_filenames_file_name=relevant_filenames_file_name, - use_redirected_read_url=use_redirected_read_url, - progress_bar=progress_bar, - **kwargs, - ) - ) - - def _download_raw_files_iter( - self, - download_function: Union[ - "DatasourcesApi.get_list_of_raw_samples_from_datasource_by_dataset_id", - "DatasourcesApi.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", - "DatasourcesApi.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", - ], - from_: int = 0, - to: Optional[int] = None, - relevant_filenames_file_name: Optional[str] = None, - use_redirected_read_url: bool = False, - progress_bar: Optional[tqdm.tqdm] = None, - **kwargs, - ) -> Iterator[Tuple[str, str]]: - if to is None: - to = int(time.time()) - relevant_filenames_kwargs = ( - {"relevant_filenames_file_name": relevant_filenames_file_name} - if relevant_filenames_file_name - else dict() - ) - - listed_filenames = set() - - def get_samples( - response: DatasourceRawSamplesData, - ) -> Iterator[Tuple[str, str]]: - for sample in response.data: - if _sample_unseen_and_valid( - sample=sample, - relevant_filenames_file_name=relevant_filenames_file_name, - listed_filenames=listed_filenames, - ): - listed_filenames.add(sample.file_name) - yield sample.file_name, sample.read_url - if progress_bar is not None: - progress_bar.update(1) - - response: DatasourceRawSamplesData = download_function( - dataset_id=self.dataset_id, - var_from=from_, - to=to, - use_redirected_read_url=use_redirected_read_url, - **relevant_filenames_kwargs, - **kwargs, - ) - yield from get_samples(response=response) - while response.has_more: - response: DatasourceRawSamplesData = download_function( - dataset_id=self.dataset_id, - cursor=response.cursor, - use_redirected_read_url=use_redirected_read_url, - **relevant_filenames_kwargs, - **kwargs, - ) - yield from get_samples(response=response) - - -def _sample_unseen_and_valid( - sample: DatasourceRawSamplesDataRow, - relevant_filenames_file_name: Optional[str], - listed_filenames: Set[str], -) -> bool: - # Note: We want to remove these checks eventually. Absolute paths and relative paths - # with dot notation should be handled either in the API or the Worker. Duplicate - # filenames should be handled in the Worker as handling it in the API would require - # too much memory. - if sample.file_name.startswith("/"): - warnings.warn( - UserWarning( - f"Absolute file paths like {sample.file_name} are not supported" - f" in relevant filenames file {relevant_filenames_file_name} due to blob storage" - ) - ) - return False - elif sample.file_name.startswith(("./", "../")): - warnings.warn( - UserWarning( - f"Using dot notation ('./', '../') like in {sample.file_name} is not supported" - f" in relevant filenames file {relevant_filenames_file_name} due to blob storage" - ) - ) - return False - elif sample.file_name in listed_filenames: - warnings.warn( - UserWarning( - f"Duplicate filename {sample.file_name} in relevant" - f" filenames file {relevant_filenames_file_name}" - ) - ) - return False - else: - return True diff --git a/lightly/api/api_workflow_download_dataset.py b/lightly/api/api_workflow_download_dataset.py deleted file mode 100644 index cda122482..000000000 --- a/lightly/api/api_workflow_download_dataset.py +++ /dev/null @@ -1,322 +0,0 @@ -import io -import os -import urllib.request -import warnings -from concurrent.futures.thread import ThreadPoolExecutor -from typing import Dict, List, Optional -from urllib.request import Request - -import tqdm -from PIL import Image - -from lightly.api import download, utils -from lightly.api.bitmask import BitMask -from lightly.openapi_generated.swagger_client.models import ( - DatasetEmbeddingData, - ImageType, -) -from lightly.utils.hipify import bcolors - - -def _make_dir_and_save_image(output_dir: str, filename: str, img: Image): - """Saves the images and creates necessary subdirectories.""" - path = os.path.join(output_dir, filename) - - head = os.path.split(path)[0] - if not os.path.exists(head): - os.makedirs(head) - - img.save(path) - img.close() - - -def _get_image_from_read_url(read_url: str): - """Makes a get request to the signed read url and returns the image.""" - request = Request(read_url, method="GET") - with urllib.request.urlopen(request) as response: - blob = response.read() - img = Image.open(io.BytesIO(blob)) - return img - - -class _DownloadDatasetMixin: - def download_dataset( - self, - output_dir: str, - tag_name: str = "initial-tag", - max_workers: int = 8, - verbose: bool = True, - ) -> None: - """Downloads images from the web-app and stores them in output_dir. - - Args: - output_dir: - Where to store the downloaded images. - tag_name: - Name of the tag which should be downloaded. - max_workers: - Maximum number of workers downloading images in parallel. - verbose: - Whether or not to show the progress bar. - - Raises: - ValueError: - If the specified tag does not exist on the dataset. - RuntimeError: - If the connection to the server failed. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_dataset("/tmp/data") - Downloading 3 images (with 3 workers): - 100%|██████████████████████████████████| 3/3 [00:01<00:00, 1.99imgs/s] - """ - - # check if images are available - dataset = self._datasets_api.get_dataset_by_id(self.dataset_id) - if dataset.img_type != ImageType.FULL: - # only thumbnails or metadata available - raise ValueError( - f"Dataset with id {self.dataset_id} has no downloadable images!" - ) - - # check if tag exists - available_tags = self.get_all_tags() - try: - tag = next(tag for tag in available_tags if tag.name == tag_name) - except StopIteration: - raise ValueError( - f"Dataset with id {self.dataset_id} has no tag {tag_name}!" - ) - - # get sample ids - sample_ids = list( - utils.paginate_endpoint( - self._mappings_api.get_sample_mappings_by_dataset_id, - page_size=25000, - dataset_id=self.dataset_id, - field="_id", - ) - ) - - indices = BitMask.from_hex(tag.bit_mask_data).to_indices() - sample_ids = [sample_ids[i] for i in indices] - - filenames_on_server = self.get_filenames() - filenames = [filenames_on_server[i] for i in indices] - - downloadables = zip(sample_ids, filenames) - - # handle the case where len(sample_ids) < max_workers - max_workers = min(len(sample_ids), max_workers) - max_workers = max(max_workers, 1) - - if verbose: - print( - f"Downloading {bcolors.OKGREEN}{len(sample_ids)}{bcolors.ENDC} images (with {bcolors.OKGREEN}{max_workers}{bcolors.ENDC} workers):", - flush=True, - ) - pbar = tqdm.tqdm(unit="imgs", total=len(sample_ids)) - tqdm_lock = tqdm.tqdm.get_lock() - - # define lambda function for concurrent download - def lambda_(i): - sample_id, filename = i - # try to download image - try: - read_url = self._samples_api.get_sample_image_read_url_by_id( - dataset_id=self.dataset_id, - sample_id=sample_id, - type="full", - ) - img = _get_image_from_read_url(read_url) - _make_dir_and_save_image(output_dir, filename, img) - success = True - except Exception as e: # pylint: disable=broad-except - warnings.warn(f"Downloading of image {filename} failed with error {e}") - success = False - - # update the progress bar - if verbose: - tqdm_lock.acquire() - pbar.update(1) - tqdm_lock.release() - # return whether the download was successful - return success - - with ThreadPoolExecutor(max_workers=max_workers) as executor: - results = list(executor.map(lambda_, downloadables, chunksize=1)) - - if not all(results): - msg = "Warning: Unsuccessful download! " - msg += "Failed at image: {}".format(results.index(False)) - warnings.warn(msg) - - def get_all_embedding_data(self) -> List[DatasetEmbeddingData]: - """Fetches embedding data of all embeddings for this dataset. - - Returns: - A list of embedding data. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_all_embedding_data() - [{'created_at': 1684750552181, - 'id': '646b40d88355e2f54c6d2235', - 'is2d': False, - 'is_processed': True, - 'name': 'default_20230522_10h15m50s'}] - """ - return self._embeddings_api.get_embeddings_by_dataset_id( - dataset_id=self.dataset_id - ) - - def get_embedding_data_by_name(self, name: str) -> DatasetEmbeddingData: - """Fetches embedding data with the given name for this dataset. - - Args: - name: Embedding name. - - Returns: - Embedding data. - - Raises: - ValueError: - If no embedding with this name exists. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_embedding_data_by_name("embedding-data") - [{'created_at': 1654756552401, - 'id': '646f346004d77b4e1424e67e', - 'is2d': False, - 'is_processed': True, - 'name': 'embedding-data'}] - """ - for embedding_data in self.get_all_embedding_data(): - if embedding_data.name == name: - return embedding_data - raise ValueError( - f"There are no embeddings with name '{name}' for dataset with id " - f"'{self.dataset_id}'." - ) - - def download_embeddings_csv_by_id( - self, - embedding_id: str, - output_path: str, - ) -> None: - """Downloads embeddings with the given embedding id from the dataset. - - Args: - embedding_id: ID of the embedding data to be downloaded. - output_path: Where the downloaded embedding data should be stored. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_embeddings_csv_by_id( - ... embedding_id="646f346004d77b4e1424e67e", - ... output_path="/tmp/embeddings.csv" - ... ) - >>> - >>> # File content: - >>> # filenames,embedding_0,embedding_1,embedding_...,labels - >>> # image-1.png,0.2124302,-0.26934767,...,0 - """ - read_url = self._embeddings_api.get_embeddings_csv_read_url_by_id( - dataset_id=self.dataset_id, embedding_id=embedding_id - ) - download.download_and_write_file(url=read_url, output_path=output_path) - - def download_embeddings_csv(self, output_path: str) -> None: - """Downloads the latest embeddings from the dataset. - - Args: - output_path: Where the downloaded embedding data should be stored. - - Raises: - RuntimeError: - If no embeddings could be found for the dataset. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.download_embeddings_csv(output_path="/tmp/embeddings.csv") - >>> - >>> # File content: - >>> # filenames,embedding_0,embedding_1,embedding_...,labels - >>> # image-1.png,0.2124302,-0.26934767,...,0 - """ - last_embedding = _get_latest_default_embedding_data( - embeddings=self.get_all_embedding_data() - ) - if last_embedding is None: - raise RuntimeError( - f"Could not find embeddings for dataset with id '{self.dataset_id}'." - ) - self.download_embeddings_csv_by_id( - embedding_id=last_embedding.id, - output_path=output_path, - ) - - def export_label_studio_tasks_by_tag_id( - self, - tag_id: str, - ) -> List[Dict]: - """Exports samples in a format compatible with Label Studio. - - The format is documented here: - https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format - - Args: - tag_id: - Id of the tag which should exported. - - Returns: - A list of dictionaries in a format compatible with Label Studio. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.export_label_studio_tasks_by_tag_id(tag_id="646f34608a5613b57d8b73cc") - [{'id': 0, 'data': {'image': '...', ...}}] - """ - label_studio_tasks = list( - utils.paginate_endpoint( - self._tags_api.export_tag_to_label_studio_tasks, - page_size=20000, - dataset_id=self.dataset_id, - tag_id=tag_id, - ) - ) - return label_studio_tasks - - -def _get_latest_default_embedding_data( - embeddings: List[DatasetEmbeddingData], -) -> Optional[DatasetEmbeddingData]: - """Returns the latest embedding data with a default name or None if no such - default embedding exists. - """ - default_embeddings = [e for e in embeddings if e.name.startswith("default")] - if default_embeddings: - last_embedding = sorted(default_embeddings, key=lambda e: e.created_at)[-1] - return last_embedding - else: - return None diff --git a/lightly/api/api_workflow_export.py b/lightly/api/api_workflow_export.py deleted file mode 100644 index 7e9bb3ba4..000000000 --- a/lightly/api/api_workflow_export.py +++ /dev/null @@ -1,388 +0,0 @@ -import warnings -from typing import Dict, List - -from lightly.api import utils -from lightly.openapi_generated.swagger_client.models import ( - FileNameFormat, - LabelBoxDataRow, - LabelBoxV4DataRow, - LabelStudioTask, -) - - -class _ExportDatasetMixin: - def export_label_studio_tasks_by_tag_id( - self, - tag_id: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Label Studio. - - The format is documented here: - https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format - - More information: - https://docs.lightly.ai/docs/labelstudio-integration - - Args: - tag_id: - ID of the tag which should exported. - - Returns: - A list of dictionaries in a format compatible with Label Studio. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.export_label_studio_tasks_by_tag_id(tag_id="646f34608a5613b57d8b73cc") - [{'id': 0, 'data': {'image': '...', ...}}] - """ - label_studio_tasks: List[LabelStudioTask] = list( - utils.paginate_endpoint( - self._tags_api.export_tag_to_label_studio_tasks, - page_size=20000, - dataset_id=self.dataset_id, - tag_id=tag_id, - ) - ) - return [task.to_dict(by_alias=True) for task in label_studio_tasks] - - def export_label_studio_tasks_by_tag_name( - self, - tag_name: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Label Studio. - - The format is documented here: - https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format - - More information: - https://docs.lightly.ai/docs/labelstudio-integration - - Args: - tag_name: - Name of the tag which should exported. - - Returns: - A list of dictionaries in a format compatible with Label Studio. - - Examples: - >>> # write json file which can be imported in Label Studio - >>> tasks = client.export_label_studio_tasks_by_tag_name( - >>> 'initial-tag' - >>> ) - >>> - >>> with open('my-label-studio-tasks.json', 'w') as f: - >>> json.dump(tasks, f) - - """ - tag = self.get_tag_by_name(tag_name) - return self.export_label_studio_tasks_by_tag_id(tag.id) - - def export_label_box_data_rows_by_tag_id( - self, - tag_id: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Labelbox v3. - - The format is documented here: https://docs.labelbox.com/docs/images-json - - More information: - https://docs.lightly.ai/docs/labelbox - - Args: - tag_id: - ID of the tag which should exported. - - Returns: - A list of dictionaries in a format compatible with Labelbox v3. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.export_label_box_data_rows_by_tag_id(tag_id="646f34608a5613b57d8b73cc") - [{'externalId': '2218961434_7916358f53_z.jpg', 'imageUrl': ...}] - """ - warnings.warn( - DeprecationWarning( - "This method exports data in the deprecated Labelbox v3 format and " - "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_id " - "to export data in the Labelbox v4 format instead." - ) - ) - label_box_data_rows: List[LabelBoxDataRow] = list( - utils.paginate_endpoint( - self._tags_api.export_tag_to_label_box_data_rows, - page_size=20000, - dataset_id=self.dataset_id, - tag_id=tag_id, - ) - ) - return [row.to_dict(by_alias=True) for row in label_box_data_rows] - - def export_label_box_data_rows_by_tag_name( - self, - tag_name: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Labelbox v3. - - The format is documented here: https://docs.labelbox.com/docs/images-json - - More information: - https://docs.lightly.ai/docs/labelbox - - Args: - tag_name: - Name of the tag which should exported. - - Returns: - A list of dictionaries in a format compatible with Labelbox v3. - - Examples: - >>> # write json file which can be imported in Label Studio - >>> tasks = client.export_label_box_data_rows_by_tag_name( - >>> 'initial-tag' - >>> ) - >>> - >>> with open('my-labelbox-rows.json', 'w') as f: - >>> json.dump(tasks, f) - - """ - warnings.warn( - DeprecationWarning( - "This method exports data in the deprecated Labelbox v3 format and " - "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_name " - "to export data in the Labelbox v4 format instead." - ) - ) - tag = self.get_tag_by_name(tag_name) - return self.export_label_box_data_rows_by_tag_id(tag.id) - - def export_label_box_v4_data_rows_by_tag_id( - self, - tag_id: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Labelbox v4. - - The format is documented here: https://docs.labelbox.com/docs/images-json - - More information: - https://docs.lightly.ai/docs/labelbox - - Args: - tag_id: - ID of the tag which should exported. - Returns: - A list of dictionaries in a format compatible with Labelbox v4. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.export_label_box_v4_data_rows_by_tag_id(tag_id="646f34608a5613b57d8b73cc") - [{'row_data': '...', 'global_key': 'image-1.jpg', 'media_type': 'IMAGE'} - """ - label_box_data_rows: List[LabelBoxV4DataRow] = list( - utils.paginate_endpoint( - self._tags_api.export_tag_to_label_box_v4_data_rows, - page_size=20000, - dataset_id=self.dataset_id, - tag_id=tag_id, - ) - ) - return [row.to_dict() for row in label_box_data_rows] - - def export_label_box_v4_data_rows_by_tag_name( - self, - tag_name: str, - ) -> List[Dict]: - """Fetches samples in a format compatible with Labelbox. - - The format is documented here: https://docs.labelbox.com/docs/images-json - - More information: - https://docs.lightly.ai/docs/labelbox - - Args: - tag_name: - Name of the tag which should exported. - Returns: - A list of dictionaries in a format compatible with Labelbox. - Examples: - >>> # write json file which can be imported in Label Studio - >>> tasks = client.export_label_box_v4_data_rows_by_tag_name( - >>> 'initial-tag' - >>> ) - >>> - >>> with open('my-labelbox-rows.json', 'w') as f: - >>> json.dump(tasks, f) - """ - tag = self.get_tag_by_name(tag_name) - return self.export_label_box_v4_data_rows_by_tag_id(tag.id) - - def export_filenames_by_tag_id( - self, - tag_id: str, - ) -> str: - """Fetches samples filenames within a certain tag by tag ID. - - More information: - https://docs.lightly.ai/docs/filenames-and-readurls - - Args: - tag_id: - ID of the tag which should exported. - - Returns: - A list of filenames of samples within a certain tag. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.export_filenames_by_tag_id("646b40d6c06aae1b91294a9e") - 'image-1.jpg\nimage-2.jpg\nimage-3.jpg' - """ - filenames = "\n".join( - utils.paginate_endpoint( - self._tags_api.export_tag_to_basic_filenames, - dataset_id=self.dataset_id, - tag_id=tag_id, - ) - ) - return filenames - - def export_filenames_by_tag_name( - self, - tag_name: str, - ) -> str: - """Fetches samples filenames within a certain tag by tag name. - - More information: - https://docs.lightly.ai/docs/filenames-and-readurls - - Args: - tag_name: - Name of the tag which should exported. - - Returns: - A list of filenames of samples within a certain tag. - - Examples: - >>> # write json file which can be imported in Label Studio - >>> filenames = client.export_filenames_by_tag_name( - >>> 'initial-tag' - >>> ) - >>> - >>> with open('filenames-of-initial-tag.txt', 'w') as f: - >>> f.write(filenames) - - """ - tag = self.get_tag_by_name(tag_name) - return self.export_filenames_by_tag_id(tag.id) - - def export_filenames_and_read_urls_by_tag_id( - self, - tag_id: str, - ) -> List[Dict[str, str]]: - """Fetches filenames, read URLs, and datasource URLs from the given tag. - - More information: - https://docs.lightly.ai/docs/filenames-and-readurls - - Args: - tag_id: - ID of the tag which should exported. - - Returns: - A list of dictionaries with the keys "filename", "readUrl" and "datasourceUrl". - An example: - [ - { - "fileName": "sample1.jpg", - "readUrl": "s3://my_datasource/sample1.jpg?read_url_key=EAIFUIENDLFN", - "datasourceUrl": "s3://my_datasource/sample1.jpg", - }, - { - "fileName": "sample2.jpg", - "readUrl": "s3://my_datasource/sample2.jpg?read_url_key=JSBFIEUHVSJ", - "datasourceUrl": "s3://my_datasource/sample2.jpg", - }, - ] - - """ - filenames_string = "\n".join( - utils.paginate_endpoint( - self._tags_api.export_tag_to_basic_filenames, - dataset_id=self.dataset_id, - tag_id=tag_id, - file_name_format=FileNameFormat.NAME, - ) - ) - read_urls_string = "\n".join( - utils.paginate_endpoint( - self._tags_api.export_tag_to_basic_filenames, - dataset_id=self.dataset_id, - tag_id=tag_id, - file_name_format=FileNameFormat.REDIRECTED_READ_URL, - ) - ) - datasource_urls_string = "\n".join( - utils.paginate_endpoint( - self._tags_api.export_tag_to_basic_filenames, - dataset_id=self.dataset_id, - tag_id=tag_id, - file_name_format=FileNameFormat.DATASOURCE_FULL, - ) - ) - # The endpoint exportTagToBasicFilenames returns a plain string so we - # have to split it by newlines in order to get the individual entries. - # The order of the fileNames and readUrls and datasourceUrls is guaranteed to be the same - # by the API so we can simply zip them. - filenames = filenames_string.split("\n") - read_urls = read_urls_string.split("\n") - datasource_urls = datasource_urls_string.split("\n") - return [ - { - "fileName": filename, - "readUrl": read_url, - "datasourceUrl": datasource_url, - } - for filename, read_url, datasource_url in zip( - filenames, read_urls, datasource_urls - ) - ] - - def export_filenames_and_read_urls_by_tag_name( - self, - tag_name: str, - ) -> List[Dict[str, str]]: - """Fetches filenames, read URLs, and datasource URLs from the given tag name. - - More information: - https://docs.lightly.ai/docs/filenames-and-readurls - - Args: - tag_name: - Name of the tag which should exported. - - Returns: - A list of dictionaries with keys "filename", "readUrl" and "datasourceUrl". - - Examples: - >>> # write json file which can be used to access the actual file contents. - >>> mappings = client.export_filenames_and_read_urls_by_tag_name( - >>> 'initial-tag' - >>> ) - >>> - >>> with open('my-samples.json', 'w') as f: - >>> json.dump(mappings, f) - - """ - tag = self.get_tag_by_name(tag_name) - return self.export_filenames_and_read_urls_by_tag_id(tag.id) diff --git a/lightly/api/api_workflow_predictions.py b/lightly/api/api_workflow_predictions.py deleted file mode 100644 index 258620091..000000000 --- a/lightly/api/api_workflow_predictions.py +++ /dev/null @@ -1,82 +0,0 @@ -from typing import Sequence - -from lightly.openapi_generated.swagger_client.models import ( - PredictionSingleton, - PredictionTaskSchema, -) - - -class _PredictionsMixin: - def create_or_update_prediction_task_schema( - self, - schema: PredictionTaskSchema, - prediction_version_id: int = -1, - ) -> None: - """Creates or updates the prediction task schema. - - Args: - schema: - The prediction task schema. - prediction_version_id: - A numerical ID (e.g., timestamp) to distinguish different predictions of different model versions. - Use the same ID if you don't require versioning or if you wish to overwrite the previous schema. - - Example: - >>> import time - >>> from lightly.api import ApiWorkflowClient - >>> from lightly.openapi_generated.swagger_client.models import ( - >>> PredictionTaskSchema, - >>> TaskType, - >>> PredictionTaskSchemaCategory, - >>> ) - >>> - >>> client = ApiWorkflowClient( - >>> token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" - >>> ) - >>> - >>> schema = PredictionTaskSchema( - >>> name="my-object-detection", - >>> type=TaskType.OBJECT_DETECTION, - >>> categories=[ - >>> PredictionTaskSchemaCategory(id=0, name="dog"), - >>> PredictionTaskSchemaCategory(id=1, name="cat"), - >>> ], - >>> ) - >>> client.create_or_update_prediction_task_schema(schema=schema) - - :meta private: # Skip docstring generation - """ - self._predictions_api.create_or_update_prediction_task_schema_by_dataset_id( - prediction_task_schema=schema, - dataset_id=self.dataset_id, - prediction_uuid_timestamp=prediction_version_id, - ) - - def create_or_update_prediction( - self, - sample_id: str, - prediction_singletons: Sequence[PredictionSingleton], - prediction_version_id: int = -1, - ) -> None: - """Creates or updates predictions for one specific sample. - - Args: - sample_id - The ID of the sample. - - prediction_version_id: - A numerical ID (e.g., timestamp) to distinguish different predictions of different model versions. - Use the same id if you don't require versioning or if you wish to overwrite the previous schema. - This ID must match the ID of a prediction task schema. - - prediction_singletons: - Predictions to be uploaded for the designated sample. - - :meta private: # Skip docstring generation - """ - self._predictions_api.create_or_update_prediction_by_sample_id( - prediction_singleton=prediction_singletons, - dataset_id=self.dataset_id, - sample_id=sample_id, - prediction_uuid_timestamp=prediction_version_id, - ) diff --git a/lightly/api/api_workflow_selection.py b/lightly/api/api_workflow_selection.py deleted file mode 100644 index 760ef2d4d..000000000 --- a/lightly/api/api_workflow_selection.py +++ /dev/null @@ -1,192 +0,0 @@ -import time -import warnings -from typing import Dict, List, Optional, Union - -import numpy as np -from numpy.typing import NDArray - -from lightly.active_learning.config.selection_config import SelectionConfig -from lightly.openapi_generated.swagger_client.models import ( - ActiveLearningScoreCreateRequest, - JobState, - JobStatusData, - SamplingConfig, - SamplingConfigStoppingCondition, - SamplingCreateRequest, - TagData, -) - - -def _parse_active_learning_scores(scores: Union[np.ndarray, List]): - """Makes list/np.array of active learning scores serializable.""" - # the api only accepts float64s - if isinstance(scores, np.ndarray): - scores = scores.astype(np.float64) - - # convert to list and return - return list(scores) - - -class _SelectionMixin: - def upload_scores( - self, al_scores: Dict[str, NDArray[np.float_]], query_tag_id: str - ) -> None: - """Uploads active learning scores for a tag. - - Args: - al_scores: - Active learning scores. Must be a mapping between score names - and score arrays. The length of each score array must match samples - in the designated tag. - query_tag_id: ID of the desired tag. - - :meta private: # Skip docstring generation - """ - # iterate over all available score types and upload them - for score_type, score_values in al_scores.items(): - body = ActiveLearningScoreCreateRequest( - score_type=score_type, - scores=_parse_active_learning_scores(score_values), - ) - self._scores_api.create_or_update_active_learning_score_by_tag_id( - active_learning_score_create_request=body, - dataset_id=self.dataset_id, - tag_id=query_tag_id, - ) - - def selection( - self, - selection_config: SelectionConfig, - preselected_tag_id: Optional[str] = None, - query_tag_id: Optional[str] = None, - ) -> TagData: - """Performs a selection given the arguments. - - Args: - selection_config: - The configuration of the selection. - preselected_tag_id: - The tag defining the already chosen samples (e.g., already - labelled ones). Optional. - query_tag_id: - ID of the tag where samples should be fetched. None resolves to - `initial-tag`. Defaults to None. - - Returns: - The newly created tag of the selection. - - Raises: - RuntimeError: - When a tag with the tag name specified in the selection config already exists. - When `initial-tag` does not exist in the dataset. - When the selection task fails. - - :meta private: # Skip docstring generation - """ - - warnings.warn( - DeprecationWarning( - "ApiWorkflowClient.selection() is deprecated " - "and will be removed in the future." - ), - ) - - # make sure the tag name does not exist yet - tags = self.get_all_tags() - if selection_config.name in [tag.name for tag in tags]: - raise RuntimeError( - f"There already exists a tag with tag_name {selection_config.name}." - ) - if len(tags) == 0: - raise RuntimeError("There exists no initial-tag for this dataset.") - - # make sure we have an embedding id - try: - self.embedding_id - except AttributeError: - self.set_embedding_id_to_latest() - - # trigger the selection - payload = self._create_selection_create_request( - selection_config, preselected_tag_id, query_tag_id - ) - payload.row_count = self.get_all_tags()[0].tot_size - response = self._selection_api.trigger_sampling_by_id( - sampling_create_request=payload, - dataset_id=self.dataset_id, - embedding_id=self.embedding_id, - ) - job_id = response.job_id - - # poll the job status till the job is not running anymore - exception_counter = 0 # TODO; remove after solving https://github.com/lightly-ai/lightly-core/issues/156 - job_status_data = None - - wait_time_till_next_poll = getattr(self, "wait_time_till_next_poll", 1) - while ( - job_status_data is None - or job_status_data.status == JobState.RUNNING - or job_status_data.status == JobState.WAITING - or job_status_data.status == JobState.UNKNOWN - ): - # sleep before polling again - time.sleep(wait_time_till_next_poll) - # try to read the sleep time until the next poll from the status data - try: - job_status_data: JobStatusData = self._jobs_api.get_job_status_by_id( - job_id=job_id - ) - wait_time_till_next_poll = job_status_data.wait_time_till_next_poll - except Exception as err: - exception_counter += 1 - if exception_counter == 20: - print( - f"Selection job with job_id {job_id} could not be started because of error: {err}" - ) - raise err - - if job_status_data.status == JobState.FAILED: - raise RuntimeError( - f"Selection job with job_id {job_id} failed with error {job_status_data.error}" - ) - - # get the new tag from the job status - new_tag_id = job_status_data.result.data - if new_tag_id is None: - raise RuntimeError(f"TagId returned by job with job_id {job_id} is None.") - new_tag_data = self._tags_api.get_tag_by_tag_id( - dataset_id=self.dataset_id, tag_id=new_tag_id - ) - - return new_tag_data - - def _create_selection_create_request( - self, - selection_config: SelectionConfig, - preselected_tag_id: Optional[str], - query_tag_id: Optional[str], - ) -> SamplingCreateRequest: - """Creates a SamplingCreateRequest - - First, it checks how many samples are already labeled by - getting the number of samples in the preselected_tag_id. - Then the stopping_condition.n_samples - is set to be the number of already labeled samples + the selection_config.batch_size. - Last the SamplingCreateRequest is created with the necessary nested class instances. - - """ - - sampling_config = SamplingConfig( - stopping_condition=SamplingConfigStoppingCondition( - n_samples=selection_config.n_samples, - min_distance=selection_config.min_distance, - ) - ) - sampling_create_request = SamplingCreateRequest( - new_tag_name=selection_config.name, - method=selection_config.method, - config=sampling_config, - preselected_tag_id=preselected_tag_id, - query_tag_id=query_tag_id, - ) - return sampling_create_request diff --git a/lightly/api/api_workflow_tags.py b/lightly/api/api_workflow_tags.py deleted file mode 100644 index be70ebe22..000000000 --- a/lightly/api/api_workflow_tags.py +++ /dev/null @@ -1,276 +0,0 @@ -from typing import * - -from lightly.api.bitmask import BitMask -from lightly.openapi_generated.swagger_client.models import ( - TagArithmeticsOperation, - TagArithmeticsRequest, - TagBitMaskResponse, - TagCreateRequest, - TagData, -) - - -class TagDoesNotExistError(ValueError): - pass - - -class _TagsMixin: - def get_all_tags(self) -> List[TagData]: - """Gets all tags in the Lightly Platform from the current dataset. - - Returns: - A list of tags. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_all_tags() - [{'created_at': 1684750550014, - 'dataset_id': '646b40a18355e2f54c6d2200', - 'id': '646b40d6c06aae1b91294a9e', - 'last_modified_at': 1684750550014, - 'name': 'cool-tag', - 'preselected_tag_id': None, - ...}] - """ - return self._tags_api.get_tags_by_dataset_id(self.dataset_id) - - def get_tag_by_id(self, tag_id: str) -> TagData: - """Gets a tag from the current dataset by tag ID. - - Args: - tag_id: - ID of the requested tag. - - Returns: - Tag data for the requested tag. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_tag_by_id("646b40d6c06aae1b91294a9e") - {'created_at': 1684750550014, - 'dataset_id': '646b40a18355e2f54c6d2200', - 'id': '646b40d6c06aae1b91294a9e', - 'last_modified_at': 1684750550014, - 'name': 'cool-tag', - 'preselected_tag_id': None, - ...} - """ - tag_data = self._tags_api.get_tag_by_tag_id( - dataset_id=self.dataset_id, tag_id=tag_id - ) - return tag_data - - def get_tag_by_name(self, tag_name: str) -> TagData: - """Gets a tag from the current dataset by tag name. - - Args: - tag_name: - Name of the requested tag. - - Returns: - Tag data for the requested tag. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> client.get_tag_by_name("cool-tag") - {'created_at': 1684750550014, - 'dataset_id': '646b40a18355e2f54c6d2200', - 'id': '646b40d6c06aae1b91294a9e', - 'last_modified_at': 1684750550014, - 'name': 'cool-tag', - 'preselected_tag_id': None, - ...} - """ - tag_name_id_dict = {tag.name: tag.id for tag in self.get_all_tags()} - tag_id = tag_name_id_dict.get(tag_name, None) - if tag_id is None: - raise TagDoesNotExistError(f"Your tag_name does not exist: {tag_name}.") - return self.get_tag_by_id(tag_id) - - def get_filenames_in_tag( - self, - tag_data: TagData, - filenames_on_server: List[str] = None, - exclude_parent_tag: bool = False, - ) -> List[str]: - """Gets the filenames of samples under a tag. - - Args: - tag_data: - Information about the tag. - filenames_on_server: - List of all filenames on the server. If they are not given, - they need to be downloaded, which is a time-consuming operation. - exclude_parent_tag: - Excludes the parent tag in the returned filenames. - - Returns: - Filenames of all samples under the tag. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> tag = client.get_tag_by_name("cool-tag") - >>> client.get_filenames_in_tag(tag_data=tag) - ['image-1.png', 'image-2.png'] - - :meta private: # Skip docstring generation - """ - - if exclude_parent_tag: - parent_tag_id = tag_data.prev_tag_id - tag_arithmetics_request = TagArithmeticsRequest( - tag_id1=tag_data.id, - tag_id2=parent_tag_id, - operation=TagArithmeticsOperation.DIFFERENCE, - ) - bit_mask_response: TagBitMaskResponse = ( - self._tags_api.perform_tag_arithmetics_bitmask( - tag_arithmetics_request=tag_arithmetics_request, - dataset_id=self.dataset_id, - ) - ) - bit_mask_data = bit_mask_response.bit_mask_data - else: - bit_mask_data = tag_data.bit_mask_data - - if not filenames_on_server: - filenames_on_server = self.get_filenames() - - filenames_tag = BitMask.from_hex(bit_mask_data).masked_select_from_list( - filenames_on_server - ) - - return filenames_tag - - def create_tag_from_filenames( - self, fnames_new_tag: List[str], new_tag_name: str, parent_tag_id: str = None - ) -> TagData: - """Creates a new tag from a list of filenames. - - Args: - fnames_new_tag: - A list of filenames to be included in the new tag. - new_tag_name: - The name of the new tag. - parent_tag_id: - The tag defining where to sample from, default: None resolves to the initial-tag. - - Returns: - The newly created tag. - - Raises: - RuntimeError: - When a tag with the desired tag name already exists. - When `initial-tag` does not exist. - When any of the given files does not exist. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> filenames = ['image-1.png', 'image-2.png'] - >>> client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag') - {'id': '6470c4c1060894655c5a8ed5'} - """ - - # make sure the tag name does not exist yet - tags = self.get_all_tags() - if new_tag_name in [tag.name for tag in tags]: - raise RuntimeError( - f"There already exists a tag with tag_name {new_tag_name}." - ) - if len(tags) == 0: - raise RuntimeError("There exists no initial-tag for this dataset.") - - # fallback to initial tag if no parent tag is provided - if parent_tag_id is None: - parent_tag_id = next(tag.id for tag in tags if tag.name == "initial-tag") - - # get list of filenames from tag - fnames_server = self.get_filenames() - tot_size = len(fnames_server) - - # create new bitmask for the new tag - bitmask = BitMask(0) - fnames_new_tag = set(fnames_new_tag) - for i, fname in enumerate(fnames_server): - if fname in fnames_new_tag: - bitmask.set_kth_bit(i) - - # quick sanity check - num_selected_samples = len(bitmask.to_indices()) - if num_selected_samples != len(fnames_new_tag): - raise RuntimeError( - "An error occured when creating the new subset! " - f"Out of the {len(fnames_new_tag)} filenames you provided " - f"to create a new tag, only {num_selected_samples} have been " - "found on the server. " - "Make sure you use the correct filenames. " - f"Valid filename example from the dataset: {fnames_server[0]}" - ) - - # create new tag - tag_data_dict = { - "name": new_tag_name, - "prevTagId": parent_tag_id, - "bitMaskData": bitmask.to_hex(), - "totSize": tot_size, - "creator": self._creator, - } - - new_tag = self._tags_api.create_tag_by_dataset_id( - tag_create_request=TagCreateRequest.from_dict(tag_data_dict), - dataset_id=self.dataset_id, - ) - - return new_tag - - def delete_tag_by_id(self, tag_id: str) -> None: - """Deletes a tag from the current dataset. - - Args: - tag_id: - The id of the tag to be deleted. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> filenames = ['image-1.png', 'image-2.png'] - >>> tag_id = client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag')["id"] - >>> client.delete_tag_by_id(tag_id=tag_id) - """ - self._tags_api.delete_tag_by_tag_id(dataset_id=self.dataset_id, tag_id=tag_id) - - def delete_tag_by_name(self, tag_name: str) -> None: - """Deletes a tag from the current dataset. - - Args: - tag_name: - The name of the tag to be deleted. - - Examples: - >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") - >>> - >>> # Already created some Lightly Worker runs with this dataset - >>> client.set_dataset_id_by_name("my-dataset") - >>> filenames = ['image-1.png', 'image-2.png'] - >>> client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag') - >>> client.delete_tag_by_name(tag_name="new-tag") - """ - tag_data = self.get_tag_by_name(tag_name=tag_name) - self.delete_tag_by_id(tag_data.id) diff --git a/lightly/api/api_workflow_upload_embeddings.py b/lightly/api/api_workflow_upload_embeddings.py deleted file mode 100644 index bf28c1c2f..000000000 --- a/lightly/api/api_workflow_upload_embeddings.py +++ /dev/null @@ -1,270 +0,0 @@ -import csv -import io -import tempfile -import urllib.request -from datetime import datetime -from typing import List -from urllib.request import Request - -from lightly.api.utils import retry -from lightly.openapi_generated.swagger_client.models import ( - DatasetEmbeddingData, - DimensionalityReductionMethod, - Trigger2dEmbeddingJobRequest, - WriteCSVUrlData, -) -from lightly.utils import io as io_utils - - -class EmbeddingDoesNotExistError(ValueError): - pass - - -class _UploadEmbeddingsMixin: - def _get_csv_reader_from_read_url(self, read_url: str) -> None: - """Makes a get request to the signed read url and returns the .csv file.""" - request = Request(read_url, method="GET") - with urllib.request.urlopen(request) as response: - buffer = io.StringIO(response.read().decode("utf-8")) - reader = csv.reader(buffer) - - return reader - - def set_embedding_id_to_latest(self) -> None: - """Sets the embedding ID in the API client to the latest embedding ID in the current dataset. - - :meta private: # Skip docstring generation - """ - embeddings_on_server: List[ - DatasetEmbeddingData - ] = self._embeddings_api.get_embeddings_by_dataset_id( - dataset_id=self.dataset_id - ) - if len(embeddings_on_server) == 0: - raise RuntimeError( - f"There are no known embeddings for dataset_id {self.dataset_id}." - ) - # return first entry as the API returns newest first - self.embedding_id = embeddings_on_server[0].id - - def get_embedding_by_name( - self, name: str, ignore_suffix: bool = True - ) -> DatasetEmbeddingData: - """Fetches an embedding in the current dataset by name. - - Args: - name: - The name of the desired embedding. - ignore_suffix: - If true, a suffix of the embedding name in the current dataset - is ignored. - - Returns: - The embedding data. - - Raises: - EmbeddingDoesNotExistError: - If the name does not match the name of an embedding - on the server. - - """ - embeddings_on_server: List[ - DatasetEmbeddingData - ] = self._embeddings_api.get_embeddings_by_dataset_id( - dataset_id=self.dataset_id - ) - try: - if ignore_suffix: - embedding = next( - embedding - for embedding in embeddings_on_server - if embedding.name.startswith(name) - ) - else: - embedding = next( - embedding - for embedding in embeddings_on_server - if embedding.name == name - ) - except StopIteration: - raise EmbeddingDoesNotExistError( - f"Embedding with the specified name " - f"does not exist on the server: {name}" - ) - return embedding - - def upload_embeddings(self, path_to_embeddings_csv: str, name: str) -> None: - """Uploads embeddings to the Lightly Platform. - - First checks that the specified embedding name is not on the server. If it is, the upload is aborted. - Then creates a new csv file with the embeddings in the order specified on the server. Next uploads it - to the Lightly Platform. The received embedding ID is stored in the API client. - - Args: - path_to_embeddings_csv: - The path to the .csv containing the embeddings, e.g. "path/to/embeddings.csv" - name: - The name of the embedding. If an embedding with such a name already exists on the server, - the upload is aborted. - - :meta private: # Skip docstring generation - """ - io_utils.check_embeddings( - path_to_embeddings_csv, remove_additional_columns=True - ) - - # Try to append the embeddings on the server, if they exist - try: - embedding = self.get_embedding_by_name(name, ignore_suffix=True) - # -> append rows from server - print("Appending embeddings from server.") - self.append_embeddings(path_to_embeddings_csv, embedding.id) - now = datetime.now().strftime("%Y%m%d_%Hh%Mm%Ss") - name = f"{name}_{now}" - except EmbeddingDoesNotExistError: - pass - - # create a new csv with the filenames in the desired order - rows_csv = self._order_csv_by_filenames( - path_to_embeddings_csv=path_to_embeddings_csv - ) - - # get the URL to upload the csv to - response: WriteCSVUrlData = ( - self._embeddings_api.get_embeddings_csv_write_url_by_id( - self.dataset_id, name=name - ) - ) - self.embedding_id = response.embedding_id - signed_write_url = response.signed_write_url - - # save the csv rows in a temporary in-memory string file - # using a csv writer and then read them as bytes - with tempfile.SpooledTemporaryFile(mode="rw") as f: - writer = csv.writer(f) - writer.writerows(rows_csv) - f.seek(0) - embeddings_csv_as_bytes = f.read().encode("utf-8") - - # write the bytes to a temporary in-memory byte file - with tempfile.SpooledTemporaryFile(mode="r+b") as f_bytes: - f_bytes.write(embeddings_csv_as_bytes) - f_bytes.seek(0) - retry( - self.upload_file_with_signed_url, - file=f_bytes, - signed_write_url=signed_write_url, - ) - - # trigger the 2d embeddings job - for dimensionality_reduction_method in [ - DimensionalityReductionMethod.PCA, - DimensionalityReductionMethod.TSNE, - DimensionalityReductionMethod.UMAP, - ]: - body = Trigger2dEmbeddingJobRequest( - dimensionality_reduction_method=dimensionality_reduction_method - ) - self._embeddings_api.trigger2d_embeddings_job( - trigger2d_embedding_job_request=body, - dataset_id=self.dataset_id, - embedding_id=self.embedding_id, - ) - - def append_embeddings(self, path_to_embeddings_csv: str, embedding_id: str) -> None: - """Concatenates embeddings from the Lightly Platform to the local ones. - - Loads the embedding csv file with the corresponding embedding ID in the current dataset - and appends all of its rows to the local embeddings file located at - 'path_to_embeddings_csv'. - - Args: - path_to_embeddings_csv: - The path to the csv containing the local embeddings. - embedding_id: - ID of the embedding summary of the embeddings on the Lightly Platform. - - Raises: - RuntimeError: - If the number of columns in the local embeddings file and that of the remote - embeddings file mismatch. - - :meta private: # Skip docstring generation - """ - - # read embedding from API - embedding_read_url = self._embeddings_api.get_embeddings_csv_read_url_by_id( - self.dataset_id, embedding_id - ) - embedding_reader = self._get_csv_reader_from_read_url(embedding_read_url) - rows = list(embedding_reader) - header, online_rows = rows[0], rows[1:] - - # read local embedding - with open(path_to_embeddings_csv, "r") as f: - local_rows = list(csv.reader(f)) - - if len(local_rows[0]) != len(header): - raise RuntimeError( - "Column mismatch! Number of columns in local and remote" - f" embeddings files must match but are {len(local_rows[0])}" - f" and {len(header)} respectively." - ) - - local_rows = local_rows[1:] - - # combine online and local embeddings - total_rows = [header] - filename_to_local_row = {row[0]: row for row in local_rows} - for row in online_rows: - # pick local over online filename if it exists - total_rows.append(filename_to_local_row.pop(row[0], row)) - # add all local rows which were not added yet - total_rows.extend(list(filename_to_local_row.values())) - - # save embeddings again - with open(path_to_embeddings_csv, "w") as f: - writer = csv.writer(f) - writer.writerows(total_rows) - - def _order_csv_by_filenames(self, path_to_embeddings_csv: str) -> List[str]: - """Orders the rows in a csv according to the order specified on the server and saves it as a new file. - - Args: - path_to_embeddings_csv: - the path to the csv to order - - Returns: - the filepath to the new csv - - """ - with open(path_to_embeddings_csv, "r") as f: - data = csv.reader(f) - - rows = list(data) - header_row = rows[0] - rows_without_header = rows[1:] - index_filenames = header_row.index("filenames") - filenames = [row[index_filenames] for row in rows_without_header] - - filenames_on_server = self.get_filenames() - - if len(filenames) != len(filenames_on_server): - raise ValueError( - f"There are {len(filenames)} rows in the embedding file, but " - f"{len(filenames_on_server)} filenames/samples on the server." - ) - if set(filenames) != set(filenames_on_server): - raise ValueError( - f"The filenames in the embedding file and " - f"the filenames on the server do not align" - ) - - rows_without_header_ordered = self._order_list_by_filenames( - filenames, rows_without_header - ) - - rows_csv = [header_row] - rows_csv += rows_without_header_ordered - - return rows_csv diff --git a/lightly/api/api_workflow_upload_metadata.py b/lightly/api/api_workflow_upload_metadata.py deleted file mode 100644 index 87aa55f4e..000000000 --- a/lightly/api/api_workflow_upload_metadata.py +++ /dev/null @@ -1,253 +0,0 @@ -from concurrent.futures import ThreadPoolExecutor -from typing import Any, Dict, List, Union - -from requests import Response -from tqdm import tqdm - -from lightly.api.utils import paginate_endpoint, retry -from lightly.openapi_generated.swagger_client.models import ( - ConfigurationEntry, - ConfigurationSetRequest, - SampleDataModes, - SamplePartialMode, - SampleUpdateRequest, -) -from lightly.utils import hipify -from lightly.utils.io import COCO_ANNOTATION_KEYS - - -class InvalidCustomMetadataWarning(Warning): - pass - - -def _assert_key_exists_in_custom_metadata(key: str, dictionary: Dict[str, Any]): - """Raises a formatted KeyError if key is not a key of the dictionary.""" - if key not in dictionary.keys(): - raise KeyError( - f"Key {key} not found in custom metadata.\n" - f"Found keys: {dictionary.keys()}" - ) - - -class _UploadCustomMetadataMixin: - """Mixin of helpers to allow upload of custom metadata.""" - - def verify_custom_metadata_format(self, custom_metadata: Dict) -> None: - """Verifies that the custom metadata is in the correct format. - - Args: - custom_metadata: - Dictionary of custom metadata, see upload_custom_metadata for - the required format. - - Raises: - KeyError: - If "images" or "metadata" aren't a key of custom_metadata. - - """ - _assert_key_exists_in_custom_metadata( - COCO_ANNOTATION_KEYS.images, custom_metadata - ) - _assert_key_exists_in_custom_metadata( - COCO_ANNOTATION_KEYS.custom_metadata, custom_metadata - ) - - def index_custom_metadata_by_filename( - self, custom_metadata: Dict[str, Any] - ) -> Dict[str, Union[Dict, None]]: - """Creates an index to lookup custom metadata by filename. - - Args: - custom_metadata: - Dictionary of custom metadata, see upload_custom_metadata for - the required format. - - Returns: - A dictionary mapping from filenames to custom metadata. - If there are no annotations for a filename, the custom metadata - is None instead. - - :meta private: # Skip docstring generation - """ - - # The mapping is filename -> image_id -> custom_metadata - # This mapping is created in linear time. - filename_to_image_id = { - image_info[COCO_ANNOTATION_KEYS.images_filename]: image_info[ - COCO_ANNOTATION_KEYS.images_id - ] - for image_info in custom_metadata[COCO_ANNOTATION_KEYS.images] - } - image_id_to_custom_metadata = { - metadata[COCO_ANNOTATION_KEYS.custom_metadata_image_id]: metadata - for metadata in custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata] - } - filename_to_metadata = { - filename: image_id_to_custom_metadata.get(image_id, None) - for (filename, image_id) in filename_to_image_id.items() - } - return filename_to_metadata - - def upload_custom_metadata( - self, - custom_metadata: Dict[str, Any], - verbose: bool = False, - max_workers: int = 8, - ) -> None: - """Uploads custom metadata to the Lightly Platform. - - The custom metadata is expected in a format similar to the COCO annotations: - Under the key "images" there should be a list of dictionaries, each with - a file_name and id. Under the key "metadata", the custom metadata is stored - as a list of dictionaries, each with an image ID that corresponds to an image - under the key "images". - - Example: - >>> custom_metadata = { - >>> "images": [ - >>> { - >>> "file_name": "image0.jpg", - >>> "id": 0, - >>> }, - >>> { - >>> "file_name": "image1.jpg", - >>> "id": 1, - >>> } - >>> ], - >>> "metadata": [ - >>> { - >>> "image_id": 0, - >>> "number_of_people": 3, - >>> "weather": { - >>> "scenario": "cloudy", - >>> "temperature": 20.3 - >>> } - >>> }, - >>> { - >>> "image_id": 1, - >>> "number_of_people": 1, - >>> "weather": { - >>> "scenario": "rainy", - >>> "temperature": 15.0 - >>> } - >>> } - >>> ] - >>> } - - Args: - custom_metadata: - Custom metadata as described above. - verbose: - If True, displays a progress bar during the upload. - max_workers: - Maximum number of concurrent threads during upload. - - :meta private: # Skip docstring generation - """ - - self.verify_custom_metadata_format(custom_metadata) - - # For each metadata, we need the corresponding sample_id - # on the server. The mapping is: - # metadata -> image_id -> filename -> sample_id - - image_id_to_filename = { - image_info[COCO_ANNOTATION_KEYS.images_id]: image_info[ - COCO_ANNOTATION_KEYS.images_filename - ] - for image_info in custom_metadata[COCO_ANNOTATION_KEYS.images] - } - - samples: List[SampleDataModes] = list( - paginate_endpoint( - self._samples_api.get_samples_partial_by_dataset_id, - page_size=25000, # as this information is rather small, we can request a lot of samples at once - dataset_id=self.dataset_id, - mode=SamplePartialMode.FILENAMES, - ) - ) - - filename_to_sample_id = {sample.file_name: sample.id for sample in samples} - - upload_requests = [] - for metadata in custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata]: - image_id = metadata[COCO_ANNOTATION_KEYS.custom_metadata_image_id] - filename = image_id_to_filename.get(image_id, None) - if filename is None: - hipify.print_as_warning( - "No image found for custom metadata annotation " - f"with image_id {image_id}. " - "This custom metadata annotation is skipped. ", - InvalidCustomMetadataWarning, - ) - continue - sample_id = filename_to_sample_id.get(filename, None) - if sample_id is None: - hipify.print_as_warning( - "You tried to upload custom metadata for a sample with " - f"filename {{{filename}}}, " - "but a sample with this filename " - "does not exist on the server. " - "This custom metadata annotation is skipped. ", - InvalidCustomMetadataWarning, - ) - continue - upload_request = (metadata, sample_id) - upload_requests.append(upload_request) - - # retry upload if it times out - def upload_sample_metadata(upload_request): - metadata, sample_id = upload_request - request = SampleUpdateRequest(custom_meta_data=metadata) - return retry( - self._samples_api.update_sample_by_id, - sample_update_request=request, - dataset_id=self.dataset_id, - sample_id=sample_id, - ) - - # Upload in parallel with a limit on the number of concurrent requests - with ThreadPoolExecutor(max_workers=max_workers) as executor: - # get iterator over results - results = executor.map(upload_sample_metadata, upload_requests) - if verbose: - results = tqdm(results, unit="metadata", total=len(upload_requests)) - # iterate over results to make sure they are completed - list(results) - - def create_custom_metadata_config( - self, name: str, configs: List[ConfigurationEntry] - ) -> Response: - """Creates custom metadata config from a list of configurations. - - Args: - name: - The name of the custom metadata configuration. - configs: - List of metadata configuration entries. - - Returns: - The API response. - - Examples: - >>> from lightly.openapi_generated.swagger_codegen.models.configuration_entry import ConfigurationEntry - >>> entry = ConfigurationEntry( - >>> name='Weather', - >>> path='weather', - >>> default_value='unknown', - >>> value_data_type='CATEGORICAL_STRING', - >>> ) - >>> - >>> client.create_custom_metadata_config( - >>> 'My Custom Metadata', - >>> [entry], - >>> ) - - :meta private: # Skip docstring generation - """ - config_set_request = ConfigurationSetRequest(name=name, configs=configs) - resp = self._metadata_configurations_api.create_meta_data_configuration( - configuration_set_request=config_set_request, - dataset_id=self.dataset_id, - ) - return resp diff --git a/lightly/api/bitmask.py b/lightly/api/bitmask.py deleted file mode 100644 index a79f9f69f..000000000 --- a/lightly/api/bitmask.py +++ /dev/null @@ -1,221 +0,0 @@ -""" Module to work with Lightly BitMasks """ - -# Copyright (c) 2020. Lightly AG and its affiliates. -# All Rights Reserved -import copy -from typing import List - - -def _hex_to_int(hexstring: str) -> int: - """Converts a hex string representation of an integer to an integer.""" - return int(hexstring, 16) - - -def _bin_to_int(binstring: str) -> int: - """Converts a binary string representation of an integer to an integer.""" - return int(binstring, 2) - - -def _int_to_hex(x: int) -> str: - """Converts an integer to a hex string representation.""" - return hex(x) - - -def _int_to_bin(x: int) -> str: - """Converts an integer to a binary string representation.""" - return bin(x) - - -def _get_nonzero_bits(x: int) -> List[int]: - """Returns a list of indices of nonzero bits in x.""" - offset = 0 - nonzero_bit_indices = [] - while x > 0: - # if the number is odd, there is a nonzero bit at offset - if x % 2 > 0: - nonzero_bit_indices.append(offset) - # increment the offset and divide the number x by two (rounding down) - offset += 1 - x = x // 2 - return nonzero_bit_indices - - -def _invert(x: int, total_size: int) -> int: - """Flips every bit of x as if x was an unsigned integer.""" - # use XOR of x and 0xFFFFFF to get the inverse - return x ^ (2**total_size - 1) - - -def _union(x: int, y: int) -> int: - """Uses bitwise OR to get the union of the two masks.""" - return x | y - - -def _intersection(x: int, y: int) -> int: - """Uses bitwise AND to get the intersection of the two masks.""" - return x & y - - -def _get_kth_bit(x: int, k: int) -> int: - """Returns the kth bit in the mask from the right.""" - mask = 1 << k - return x & mask - - -def _set_kth_bit(x: int, k: int) -> int: - """Sets the kth bit in the mask from the right.""" - mask = 1 << k - return x | mask - - -def _unset_kth_bit(x: int, k: int) -> int: - """Clears the kth bit in the mask from the right.""" - mask = ~(1 << k) - return x & mask - - -class BitMask: - """Utility class to represent and manipulate tags. - Attributes: - x: - An integer representation of the binary mask. - Examples: - >>> # the following are equivalent - >>> mask = BitMask(6) - >>> mask = BitMask.from_hex('0x6') - >>> mask = Bitmask.from_bin('0b0110') - >>> # for a dataset with 10 images, assume the following tag - >>> # 0001011001 where the 1st, 4th, 5th and 7th image are selected - >>> # this tag would be stored as 0x59. - >>> hexstring = '0x59' # what you receive from the api - >>> mask = BitMask.from_hex(hexstring) # create a bitmask from it - >>> indices = mask.to_indices() # get list of indices which are one - >>> # indices is [0, 3, 4, 6] - """ - - def __init__(self, x): - self.x = x - - @classmethod - def from_hex(cls, hexstring: str): - """Creates a bit mask object from a hexstring.""" - return cls(_hex_to_int(hexstring)) - - @classmethod - def from_bin(cls, binstring: str): - """Creates a BitMask from a binary string.""" - return cls(_bin_to_int(binstring)) - - @classmethod - def from_length(cls, length: int): - """Creates a all-true bitmask of a predefined length""" - binstring = "0b" + "1" * length - return cls.from_bin(binstring) - - def to_hex(self): - """Creates a BitMask from a hex string.""" - return _int_to_hex(self.x) - - def to_bin(self): - """Returns a binary string representing the bit mask.""" - return _int_to_bin(self.x) - - def to_indices(self) -> List[int]: - """Returns the list of indices bits which are set to 1 from the right. - Examples: - >>> mask = BitMask('0b0101') - >>> indices = mask.to_indices() - >>> # indices is [0, 2] - """ - return _get_nonzero_bits(self.x) - - def invert(self, total_size: int): - """Sets every 0 to 1 and every 1 to 0 in the bitstring. - - Args: - total_size: - Total size of the tag. - - """ - self.x = _invert(self.x, total_size) - - def complement(self): - """Same as invert but with the appropriate name.""" - self.invert() - - def union(self, other): - """Calculates the union of two bit masks. - Examples: - >>> mask1 = BitMask.from_bin('0b0011') - >>> mask2 = BitMask.from_bin('0b1100') - >>> mask1.union(mask2) - >>> # mask1.binstring is '0b1111' - """ - self.x = _union(self.x, other.x) - - def intersection(self, other): - """Calculates the intersection of two bit masks. - Examples: - >>> mask1 = BitMask.from_bin('0b0011') - >>> mask2 = BitMask.from_bin('0b1100') - >>> mask1.intersection(mask2) - >>> # mask1.binstring is '0b0000' - """ - self.x = _intersection(self.x, other.x) - - def difference(self, other): - """Calculates the difference of two bit masks. - Examples: - >>> mask1 = BitMask.from_bin('0b0111') - >>> mask2 = BitMask.from_bin('0b1100') - >>> mask1.difference(mask2) - >>> # mask1.binstring is '0b0011' - """ - self.union(other) - self.x = self.x - other.x - - def __sub__(self, other): - ret = copy.deepcopy(self) - ret.difference(other) - return ret - - def __eq__(self, other): - return self.to_bin() == other.to_bin() - - def masked_select_from_list(self, list_: List): - """Returns a subset of a list depending on the bitmask. - - The bitmask is read from right to left, i.e. the least significant bit - corresponds to index 0. - - Examples: - >>> list_to_subset = [4, 7, 9, 1] - >>> mask = BitMask.from_bin("0b0101") - >>> masked_list = mask.masked_select_from_list(list_to_subset) - >>> # masked_list = [4, 9] - - """ - indices = self.to_indices() - return [list_[index] for index in indices] - - def get_kth_bit(self, k: int) -> bool: - """Returns the boolean value of the kth bit from the right.""" - return _get_kth_bit(self.x, k) > 0 - - def set_kth_bit(self, k: int): - """Sets the kth bit from the right to '1'. - Examples: - >>> mask = BitMask('0b0000') - >>> mask.set_kth_bit(2) - >>> # mask.binstring is '0b0100' - """ - self.x = _set_kth_bit(self.x, k) - - def unset_kth_bit(self, k: int): - """Unsets the kth bit from the right to '0'. - Examples: - >>> mask = BitMask('0b1111') - >>> mask.unset_kth_bit(2) - >>> # mask.binstring is '0b1011' - """ - self.x = _unset_kth_bit(self.x, k) diff --git a/lightly/api/download.py b/lightly/api/download.py deleted file mode 100644 index 88b8d2a33..000000000 --- a/lightly/api/download.py +++ /dev/null @@ -1,542 +0,0 @@ -import concurrent.futures -import os -import pathlib -import shutil -import threading -import warnings -from concurrent.futures import ThreadPoolExecutor -from typing import Callable, Dict, Iterable, List, Optional, Tuple, Type, Union - -import PIL -import requests -import tqdm - -from lightly.api import utils - -try: - import av -except ModuleNotFoundError: - av = ModuleNotFoundError( - "PyAV is not installed on your system. Please install it to use the video" - "functionalities. See https://github.com/mikeboers/PyAV#installation for" - "installation instructions." - ) - -DEFAULT_VIDEO_TIMEOUT = 60 * 5 # seconds - - -def _check_av_available() -> None: - if isinstance(av, Exception): - raise av - - -def download_image( - url: str, - session: requests.Session = None, - retry_fn: Callable = utils.retry, - request_kwargs: Optional[Dict] = None, -) -> PIL.Image.Image: - """Downloads an image from a url. - - Args: - url: - The url where the image is downloaded from. - session: - Session object to persist certain parameters across requests. - retry_fn: - Retry function that handles failed downloads. - request_kwargs: - Additional parameters passed to requests.get(). - - Returns: - The downloaded image. - - """ - request_kwargs = request_kwargs or {} - request_kwargs.setdefault("stream", True) - request_kwargs.setdefault("timeout", 10) - - def load_image(url, req, request_kwargs): - with req.get(url=url, **request_kwargs) as response: - response.raise_for_status() - image = PIL.Image.open(response.raw) - image.load() - return image - - req = requests if session is None else session - image = retry_fn(load_image, url, req, request_kwargs) - return image - - -if not isinstance(av, ModuleNotFoundError): - - def download_all_video_frames( - url: str, - timestamp: Optional[int] = None, - as_pil_image: int = True, - thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, - video_channel: int = 0, - retry_fn: Callable = utils.retry, - timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, - ) -> Iterable[Union[PIL.Image.Image, av.VideoFrame]]: - """Lazily retrieves all frames from a video stored at the given url. - - Args: - url: - The url where video is downloaded from. - timestamp: - Timestamp in pts from the start of the video from which the frame - download should start. See https://pyav.org/docs/develop/api/time.html#time - for details on pts. - as_pil_image: - Whether to return the frame as PIL.Image. - thread_type: - Which multithreading method to use for decoding the video. - See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType - for details. - video_channel: - The video channel from which frames are loaded. - retry_fn: - Retry function that handles errors when opening the video container. - timeout: - Time in seconds to wait for new video data before giving up. - Timeout must either be an (open_timeout, read_timeout) tuple - or a single value which will be used as open and read timeout. - Timeouts only apply to individual steps during the download, - the complete video download can take much longer. - See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open - for details. - - Returns: - A generator that loads and returns a single frame per step. - - """ - _check_av_available() - timestamp = 0 if timestamp is None else timestamp - if timestamp < 0: - raise ValueError(f"Negative timestamp is not allowed: {timestamp}") - - with retry_fn(av.open, url, timeout=timeout) as container: - stream = container.streams.video[video_channel] - stream.thread_type = thread_type - - # seek to last keyframe before the timestamp - container.seek(timestamp, any_frame=False, backward=True, stream=stream) - - frame = None - for frame in container.decode(stream): - # advance from keyframe until correct timestamp is reached - if frame.pts < timestamp: - continue - # yield next frame - if as_pil_image: - yield frame.to_image() - else: - yield frame - - def download_video_frame( - url: str, timestamp: int, *args, **kwargs - ) -> Union[PIL.Image.Image, av.VideoFrame, None]: - """ - Wrapper around download_video_frames_at_timestamps - for downloading only a single frame. - """ - frames = download_video_frames_at_timestamps( - url, timestamps=[timestamp], *args, **kwargs - ) - frames = list(frames) - return frames[0] - - def video_frame_count( - url: str, - video_channel: int = 0, - thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, - ignore_metadata: bool = False, - retry_fn: Callable = utils.retry, - timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, - ) -> Optional[int]: - """Returns the number of frames in the video from the given url. - - The video is only decoded if no information about the number of frames is - stored in the video metadata. - - Args: - url: - The url of the video. - video_channel: - The video stream channel from which to find the number of frames. - thread_type: - Which multithreading method to use for decoding the video. - See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType - for details. - ignore_metadata: - If True, frames are counted by iterating through the video instead - of relying on the video metadata. - timeout: - Time in seconds to wait for new video data before giving up. - Timeout must either be an (open_timeout, read_timeout) tuple - or a single value which will be used as open and read timeout. - Timeouts only apply to individual steps during the download, - the complete video download can take much longer. - See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open - for details. - - Returns: - The number of frames in the video. Can be None if the video could not be - decoded. - - """ - with retry_fn(av.open, url, timeout=timeout) as container: - stream = container.streams.video[video_channel] - num_frames = 0 if ignore_metadata else stream.frames - # If number of frames not stored in the video file we have to decode all - # frames and count them. - if num_frames == 0: - stream.thread_type = thread_type - for _ in container.decode(stream): - num_frames += 1 - return num_frames - - def all_video_frame_counts( - urls: List[str], - max_workers: int = None, - video_channel: int = 0, - thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, - ignore_metadata: bool = False, - retry_fn: Callable = utils.retry, - exceptions_indicating_empty_video: Tuple[Type[BaseException], ...] = ( - RuntimeError, - ), - progress_bar: Optional[tqdm.tqdm] = None, - ) -> List[Optional[int]]: - """Finds the number of frames in the videos at the given urls. - - Videos are only decoded if no information about the number of frames is - stored in the video metadata. - - Args: - urls: - A list of video urls. - max_workers: - Maximum number of workers. If `None` the number of workers is chosen - based on the number of available cores. - video_channel: - The video stream channel from which to find the number of frames. - thread_type: - Which multithreading method to use for decoding the video. - See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType - for details. - ignore_metadata: - If True, frames are counted by iterating through the video instead - of relying on the video metadata. - retry_fn: - Retry function that handles errors when loading a video. - exceptions_indicating_empty_video: - If an exception in exceptions_indicating_empty_video is raised, - the video is considered as empty and None is returned as number - of frames for the video. - - Returns: - A list with the number of frames per video. Contains None for all videos - that could not be decoded. - - """ - - def job(url): - try: - return retry_fn( - video_frame_count, - url=url, - video_channel=video_channel, - thread_type=thread_type, - ignore_metadata=ignore_metadata, - retry_fn=retry_fn, - ) - except exceptions_indicating_empty_video: - return - - with ThreadPoolExecutor(max_workers=max_workers) as executor: - frame_counts = [] - total_count = 0 - for count in executor.map(job, urls): - frame_counts.append(count) - if progress_bar is not None: - if count is not None: - total_count += count - progress_bar.update(1) - progress_bar.set_description(f"Total frames found: {total_count}") - return frame_counts - - def download_video_frames_at_timestamps( - url: str, - timestamps: List[int], - as_pil_image: int = True, - thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, - video_channel: int = 0, - seek_to_first_frame: bool = True, - retry_fn: Callable = utils.retry, - timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, - ) -> Iterable[Union[PIL.Image.Image, av.VideoFrame]]: - """Lazily retrieves frames from a video at a specific timestamp stored at the given url. - - Args: - url: - The url where video is downloaded from. - timestamps: - Timestamps in pts from the start of the video. The images - at these timestamps are returned. - The timestamps must be strictly monotonically ascending. - See https://pyav.org/docs/develop/api/time.html#time - for details on pts. - as_pil_image: - Whether to return the frame as PIL.Image. - thread_type: - Which multithreading method to use for decoding the video. - See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType - for details. - video_channel: - The video channel from which frames are loaded. - seek_to_first_frame: - Boolean indicating whether to seek to the first frame. - retry_fn: - Retry function that handles errors when opening the video container. - timeout: - Time in seconds to wait for new video data before giving up. - Timeout must either be an (open_timeout, read_timeout) tuple - or a single value which will be used as open and read timeout. - Timeouts only apply to individual steps during the download, - the complete video download can take much longer. - See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open - for details. - - Returns: - A generator that loads and returns a single frame per step. - - """ - _check_av_available() - - if len(timestamps) == 0: - return [] - - if any(timestamps[i + 1] <= timestamps[i] for i in range(len(timestamps) - 1)): - raise ValueError( - "The timestamps must be sorted " - "strictly monotonically ascending, but are not." - ) - min_timestamp = timestamps[0] - - if min_timestamp < 0: - raise ValueError(f"Negative timestamp is not allowed: {min_timestamp}") - - with retry_fn(av.open, url, timeout=timeout) as container: - stream = container.streams.video[video_channel] - stream.thread_type = thread_type - - if seek_to_first_frame: - # seek to last keyframe before the min_timestamp - container.seek( - min_timestamp, any_frame=False, backward=True, stream=stream - ) - - index_timestamp = 0 - for frame in container.decode(stream): - # advance from keyframe until correct timestamp is reached - if frame.pts > timestamps[index_timestamp]: - # dropped frames! - break - - # it's ok to check by equality because timestamps are ints - if frame.pts == timestamps[index_timestamp]: - # yield next frame - if as_pil_image: - yield frame.to_image() - else: - yield frame - - # update the timestamp - index_timestamp += 1 - - if index_timestamp >= len(timestamps): - return - - leftovers = timestamps[index_timestamp:] - - # sometimes frames are skipped when we seek to the first frame - # let's retry downloading these frames without seeking - retry_skipped_timestamps = seek_to_first_frame - if retry_skipped_timestamps: - warnings.warn( - f"Timestamps {leftovers} could not be decoded! Retrying from the start..." - ) - frames = download_video_frames_at_timestamps( - url, - leftovers, - as_pil_image=as_pil_image, - thread_type=thread_type, - video_channel=video_channel, - seek_to_first_frame=False, - retry_fn=retry_fn, - ) - for frame in frames: - yield frame - return - - raise RuntimeError( - f"Timestamps {leftovers} in video {url} could not be decoded!" - ) - - -def download_and_write_file( - url: str, - output_path: str, - session: requests.Session = None, - retry_fn: Callable = utils.retry, - request_kwargs: Optional[Dict] = None, -) -> None: - """Downloads a file from a url and saves it to disk - - Args: - url: - Url of the file to download. - output_path: - Where to store the file, including filename and extension. - session: - Session object to persist certain parameters across requests. - retry_fn: - Retry function that handles failed downloads. - request_kwargs: - Additional parameters passed to requests.get(). - """ - request_kwargs = request_kwargs or {} - request_kwargs.setdefault("stream", True) - request_kwargs.setdefault("timeout", 10) - req = requests if session is None else session - out_path = pathlib.Path(output_path) - out_path.parent.mkdir(parents=True, exist_ok=True) - with retry_fn(req.get, url=url, **request_kwargs) as response: - response.raise_for_status() - with open(out_path, "wb") as file: - shutil.copyfileobj(response.raw, file) - - -def download_and_write_all_files( - file_infos: List[Tuple[str, str]], - output_dir: str, - max_workers: int = None, - verbose: bool = False, - retry_fn: Callable = utils.retry, - request_kwargs: Optional[Dict] = None, -) -> None: - """Downloads all files and writes them to disk. - - Args: - file_infos: - List containing (filename, url) tuples. - output_dir: - Output directory where files will stored in. - max_workers: - Maximum number of workers. If `None` the number of workers is chosen - based on the number of available cores. - verbose: - Shows progress bar if set to `True`. - retry_fn: - Retry function that handles failed downloads. - request_kwargs: - Additional parameters passed to requests.get(). - - """ - - def thread_download_and_write( - file_info: Tuple[str, str], - output_dir: str, - lock: threading.Lock, - sessions: Dict[str, requests.Session], - **kwargs, - ): - filename, url = file_info - output_path = os.path.join(output_dir, filename) - thread_id = threading.get_ident() - - lock.acquire() - session = sessions.get(thread_id) - if session is None: - session = requests.Session() - sessions[thread_id] = session - lock.release() - - download_and_write_file(url, output_path, session, **kwargs) - - # retry download if failed - def job(**kwargs): - retry_fn(thread_download_and_write, **kwargs) - - # dict where every thread stores its requests.Session - sessions = dict() - # use lock because sessions dict is shared between threads - lock = threading.Lock() - - with ThreadPoolExecutor(max_workers=max_workers) as executor: - futures_to_file_info = { - executor.submit( - job, - file_info=file_info, - output_dir=output_dir, - lock=lock, - sessions=sessions, - retry_fn=retry_fn, - request_kwargs=request_kwargs, - ): file_info - for file_info in file_infos - } - futures = concurrent.futures.as_completed(futures_to_file_info) - if verbose: - futures = tqdm.tqdm(futures) - for future in futures: - filename, url = futures_to_file_info[future] - try: - future.result() - except Exception as ex: - warnings.warn(f"Could not download {filename} from {url}") - - -def download_prediction_file( - url: str, - session: requests.Session = None, - request_kwargs: Optional[Dict] = None, -) -> Dict: - """Same as download_json_file. Keep this for backwards compatability. - - See download_json_file. - - """ - return download_json_file(url, session=session, request_kwargs=request_kwargs) - - -def download_json_file( - url: str, - session: requests.Session = None, - request_kwargs: Optional[Dict] = None, -) -> Dict: - """Downloads a json file from the provided read-url. - - Args: - url: - Url of the file to download. - session: - Session object to persist certain parameters across requests. - request_kwargs: - Additional parameters passed to requests.get(). - - Returns the content of the json file as dictionary. Raises HTTPError in case - of an error. - - """ - request_kwargs = request_kwargs or {} - request_kwargs.setdefault("stream", True) - request_kwargs.setdefault("timeout", 10) - req = requests if session is None else session - - response = req.get(url, **request_kwargs) - response.raise_for_status() - - return response.json() diff --git a/lightly/api/patch.py b/lightly/api/patch.py deleted file mode 100644 index e754160cd..000000000 --- a/lightly/api/patch.py +++ /dev/null @@ -1,58 +0,0 @@ -import logging -from typing import Any, Dict, Type - - -def make_swagger_configuration_picklable( - configuration_cls: Type, -) -> None: - """Adds __getstate__ and __setstate__ methods to swagger configuration to make it - picklable. - - This doesn't make all swagger classes picklable. Notably, the ApiClient and - and RESTClientObject classes are not picklable. Use the picklable - LightlySwaggerApiClient and LightlySwaggerRESTClientObject classes instead. - """ - configuration_cls.__getstate__ = _Configuration__getstate__ - configuration_cls.__setstate__ = _Configuration__setstate__ - - -def _Configuration__getstate__(self: Type) -> Dict[str, Any]: - state = self.__dict__.copy() - - # Remove all loggers as they are not picklable. This removes the package_logger - # and urllib3_logger. Note that we cannot remove the with: - # `del state["logger"]["package_logger"]` as this would modify self.__dict__ due to - # shallow copy. - state["logger"] = {} - - # formatter, stream_handler and file_handler are not picklable - state["logger_formatter"] = None - state["logger_stream_handler"] = None - state["logger_file_handler"] = None - return state - - -def _Configuration__setstate__(self: Type, state: Dict[str, Any]) -> None: - self.__dict__.update(state) - # Recreate logger objects. - self.logger["package_logger"] = logging.getLogger( - "lightly.openapi_generated.swagger_client" - ) - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - - # Set logger_format and logger_file explicitly because they have setter decoraters - # defined on the Configuration class. These decorates have side effects and create - # self.__logger_format, self.logger_formatter, self.__logger_file, - # self.logger_file_handler, and self.logger_stream_handler under the hood. - # - # Note that the setter decorates are not called by the self.__dict__.update(state) - # at the beginning of the function. - # - # The attributes are set to the class mangled values stored in the state dict. - self.logger_format = state[ - "_Configuration__logger_format" - ] # set to self.__logger_format - self.logger_file = state["_Configuration__logger_file"] # set to self.__logger_file - - # Set debug explicitly because it has a setter decorator with side effects. - self.debug = state["_Configuration__debug"] diff --git a/lightly/api/serve.py b/lightly/api/serve.py deleted file mode 100644 index 58aeea192..000000000 --- a/lightly/api/serve.py +++ /dev/null @@ -1,77 +0,0 @@ -from http.server import HTTPServer, SimpleHTTPRequestHandler -from pathlib import Path -from typing import Sequence -from urllib import parse - - -def get_server( - paths: Sequence[Path], - host: str, - port: int, -): - """Returns an HTTP server that serves a local datasource. - - Args: - paths: - List of paths to serve. - host: - Host to serve the datasource on. - port: - Port to serve the datasource on. - - Examples: - >>> from lightly.api import serve - >>> from pathlib import Path - >>> serve( - >>> paths=[Path("/input_mount), Path("/lightly_mount)], - >>> host="localhost", - >>> port=3456, - >>> ) - - """ - - class _LocalDatasourceRequestHandler(SimpleHTTPRequestHandler): - def translate_path(self, path: str) -> str: - return _translate_path(path=path, directories=paths) - - def do_OPTIONS(self) -> None: - self.send_response(204) - self.send_header("Access-Control-Allow-Origin", "*") - self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - self.end_headers() - - def send_response_only(self, code, message=None): - super().send_response_only(code, message) - self.send_header( - "Cache-Control", "no-store, must-revalidate, no-cache, max-age=-1" - ) - self.send_header("Expires", "0") - - return HTTPServer((host, port), _LocalDatasourceRequestHandler) - - -def _translate_path(path: str, directories: Sequence[Path]) -> str: - """Translates a relative path to a file in the local datasource. - - Tries to resolve the relative path to a file in the first directory - and serves it if it exists. Otherwise, it tries to resolve the relative - path to a file in the second directory and serves it if it exists, etc. - - Args: - path: - Relative path to a file in the local datasource. - directories: - List of directories to search for the file. - - - Returns: - Absolute path to the file in the local datasource or an empty string - if the file doesn't exist. - - """ - path = parse.unquote(path) - stripped_path = path.lstrip("/") - for directory in directories: - if (directory / stripped_path).exists(): - return str(directory / stripped_path) - return "" # Not found. diff --git a/lightly/api/swagger_api_client.py b/lightly/api/swagger_api_client.py deleted file mode 100644 index 750843094..000000000 --- a/lightly/api/swagger_api_client.py +++ /dev/null @@ -1,64 +0,0 @@ -from typing import Any, Dict, Optional, Tuple, Union - -from lightly.api.swagger_rest_client import LightlySwaggerRESTClientObject -from lightly.openapi_generated.swagger_client.api_client import ApiClient, Configuration - -DEFAULT_API_TIMEOUT = 60 * 3 # seconds - - -class PatchApiClientMixin: - """Mixin that makes an ApiClient object picklable.""" - - def __getstate__(self) -> Dict[str, Any]: - state = self.__dict__.copy() - # Set _pool to None as ThreadPool is not picklable. It will be automatically - # recreated once the pool is accessed after unpickling. - state["_pool"] = None - # Urllib3 response is not picklable. We can safely remove this as it only - # serves as a cache. - if "last_response" in state: - del state["last_response"] - return state - - -class LightlySwaggerApiClient(PatchApiClientMixin, ApiClient): - """Subclass of ApiClient with patches to make the client picklable. - - Uses a LightlySwaggerRESTClientObject instead of RESTClientObject for additional - patches. See LightlySwaggerRESTClientObject for details. - - - Attributes: - configuration: - Configuration. - timeout: - Timeout in seconds. Is either a single total_timeout value or a - (connect_timeout, read_timeout) tuple. No timeout is applied if the - value is None. - See https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html?highlight=timeout#urllib3.util.Timeout - for details on the different values. - header_name: - A header to pass when making calls to the API. - header_value: - A header value to pass when making calls to the API. - cookie: - A cookie to include in the header when making calls to the API. - """ - - def __init__( - self, - configuration: Configuration, - timeout: Union[None, int, Tuple[int, int]] = DEFAULT_API_TIMEOUT, - header_name: Optional[str] = None, - header_value: Optional[str] = None, - cookie: Optional[str] = None, - ): - super().__init__( - configuration=configuration, - header_name=header_name, - header_value=header_value, - cookie=cookie, - ) - self.rest_client = LightlySwaggerRESTClientObject( - configuration=configuration, timeout=timeout - ) diff --git a/lightly/api/swagger_rest_client.py b/lightly/api/swagger_rest_client.py deleted file mode 100644 index 79c52cccf..000000000 --- a/lightly/api/swagger_rest_client.py +++ /dev/null @@ -1,157 +0,0 @@ -import json -from json import JSONDecodeError -from typing import Any, Dict, Optional, Tuple, Union - -from lightly.openapi_generated.swagger_client.api_client import Configuration -from lightly.openapi_generated.swagger_client.exceptions import ApiException -from lightly.openapi_generated.swagger_client.rest import RESTClientObject - - -class PrettyPrintApiException(ApiException): - def __init__(self, current_exception: ApiException): - super().__init__(current_exception.status, current_exception.reason) - self.body = current_exception.body - self.headers = current_exception.headers - - def __str__(self) -> str: - error_message = "\n" - error_message += "#" * 100 - error_message += "\n" - error_message += f"Error Code: {self.status}" - error_message += "\n" - error_message += f"Error Reason: {self.reason}" - error_message += "\n" - error_message += "\n" - try: - error_body_dict = json.loads(self.body) - except JSONDecodeError: - pass - else: - if "error" in error_body_dict: - error_message += f"Error Message: {error_body_dict['error']}" - - error_message += "\n" - - error_message += "#" * 100 - - # make the error message red - error_message = f"\033[91m{error_message}\033[0m" - - return error_message - - -class PatchRESTClientObjectMixin: - """Mixin that adds patches to a RESTClientObject. - - * Adds default timeout to all requests - * Encodes list query parameters properly - * Makes the client picklable - - Should only used in combination with RESTClientObject and must come before the - RESTClientObject in the inheritance order. So this is ok: - - >>> class MyRESTClientObject(PatchRESTClientObjectMixin, RESTClientObject): pass - - while this doesn't work: - - >>> class MyRESTClientObject(RESTClientObject, PatchRESTClientObjectMixin): pass - - A wrong inheritance order will result in the super() calls no calling the correct - parent classes. - """ - - def __init__( - self, - configuration: Configuration, - timeout: Union[None, int, Tuple[int, int]], - pools_size: int = 4, - maxsize: Optional[int] = None, - ): - # Save args as attributes to make the class picklable. - self.configuration = configuration - self.timeout = timeout - self.pools_size = pools_size - self.maxsize = maxsize - - # Initialize RESTClientObject class - super().__init__( - configuration=configuration, pools_size=pools_size, maxsize=maxsize - ) - - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - # Set default timeout. This is necessary because the openapi client does not - # respect timeouts configured by urllib3. Instead it expects a timeout to be - # passed with every request. See code here: - # https://github.com/lightly-ai/lightly/blob/ffbd32fe82f76b37c8ac497640355314474bfc3b/lightly/openapi_generated/swagger_client/rest.py#L141-L148 - if _request_timeout is None: - _request_timeout = self.timeout - - # Call RESTClientObject.request - try: - return super().request( - method=method, - url=url, - query_params=query_params, - headers=headers, - body=body, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - except ApiException as e: - raise PrettyPrintApiException(e) from None - - def __getstate__(self) -> Dict[str, Any]: - """__getstate__ method for pickling.""" - state = self.__dict__.copy() - # Delete pool_manager as it cannot be pickled. Note that it is not possible to - # unpickle and use a LightlySwaggerRESTClientObject without either instantiating - # the pool_manager manually again or calling the init method on the rest client. - del state["pool_manager"] - return state - - def __setstate__(self, state: Dict[str, Any]) -> None: - """__setstate__ method for pickling.""" - self.__dict__.update(state) - # Calling init to recreate the pool_manager attribute. - self.__init__( - configuration=state["configuration"], - timeout=state["timeout"], - pools_size=state["pools_size"], - maxsize=state["maxsize"], - ) - - -class LightlySwaggerRESTClientObject(PatchRESTClientObjectMixin, RESTClientObject): - """Subclass of RESTClientObject which contains additional patches for the request - method and making the client picklable. - - See PatchRESTClientObjectMixin for details. - - Attributes: - configuration: - Configuration. - timeout: - Timeout in seconds. Is either a single total_timeout value or a - (connect_timeout, read_timeout) tuple. No timeout is applied if the - value is None. - See https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html?highlight=timeout#urllib3.util.Timeout - for details on the different values. - pools_size: - Number of connection pools. Defaults to 4. - maxsize: - Maxsize is the number of requests to host that are allowed in parallel. - Defaults to None. - """ - - pass diff --git a/lightly/api/utils.py b/lightly/api/utils.py deleted file mode 100644 index fa64f0987..000000000 --- a/lightly/api/utils.py +++ /dev/null @@ -1,246 +0,0 @@ -""" Communication Utility """ - -# Copyright (c) 2020. Lightly AG and its affiliates. -# All Rights Reserved - -import io -import os -import random -import threading -import time -from enum import Enum -from typing import Iterator, List, Optional - -# the following two lines are needed because -# PIL misidentifies certain jpeg images as MPOs -from PIL import JpegImagePlugin - -JpegImagePlugin._getmp = lambda: None - -from lightly.openapi_generated.swagger_client.configuration import Configuration - -MAXIMUM_FILENAME_LENGTH = 255 -RETRY_MAX_BACKOFF = 32 -RETRY_MAX_RETRIES = 5 - - -def retry(func, *args, **kwargs): # type: ignore - """Repeats a function until it completes successfully or fails too often. - - Args: - func: - The function call to repeat. - args: - The arguments which are passed to the function. - kwargs: - Key-word arguments which are passed to the function. - - Returns: - What func returns. - - Exceptions: - RuntimeError when number of retries has been exceeded. - - """ - - # config - backoff = 1.0 + random.random() * 0.1 - max_backoff = RETRY_MAX_BACKOFF - max_retries = RETRY_MAX_RETRIES - - # try to make the request - current_retries = 0 - while True: - try: - # return on success - return func(*args, **kwargs) - except Exception as e: - # sleep on failure - time.sleep(backoff) - backoff = 2 * backoff if backoff < max_backoff else backoff - current_retries += 1 - - # max retries exceeded - if current_retries >= max_retries: - raise RuntimeError( - f"Maximum retries exceeded! Original exception: {type(e)}: {str(e)}" - ) from e - - -class Paginated(Iterator): - def __init__(self, fn, page_size, *args, **kwargs): - self.entries: List = [] - self.last_chunk_size = page_size - self.offset = 0 - self.fn = fn - self.page_size = page_size - self.args = args - self.kwargs = kwargs - - def __iter__(self): - return self - - def __next__(self): - if len(self.entries) == 0: - # stop iteration if the last chunk was smaller than the page size - if self.last_chunk_size < self.page_size: - raise StopIteration - chunk = retry( - self.fn, - page_offset=self.offset * self.page_size, - page_size=self.page_size, - *self.args, - **self.kwargs, - ) - if len(chunk) == 0: - raise StopIteration - self.offset += 1 - self.last_chunk_size = len(chunk) - # Handle the case where the chunk is a string. In this case we want - # to return the whole page as a single string instead of an interable - # of characters. - chunk = chunk if not isinstance(chunk, str) else [chunk] - self.entries.extend(chunk) - return self.entries.pop(0) - - -def paginate_endpoint(fn, page_size=5000, *args, **kwargs) -> Iterator: - """Paginates an API endpoint - - Args: - fn: - The endpoint which will be paginated until there is not any more data - page_size: - The size of the pages to pull - """ - return Paginated(fn, page_size, *args, **kwargs) - - -def getenv(key: str, default: str): - """Return the value of the environment variable key if it exists, - or default if it doesn’t. - - """ - try: - return os.getenvb(key.encode(), default.encode()).decode() - except Exception: - pass - try: - return os.getenv(key, default) - except Exception: - pass - return default - - -def PIL_to_bytes(img, ext: str = "png", quality: int = None): - """Return the PIL image as byte stream. Useful to send image via requests.""" - bytes_io = io.BytesIO() - if quality is not None: - img.save(bytes_io, format=ext, quality=quality) - else: - subsampling = -1 if ext.lower() in ["jpg", "jpeg"] else 0 - img.save(bytes_io, format=ext, quality=100, subsampling=subsampling) - bytes_io.seek(0) - return bytes_io - - -def check_filename(basename): - """Checks the length of the filename. - - Args: - basename: - Basename of the file. - - """ - return len(basename) <= MAXIMUM_FILENAME_LENGTH - - -def build_azure_signed_url_write_headers( - content_length: str, - x_ms_blob_type: str = "BlockBlob", - accept: str = "*/*", - accept_encoding: str = "*", -): - """Builds the headers required for a SAS PUT to Azure blob storage. - - Args: - content_length: - Length of the content in bytes as string. - x_ms_blob_type: - Blob type (one of BlockBlob, PageBlob, AppendBlob) - accept: - Indicates which content types the client is able to understand. - accept_encoding: - Indicates the content encoding that the client can understand. - - Returns: - Formatted header which should be passed to the PUT request. - - """ - headers = { - "x-ms-blob-type": x_ms_blob_type, - "Accept": accept, - "Content-Length": content_length, - "x-ms-original-content-length": content_length, - "Accept-Encoding": accept_encoding, - } - return headers - - -class DatasourceType(Enum): - S3 = "S3" - GCS = "GCS" - AZURE = "AZURE" - LOCAL = "LOCAL" - - -def get_signed_url_destination(signed_url: str = "") -> DatasourceType: - """ - Tries to figure out the of which cloud provider/datasource type a signed url comes from (S3, GCS, Azure) - Args: - signed_url: - The signed url of a "bucket" provider - Returns: - DatasourceType - """ - - assert isinstance(signed_url, str) - - if "storage.googleapis.com/" in signed_url: - return DatasourceType.GCS - if ".amazonaws.com/" in signed_url and ".s3." in signed_url: - return DatasourceType.S3 - if ".windows.net/" in signed_url: - return DatasourceType.AZURE - # default to local as it must be some special setup - return DatasourceType.LOCAL - - -def get_lightly_server_location_from_env() -> str: - return ( - getenv("LIGHTLY_SERVER_LOCATION", "https://api.lightly.ai").strip().rstrip("/") - ) - - -def get_api_client_configuration( - token: Optional[str] = None, - raise_if_no_token_specified: bool = True, -) -> Configuration: - host = get_lightly_server_location_from_env() - ssl_ca_cert = getenv("LIGHTLY_CA_CERTS", None) - proxy = getenv("ALL_PROXY", getenv("HTTPS_PROXY", getenv("HTTP_PROXY", None))) - - if token is None: - token = getenv("LIGHTLY_TOKEN", None) - if token is None and raise_if_no_token_specified: - raise ValueError( - "Either provide a 'token' argument or export a LIGHTLY_TOKEN environment variable" - ) - - configuration = Configuration() - configuration.api_key = {"ApiKeyAuth": token} - configuration.ssl_ca_cert = ssl_ca_cert - configuration.proxy = proxy - configuration.host = host - - return configuration diff --git a/lightly/cli/__init__.py b/lightly/cli/__init__.py index cef81ae06..4b1d18a6e 100644 --- a/lightly/cli/__init__.py +++ b/lightly/cli/__init__.py @@ -7,7 +7,6 @@ # All Rights Reserved from lightly.cli.crop_cli import crop_cli -from lightly.cli.download_cli import download_cli from lightly.cli.embed_cli import embed_cli from lightly.cli.lightly_cli import lightly_cli from lightly.cli.train_cli import train_cli diff --git a/lightly/cli/download_cli.py b/lightly/cli/download_cli.py deleted file mode 100644 index ca544f372..000000000 --- a/lightly/cli/download_cli.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -"""**Lightly Download:** Download images from the Lightly platform. - -This module contains the entrypoint for the **lightly-download** -command-line interface. -""" - -# Copyright (c) 2020. Lightly AG and its affiliates. -# All Rights Reserved - -import os - -import hydra - -import lightly.data as data -from lightly.api.api_workflow_client import ApiWorkflowClient -from lightly.cli._helpers import cpu_count, fix_hydra_arguments, fix_input_path -from lightly.openapi_generated.swagger_client.models import Creator -from lightly.utils.hipify import bcolors, print_as_warning - - -def _download_cli(cfg, is_cli_call=True): - tag_name = str(cfg["tag_name"]) - dataset_id = str(cfg["dataset_id"]) - token = str(cfg["token"]) - - if not tag_name or not token or not dataset_id: - print_as_warning( - "Please specify all of the parameters tag_name, token and dataset_id" - ) - print_as_warning("For help, try: lightly-download --help") - return - - # set the number of workers if unset - if cfg["loader"]["num_workers"] < 0: - # set the number of workers to the number of CPUs available, - # but minimum of 8 - num_workers = max(8, cpu_count()) - num_workers = min(32, num_workers) - cfg["loader"]["num_workers"] = num_workers - - api_workflow_client = ApiWorkflowClient( - token=token, dataset_id=dataset_id, creator=Creator.USER_PIP_LIGHTLY_MAGIC - ) - - # get tag id - tag_data = api_workflow_client.get_tag_by_name(tag_name) - filenames_tag = api_workflow_client.get_filenames_in_tag( - tag_data, - exclude_parent_tag=cfg["exclude_parent_tag"], - ) - - # store sample names in a .txt file - filename = tag_name + ".txt" - with open(filename, "w") as f: - for item in filenames_tag: - f.write("%s\n" % item) - - filepath = os.path.join(os.getcwd(), filename) - msg = f'The list of samples in tag {cfg["tag_name"]} is stored at: {bcolors.OKBLUE}{filepath}{bcolors.ENDC}' - print(msg, flush=True) - - if not cfg["input_dir"] and cfg["output_dir"]: - # download full images from api - output_dir = fix_input_path(cfg["output_dir"]) - api_workflow_client.download_dataset( - output_dir, tag_name=tag_name, max_workers=cfg["loader"]["num_workers"] - ) - - elif cfg["input_dir"] and cfg["output_dir"]: - input_dir = fix_input_path(cfg["input_dir"]) - output_dir = fix_input_path(cfg["output_dir"]) - print( - f"Copying files from {input_dir} to {bcolors.OKBLUE}{output_dir}{bcolors.ENDC}." - ) - - # create a dataset from the input directory - dataset = data.LightlyDataset(input_dir=input_dir) - - # dump the dataset in the output directory - dataset.dump(output_dir, filenames_tag) - - -@hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) -def download_cli(cfg): - """Download images from the Lightly platform. - - Args: - cfg: - The default configs are loaded from the config file. - To overwrite them please see the section on the config file - (.config.config.yaml). - - Command-Line Args: - tag_name: - Download all images from the requested tag. Use initial-tag - to get all images from the dataset. - token: - User access token to the Lightly platform. If dataset_id - and token are specified, the images and embeddings are - uploaded to the platform. - dataset_id: - Identifier of the dataset on the Lightly platform. If - dataset_id and token are specified, the images and - embeddings are uploaded to the platform. - input_dir: - If input_dir and output_dir are specified, lightly will copy - all images belonging to the tag from the input_dir to the - output_dir. - output_dir: - If input_dir and output_dir are specified, lightly will copy - all images belonging to the tag from the input_dir to the - output_dir. - - Examples: - >>> # download list of all files in the dataset from the Lightly platform - >>> lightly-download token='123' dataset_id='XYZ' - >>> - >>> # download list of all files in tag 'my-tag' from the Lightly platform - >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' - >>> - >>> # download all images in tag 'my-tag' from the Lightly platform - >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' output_dir='my_data/' - >>> - >>> # copy all files in 'my-tag' to a new directory - >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' input_dir='data/' output_dir='my_data/' - - - """ - _download_cli(cfg) - - -def entry(): - download_cli() diff --git a/lightly/cli/serve_cli.py b/lightly/cli/serve_cli.py deleted file mode 100644 index 887045e86..000000000 --- a/lightly/cli/serve_cli.py +++ /dev/null @@ -1,56 +0,0 @@ -import sys -from pathlib import Path - -import hydra - -from lightly.api import serve -from lightly.cli._helpers import fix_hydra_arguments -from lightly.utils.hipify import bcolors - - -@hydra.main(**fix_hydra_arguments(config_path="config", config_name="lightly-serve")) -def lightly_serve(cfg): - """Use lightly-serve to serve your data for interactive exploration. - - Command-Line Args: - input_mount: - Path to the input directory. - lightly_mount: - Path to the Lightly directory. - host: - Hostname for serving the data (defaults to localhost). - port: - Port for serving the data (defaults to 3456). - - Examples: - >>> lightly-serve input_mount=data/ lightly_mount=lightly/ port=3456 - - - """ - if not cfg.input_mount: - print("Please provide a valid input mount. Use --help for more information.") - sys.exit(1) - - if not cfg.lightly_mount: - print("Please provide a valid Lightly mount. Use --help for more information.") - sys.exit(1) - - httpd = serve.get_server( - paths=[Path(cfg.input_mount), Path(cfg.lightly_mount)], - host=cfg.host, - port=cfg.port, - ) - print( - f"Starting server, listening at '{bcolors.OKBLUE}{httpd.server_name}:{httpd.server_port}{bcolors.ENDC}'" - ) - print( - f"Serving files in '{bcolors.OKBLUE}{cfg.input_mount}{bcolors.ENDC}' and '{bcolors.OKBLUE}{cfg.lightly_mount}{bcolors.ENDC}'" - ) - print( - f"Please follow our docs if you are facing any issues: https://docs.lightly.ai/docs/local-storage#optional-after-run-view-local-data-in-lightly-platform" - ) - httpd.serve_forever() - - -def entry() -> None: - lightly_serve() diff --git a/lightly/openapi_generated/__init__.py b/lightly/openapi_generated/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/lightly/openapi_generated/swagger_client/__init__.py b/lightly/openapi_generated/swagger_client/__init__.py deleted file mode 100644 index 708f32826..000000000 --- a/lightly/openapi_generated/swagger_client/__init__.py +++ /dev/null @@ -1,301 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -__version__ = "1.0.0" - -# import apis into sdk package -from lightly.openapi_generated.swagger_client.api.collaboration_api import CollaborationApi -from lightly.openapi_generated.swagger_client.api.datasets_api import DatasetsApi -from lightly.openapi_generated.swagger_client.api.datasources_api import DatasourcesApi -from lightly.openapi_generated.swagger_client.api.docker_api import DockerApi -from lightly.openapi_generated.swagger_client.api.embeddings_api import EmbeddingsApi -from lightly.openapi_generated.swagger_client.api.embeddings2d_api import Embeddings2dApi -from lightly.openapi_generated.swagger_client.api.jobs_api import JobsApi -from lightly.openapi_generated.swagger_client.api.mappings_api import MappingsApi -from lightly.openapi_generated.swagger_client.api.meta_data_configurations_api import MetaDataConfigurationsApi -from lightly.openapi_generated.swagger_client.api.predictions_api import PredictionsApi -from lightly.openapi_generated.swagger_client.api.quota_api import QuotaApi -from lightly.openapi_generated.swagger_client.api.samples_api import SamplesApi -from lightly.openapi_generated.swagger_client.api.samplings_api import SamplingsApi -from lightly.openapi_generated.swagger_client.api.scores_api import ScoresApi -from lightly.openapi_generated.swagger_client.api.tags_api import TagsApi -from lightly.openapi_generated.swagger_client.api.teams_api import TeamsApi -from lightly.openapi_generated.swagger_client.api.versioning_api import VersioningApi - -# import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.configuration import Configuration -from lightly.openapi_generated.swagger_client.exceptions import OpenApiException -from lightly.openapi_generated.swagger_client.exceptions import ApiTypeError -from lightly.openapi_generated.swagger_client.exceptions import ApiValueError -from lightly.openapi_generated.swagger_client.exceptions import ApiKeyError -from lightly.openapi_generated.swagger_client.exceptions import ApiAttributeError -from lightly.openapi_generated.swagger_client.exceptions import ApiException - -# import models into sdk package -from lightly.openapi_generated.swagger_client.models.active_learning_score_create_request import ActiveLearningScoreCreateRequest -from lightly.openapi_generated.swagger_client.models.active_learning_score_data import ActiveLearningScoreData -from lightly.openapi_generated.swagger_client.models.active_learning_score_types_v2_data import ActiveLearningScoreTypesV2Data -from lightly.openapi_generated.swagger_client.models.active_learning_score_v2_data import ActiveLearningScoreV2Data -from lightly.openapi_generated.swagger_client.models.api_error_code import ApiErrorCode -from lightly.openapi_generated.swagger_client.models.api_error_response import ApiErrorResponse -from lightly.openapi_generated.swagger_client.models.async_task_data import AsyncTaskData -from lightly.openapi_generated.swagger_client.models.configuration_data import ConfigurationData -from lightly.openapi_generated.swagger_client.models.configuration_entry import ConfigurationEntry -from lightly.openapi_generated.swagger_client.models.configuration_set_request import ConfigurationSetRequest -from lightly.openapi_generated.swagger_client.models.configuration_value_data_type import ConfigurationValueDataType -from lightly.openapi_generated.swagger_client.models.create_cf_bucket_activity_request import CreateCFBucketActivityRequest -from lightly.openapi_generated.swagger_client.models.create_docker_worker_registry_entry_request import CreateDockerWorkerRegistryEntryRequest -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.create_sample_with_write_urls_response import CreateSampleWithWriteUrlsResponse -from lightly.openapi_generated.swagger_client.models.create_team_membership_request import CreateTeamMembershipRequest -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.crop_data import CropData -from lightly.openapi_generated.swagger_client.models.dataset_create_request import DatasetCreateRequest -from lightly.openapi_generated.swagger_client.models.dataset_creator import DatasetCreator -from lightly.openapi_generated.swagger_client.models.dataset_data import DatasetData -from lightly.openapi_generated.swagger_client.models.dataset_data_enriched import DatasetDataEnriched -from lightly.openapi_generated.swagger_client.models.dataset_embedding_data import DatasetEmbeddingData -from lightly.openapi_generated.swagger_client.models.dataset_type import DatasetType -from lightly.openapi_generated.swagger_client.models.dataset_update_request import DatasetUpdateRequest -from lightly.openapi_generated.swagger_client.models.datasource_config import DatasourceConfig -from lightly.openapi_generated.swagger_client.models.datasource_config_azure import DatasourceConfigAzure -from lightly.openapi_generated.swagger_client.models.datasource_config_azure_all_of import DatasourceConfigAzureAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase -from lightly.openapi_generated.swagger_client.models.datasource_config_base_full_path import DatasourceConfigBaseFullPath -from lightly.openapi_generated.swagger_client.models.datasource_config_gcs import DatasourceConfigGCS -from lightly.openapi_generated.swagger_client.models.datasource_config_gcs_all_of import DatasourceConfigGCSAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_lightly import DatasourceConfigLIGHTLY -from lightly.openapi_generated.swagger_client.models.datasource_config_local import DatasourceConfigLOCAL -from lightly.openapi_generated.swagger_client.models.datasource_config_local_all_of import DatasourceConfigLOCALAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_obs import DatasourceConfigOBS -from lightly.openapi_generated.swagger_client.models.datasource_config_obs_all_of import DatasourceConfigOBSAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_s3 import DatasourceConfigS3 -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_all_of import DatasourceConfigS3AllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_delegated_access import DatasourceConfigS3DelegatedAccess -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_delegated_access_all_of import DatasourceConfigS3DelegatedAccessAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data import DatasourceConfigVerifyData -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data_errors import DatasourceConfigVerifyDataErrors -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_request import DatasourceProcessedUntilTimestampRequest -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_response import DatasourceProcessedUntilTimestampResponse -from lightly.openapi_generated.swagger_client.models.datasource_purpose import DatasourcePurpose -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data import DatasourceRawSamplesData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data_row import DatasourceRawSamplesDataRow -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data import DatasourceRawSamplesMetadataData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data_row import DatasourceRawSamplesMetadataDataRow -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data import DatasourceRawSamplesPredictionsData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data_row import DatasourceRawSamplesPredictionsDataRow -from lightly.openapi_generated.swagger_client.models.delegated_access_external_ids_inner import DelegatedAccessExternalIdsInner -from lightly.openapi_generated.swagger_client.models.dimensionality_reduction_method import DimensionalityReductionMethod -from lightly.openapi_generated.swagger_client.models.docker_license_information import DockerLicenseInformation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_create_request import DockerRunArtifactCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_created_data import DockerRunArtifactCreatedData -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_data import DockerRunArtifactData -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_storage_location import DockerRunArtifactStorageLocation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_type import DockerRunArtifactType -from lightly.openapi_generated.swagger_client.models.docker_run_create_request import DockerRunCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_data import DockerRunData -from lightly.openapi_generated.swagger_client.models.docker_run_log_create_entry_data import DockerRunLogCreateEntryData -from lightly.openapi_generated.swagger_client.models.docker_run_log_data import DockerRunLogData -from lightly.openapi_generated.swagger_client.models.docker_run_log_docker_load import DockerRunLogDockerLoad -from lightly.openapi_generated.swagger_client.models.docker_run_log_entry_data import DockerRunLogEntryData -from lightly.openapi_generated.swagger_client.models.docker_run_log_entry_data_base import DockerRunLogEntryDataBase -from lightly.openapi_generated.swagger_client.models.docker_run_log_level import DockerRunLogLevel -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_create_request import DockerRunScheduledCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_data import DockerRunScheduledData -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_priority import DockerRunScheduledPriority -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_state import DockerRunScheduledState -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_update_request import DockerRunScheduledUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState -from lightly.openapi_generated.swagger_client.models.docker_run_update_request import DockerRunUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_task_description import DockerTaskDescription -from lightly.openapi_generated.swagger_client.models.docker_user_stats import DockerUserStats -from lightly.openapi_generated.swagger_client.models.docker_worker_config import DockerWorkerConfig -from lightly.openapi_generated.swagger_client.models.docker_worker_config_create_request import DockerWorkerConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v2_create_request import DockerWorkerConfigOmniV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v2_create_request_all_of import DockerWorkerConfigOmniV2CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v3_create_request import DockerWorkerConfigOmniV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v3_create_request_all_of import DockerWorkerConfigOmniV3CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v4_create_request import DockerWorkerConfigOmniV4CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v4_create_request_all_of import DockerWorkerConfigOmniV4CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request import DockerWorkerConfigOmniVXCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request_base import DockerWorkerConfigOmniVXCreateRequestBase -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data import DockerWorkerConfigV0Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data_all_of import DockerWorkerConfigV0DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_create_request import DockerWorkerConfigV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data import DockerWorkerConfigV2Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data_all_of import DockerWorkerConfigV2DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker import DockerWorkerConfigV2Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_datasource import DockerWorkerConfigV2DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_object_level import DockerWorkerConfigV2DockerObjectLevel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_stopping_condition import DockerWorkerConfigV2DockerStoppingCondition -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly import DockerWorkerConfigV2Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_collate import DockerWorkerConfigV2LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_model import DockerWorkerConfigV2LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_trainer import DockerWorkerConfigV2LightlyTrainer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_create_request import DockerWorkerConfigV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data import DockerWorkerConfigV3Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data_all_of import DockerWorkerConfigV3DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_datasource_input_expiration import DockerWorkerConfigV3DatasourceInputExpiration -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker import DockerWorkerConfigV3Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_corruptness_check import DockerWorkerConfigV3DockerCorruptnessCheck -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_datasource import DockerWorkerConfigV3DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_training import DockerWorkerConfigV3DockerTraining -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly import DockerWorkerConfigV3Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_checkpoint_callback import DockerWorkerConfigV3LightlyCheckpointCallback -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_collate import DockerWorkerConfigV3LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_criterion import DockerWorkerConfigV3LightlyCriterion -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_loader import DockerWorkerConfigV3LightlyLoader -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_model import DockerWorkerConfigV3LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_optimizer import DockerWorkerConfigV3LightlyOptimizer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_trainer import DockerWorkerConfigV3LightlyTrainer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_data import DockerWorkerConfigV4Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_data_all_of import DockerWorkerConfigV4DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_docker import DockerWorkerConfigV4Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data import DockerWorkerConfigVXData -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase -from lightly.openapi_generated.swagger_client.models.docker_worker_registry_entry_data import DockerWorkerRegistryEntryData -from lightly.openapi_generated.swagger_client.models.docker_worker_state import DockerWorkerState -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.embedding2d_create_request import Embedding2dCreateRequest -from lightly.openapi_generated.swagger_client.models.embedding2d_data import Embedding2dData -from lightly.openapi_generated.swagger_client.models.embedding_data import EmbeddingData -from lightly.openapi_generated.swagger_client.models.expiry_handling_strategy_v3 import ExpiryHandlingStrategyV3 -from lightly.openapi_generated.swagger_client.models.file_name_format import FileNameFormat -from lightly.openapi_generated.swagger_client.models.file_output_format import FileOutputFormat -from lightly.openapi_generated.swagger_client.models.filename_and_read_url import FilenameAndReadUrl -from lightly.openapi_generated.swagger_client.models.image_type import ImageType -from lightly.openapi_generated.swagger_client.models.initial_tag_create_request import InitialTagCreateRequest -from lightly.openapi_generated.swagger_client.models.job_result_type import JobResultType -from lightly.openapi_generated.swagger_client.models.job_state import JobState -from lightly.openapi_generated.swagger_client.models.job_status_data import JobStatusData -from lightly.openapi_generated.swagger_client.models.job_status_data_result import JobStatusDataResult -from lightly.openapi_generated.swagger_client.models.job_status_meta import JobStatusMeta -from lightly.openapi_generated.swagger_client.models.job_status_upload_method import JobStatusUploadMethod -from lightly.openapi_generated.swagger_client.models.jobs_data import JobsData -from lightly.openapi_generated.swagger_client.models.label_box_data_row import LabelBoxDataRow -from lightly.openapi_generated.swagger_client.models.label_box_v4_data_row import LabelBoxV4DataRow -from lightly.openapi_generated.swagger_client.models.label_studio_task import LabelStudioTask -from lightly.openapi_generated.swagger_client.models.label_studio_task_data import LabelStudioTaskData -from lightly.openapi_generated.swagger_client.models.lightly_docker_selection_method import LightlyDockerSelectionMethod -from lightly.openapi_generated.swagger_client.models.lightly_model_v2 import LightlyModelV2 -from lightly.openapi_generated.swagger_client.models.lightly_model_v3 import LightlyModelV3 -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v2 import LightlyTrainerPrecisionV2 -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v3 import LightlyTrainerPrecisionV3 -from lightly.openapi_generated.swagger_client.models.prediction_singleton import PredictionSingleton -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase -from lightly.openapi_generated.swagger_client.models.prediction_singleton_classification import PredictionSingletonClassification -from lightly.openapi_generated.swagger_client.models.prediction_singleton_classification_all_of import PredictionSingletonClassificationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_instance_segmentation import PredictionSingletonInstanceSegmentation -from lightly.openapi_generated.swagger_client.models.prediction_singleton_instance_segmentation_all_of import PredictionSingletonInstanceSegmentationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_keypoint_detection import PredictionSingletonKeypointDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_keypoint_detection_all_of import PredictionSingletonKeypointDetectionAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_object_detection import PredictionSingletonObjectDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_object_detection_all_of import PredictionSingletonObjectDetectionAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_semantic_segmentation import PredictionSingletonSemanticSegmentation -from lightly.openapi_generated.swagger_client.models.prediction_singleton_semantic_segmentation_all_of import PredictionSingletonSemanticSegmentationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema import PredictionTaskSchema -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_base import PredictionTaskSchemaBase -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category import PredictionTaskSchemaCategory -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints import PredictionTaskSchemaCategoryKeypoints -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints_all_of import PredictionTaskSchemaCategoryKeypointsAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_keypoint import PredictionTaskSchemaKeypoint -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_keypoint_all_of import PredictionTaskSchemaKeypointAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_simple import PredictionTaskSchemaSimple -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_simple_all_of import PredictionTaskSchemaSimpleAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schemas import PredictionTaskSchemas -from lightly.openapi_generated.swagger_client.models.questionnaire_data import QuestionnaireData -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region -from lightly.openapi_generated.swagger_client.models.sama_task import SamaTask -from lightly.openapi_generated.swagger_client.models.sama_task_data import SamaTaskData -from lightly.openapi_generated.swagger_client.models.sample_create_request import SampleCreateRequest -from lightly.openapi_generated.swagger_client.models.sample_data import SampleData -from lightly.openapi_generated.swagger_client.models.sample_data_modes import SampleDataModes -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData -from lightly.openapi_generated.swagger_client.models.sample_partial_mode import SamplePartialMode -from lightly.openapi_generated.swagger_client.models.sample_sort_by import SampleSortBy -from lightly.openapi_generated.swagger_client.models.sample_type import SampleType -from lightly.openapi_generated.swagger_client.models.sample_update_request import SampleUpdateRequest -from lightly.openapi_generated.swagger_client.models.sample_write_urls import SampleWriteUrls -from lightly.openapi_generated.swagger_client.models.sampling_config import SamplingConfig -from lightly.openapi_generated.swagger_client.models.sampling_config_stopping_condition import SamplingConfigStoppingCondition -from lightly.openapi_generated.swagger_client.models.sampling_create_request import SamplingCreateRequest -from lightly.openapi_generated.swagger_client.models.sampling_method import SamplingMethod -from lightly.openapi_generated.swagger_client.models.sector import Sector -from lightly.openapi_generated.swagger_client.models.selection_config import SelectionConfig -from lightly.openapi_generated.swagger_client.models.selection_config_all_of import SelectionConfigAllOf -from lightly.openapi_generated.swagger_client.models.selection_config_base import SelectionConfigBase -from lightly.openapi_generated.swagger_client.models.selection_config_entry import SelectionConfigEntry -from lightly.openapi_generated.swagger_client.models.selection_config_entry_input import SelectionConfigEntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_entry_strategy import SelectionConfigEntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_config_v3 import SelectionConfigV3 -from lightly.openapi_generated.swagger_client.models.selection_config_v3_all_of import SelectionConfigV3AllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry import SelectionConfigV3Entry -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_input import SelectionConfigV3EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy import SelectionConfigV3EntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of import SelectionConfigV3EntryStrategyAllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of_target_range import SelectionConfigV3EntryStrategyAllOfTargetRange -from lightly.openapi_generated.swagger_client.models.selection_config_v4 import SelectionConfigV4 -from lightly.openapi_generated.swagger_client.models.selection_config_v4_all_of import SelectionConfigV4AllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry import SelectionConfigV4Entry -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_input import SelectionConfigV4EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_strategy import SelectionConfigV4EntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_input_predictions_name import SelectionInputPredictionsName -from lightly.openapi_generated.swagger_client.models.selection_input_type import SelectionInputType -from lightly.openapi_generated.swagger_client.models.selection_strategy_threshold_operation import SelectionStrategyThresholdOperation -from lightly.openapi_generated.swagger_client.models.selection_strategy_type import SelectionStrategyType -from lightly.openapi_generated.swagger_client.models.selection_strategy_type_v3 import SelectionStrategyTypeV3 -from lightly.openapi_generated.swagger_client.models.service_account_basic_data import ServiceAccountBasicData -from lightly.openapi_generated.swagger_client.models.set_embeddings_is_processed_flag_by_id_body_request import SetEmbeddingsIsProcessedFlagByIdBodyRequest -from lightly.openapi_generated.swagger_client.models.shared_access_config_create_request import SharedAccessConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.shared_access_config_data import SharedAccessConfigData -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType -from lightly.openapi_generated.swagger_client.models.tag_active_learning_scores_data import TagActiveLearningScoresData -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_operation import TagArithmeticsOperation -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_request import TagArithmeticsRequest -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_response import TagArithmeticsResponse -from lightly.openapi_generated.swagger_client.models.tag_bit_mask_response import TagBitMaskResponse -from lightly.openapi_generated.swagger_client.models.tag_change_data import TagChangeData -from lightly.openapi_generated.swagger_client.models.tag_change_data_arithmetics import TagChangeDataArithmetics -from lightly.openapi_generated.swagger_client.models.tag_change_data_initial import TagChangeDataInitial -from lightly.openapi_generated.swagger_client.models.tag_change_data_metadata import TagChangeDataMetadata -from lightly.openapi_generated.swagger_client.models.tag_change_data_operation_method import TagChangeDataOperationMethod -from lightly.openapi_generated.swagger_client.models.tag_change_data_rename import TagChangeDataRename -from lightly.openapi_generated.swagger_client.models.tag_change_data_sampler import TagChangeDataSampler -from lightly.openapi_generated.swagger_client.models.tag_change_data_samples import TagChangeDataSamples -from lightly.openapi_generated.swagger_client.models.tag_change_data_scatterplot import TagChangeDataScatterplot -from lightly.openapi_generated.swagger_client.models.tag_change_data_upsize import TagChangeDataUpsize -from lightly.openapi_generated.swagger_client.models.tag_change_entry import TagChangeEntry -from lightly.openapi_generated.swagger_client.models.tag_create_request import TagCreateRequest -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator -from lightly.openapi_generated.swagger_client.models.tag_data import TagData -from lightly.openapi_generated.swagger_client.models.tag_update_request import TagUpdateRequest -from lightly.openapi_generated.swagger_client.models.tag_upsize_request import TagUpsizeRequest -from lightly.openapi_generated.swagger_client.models.task_type import TaskType -from lightly.openapi_generated.swagger_client.models.team_basic_data import TeamBasicData -from lightly.openapi_generated.swagger_client.models.team_data import TeamData -from lightly.openapi_generated.swagger_client.models.team_role import TeamRole -from lightly.openapi_generated.swagger_client.models.trigger2d_embedding_job_request import Trigger2dEmbeddingJobRequest -from lightly.openapi_generated.swagger_client.models.update_docker_worker_registry_entry_request import UpdateDockerWorkerRegistryEntryRequest -from lightly.openapi_generated.swagger_client.models.update_team_membership_request import UpdateTeamMembershipRequest -from lightly.openapi_generated.swagger_client.models.user_type import UserType -from lightly.openapi_generated.swagger_client.models.video_frame_data import VideoFrameData -from lightly.openapi_generated.swagger_client.models.write_csv_url_data import WriteCSVUrlData diff --git a/lightly/openapi_generated/swagger_client/api/__init__.py b/lightly/openapi_generated/swagger_client/api/__init__.py deleted file mode 100644 index 3780d6891..000000000 --- a/lightly/openapi_generated/swagger_client/api/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# flake8: noqa - -# import apis into api package -from lightly.openapi_generated.swagger_client.api.collaboration_api import CollaborationApi -from lightly.openapi_generated.swagger_client.api.datasets_api import DatasetsApi -from lightly.openapi_generated.swagger_client.api.datasources_api import DatasourcesApi -from lightly.openapi_generated.swagger_client.api.docker_api import DockerApi -from lightly.openapi_generated.swagger_client.api.embeddings_api import EmbeddingsApi -from lightly.openapi_generated.swagger_client.api.embeddings2d_api import Embeddings2dApi -from lightly.openapi_generated.swagger_client.api.jobs_api import JobsApi -from lightly.openapi_generated.swagger_client.api.mappings_api import MappingsApi -from lightly.openapi_generated.swagger_client.api.meta_data_configurations_api import MetaDataConfigurationsApi -from lightly.openapi_generated.swagger_client.api.predictions_api import PredictionsApi -from lightly.openapi_generated.swagger_client.api.quota_api import QuotaApi -from lightly.openapi_generated.swagger_client.api.samples_api import SamplesApi -from lightly.openapi_generated.swagger_client.api.samplings_api import SamplingsApi -from lightly.openapi_generated.swagger_client.api.scores_api import ScoresApi -from lightly.openapi_generated.swagger_client.api.tags_api import TagsApi -from lightly.openapi_generated.swagger_client.api.teams_api import TeamsApi -from lightly.openapi_generated.swagger_client.api.versioning_api import VersioningApi - diff --git a/lightly/openapi_generated/swagger_client/api/collaboration_api.py b/lightly/openapi_generated/swagger_client/api/collaboration_api.py deleted file mode 100644 index 2cc360133..000000000 --- a/lightly/openapi_generated/swagger_client/api/collaboration_api.py +++ /dev/null @@ -1,495 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, constr, validator - -from typing import List - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.shared_access_config_create_request import SharedAccessConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.shared_access_config_data import SharedAccessConfigData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class CollaborationApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_or_update_shared_access_config_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], shared_access_config_create_request : SharedAccessConfigCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_or_update_shared_access_config_by_dataset_id # noqa: E501 - - Create or update a shared access config. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_shared_access_config_by_dataset_id(dataset_id, shared_access_config_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param shared_access_config_create_request: (required) - :type shared_access_config_create_request: SharedAccessConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_or_update_shared_access_config_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_or_update_shared_access_config_by_dataset_id_with_http_info(dataset_id, shared_access_config_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_or_update_shared_access_config_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], shared_access_config_create_request : SharedAccessConfigCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_or_update_shared_access_config_by_dataset_id # noqa: E501 - - Create or update a shared access config. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_shared_access_config_by_dataset_id_with_http_info(dataset_id, shared_access_config_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param shared_access_config_create_request: (required) - :type shared_access_config_create_request: SharedAccessConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'shared_access_config_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_or_update_shared_access_config_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['shared_access_config_create_request'] is not None: - _body_params = _params['shared_access_config_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/collaboration/access', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def delete_shared_access_config_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], access_config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the shared access config.")], **kwargs) -> None: # noqa: E501 - """delete_shared_access_config_by_id # noqa: E501 - - Delete shared access config by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_shared_access_config_by_id(dataset_id, access_config_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param access_config_id: ObjectId of the shared access config. (required) - :type access_config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_shared_access_config_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_shared_access_config_by_id_with_http_info(dataset_id, access_config_id, **kwargs) # noqa: E501 - - @validate_arguments - def delete_shared_access_config_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], access_config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the shared access config.")], **kwargs) -> ApiResponse: # noqa: E501 - """delete_shared_access_config_by_id # noqa: E501 - - Delete shared access config by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_shared_access_config_by_id_with_http_info(dataset_id, access_config_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param access_config_id: ObjectId of the shared access config. (required) - :type access_config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'access_config_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_shared_access_config_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['access_config_id']: - _path_params['accessConfigId'] = _params['access_config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/collaboration/access/{accessConfigId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_shared_access_configs_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[SharedAccessConfigData]: # noqa: E501 - """get_shared_access_configs_by_dataset_id # noqa: E501 - - Get shared access configs by datasetId. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_shared_access_configs_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[SharedAccessConfigData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_shared_access_configs_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_shared_access_configs_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_shared_access_configs_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_shared_access_configs_by_dataset_id # noqa: E501 - - Get shared access configs by datasetId. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_shared_access_configs_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[SharedAccessConfigData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_shared_access_configs_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[SharedAccessConfigData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/collaboration/access', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/datasets_api.py b/lightly/openapi_generated/swagger_client/api/datasets_api.py deleted file mode 100644 index 1a89cca96..000000000 --- a/lightly/openapi_generated/swagger_client/api/datasets_api.py +++ /dev/null @@ -1,1896 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictInt, StrictStr, conint, conlist, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.dataset_create_request import DatasetCreateRequest -from lightly.openapi_generated.swagger_client.models.dataset_data import DatasetData -from lightly.openapi_generated.swagger_client.models.dataset_data_enriched import DatasetDataEnriched -from lightly.openapi_generated.swagger_client.models.dataset_update_request import DatasetUpdateRequest -from lightly.openapi_generated.swagger_client.models.job_status_meta import JobStatusMeta - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class DatasetsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_dataset(self, dataset_create_request : DatasetCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_dataset # noqa: E501 - - Creates a new dataset for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_dataset(dataset_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_create_request: (required) - :type dataset_create_request: DatasetCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_dataset_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_dataset_with_http_info(dataset_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_dataset_with_http_info(self, dataset_create_request : DatasetCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_dataset # noqa: E501 - - Creates a new dataset for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_dataset_with_http_info(dataset_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_create_request: (required) - :type dataset_create_request: DatasetCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_dataset" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['dataset_create_request'] is not None: - _body_params = _params['dataset_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def delete_dataset_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], force : Optional[StrictBool] = None, **kwargs) -> None: # noqa: E501 - """delete_dataset_by_id # noqa: E501 - - Delete a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_dataset_by_id(dataset_id, force, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param force: - :type force: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_dataset_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_dataset_by_id_with_http_info(dataset_id, force, **kwargs) # noqa: E501 - - @validate_arguments - def delete_dataset_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], force : Optional[StrictBool] = None, **kwargs) -> ApiResponse: # noqa: E501 - """delete_dataset_by_id # noqa: E501 - - Delete a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_dataset_by_id_with_http_info(dataset_id, force, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param force: - :type force: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'force' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_dataset_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('force') is not None: # noqa: E501 - _query_params.append(( - 'force', - _params['force'].value if hasattr(_params['force'], 'value') else _params['force'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_children_of_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[DatasetData]: # noqa: E501 - """get_children_of_dataset_id # noqa: E501 - - Get all datasets which are the children of a specific dataset (e.g crop datasets) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_children_of_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_children_of_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_children_of_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_children_of_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_children_of_dataset_id # noqa: E501 - - Get all datasets which are the children of a specific dataset (e.g crop datasets) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_children_of_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_children_of_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/children', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_dataset_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> DatasetData: # noqa: E501 - """get_dataset_by_id # noqa: E501 - - Get a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_dataset_by_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasetData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_dataset_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_dataset_by_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_dataset_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_dataset_by_id # noqa: E501 - - Get a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_dataset_by_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasetData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_dataset_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasetData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasets(self, shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[DatasetData]: # noqa: E501 - """get_datasets # noqa: E501 - - Get all datasets for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets(shared, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasets_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasets_with_http_info(shared, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasets_with_http_info(self, shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_datasets # noqa: E501 - - Get all datasets for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_with_http_info(shared, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'shared', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasets" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('shared') is not None: # noqa: E501 - _query_params.append(( - 'shared', - _params['shared'].value if hasattr(_params['shared'], 'value') else _params['shared'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasets_enriched(self, shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, limit : Annotated[Optional[StrictInt], Field(description="DEPRECATED, use pageSize instead. if set, only returns the newest up until limit")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[DatasetDataEnriched]: # noqa: E501 - """get_datasets_enriched # noqa: E501 - - Get all datasets for a user but enriched with additional information as nTags, nEmbeddings, samples # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched(shared, limit, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param limit: DEPRECATED, use pageSize instead. if set, only returns the newest up until limit - :type limit: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetDataEnriched] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasets_enriched_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasets_enriched_with_http_info(shared, limit, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasets_enriched_with_http_info(self, shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, limit : Annotated[Optional[StrictInt], Field(description="DEPRECATED, use pageSize instead. if set, only returns the newest up until limit")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_datasets_enriched # noqa: E501 - - Get all datasets for a user but enriched with additional information as nTags, nEmbeddings, samples # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched_with_http_info(shared, limit, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param limit: DEPRECATED, use pageSize instead. if set, only returns the newest up until limit - :type limit: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetDataEnriched], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'shared', - 'limit', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasets_enriched" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('shared') is not None: # noqa: E501 - _query_params.append(( - 'shared', - _params['shared'].value if hasattr(_params['shared'], 'value') else _params['shared'] - )) - - if _params.get('limit') is not None: # noqa: E501 - _query_params.append(( - 'limit', - _params['limit'].value if hasattr(_params['limit'], 'value') else _params['limit'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetDataEnriched]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/enriched', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasets_enriched_query_by_ids(self, dataset_ids : conlist(StrictStr), **kwargs) -> List[DatasetDataEnriched]: # noqa: E501 - """get_datasets_enriched_query_by_ids # noqa: E501 - - Query for datasets enriched with additional information by their Ids. Includes team and shared datasets. Used for favorite resolving # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched_query_by_ids(dataset_ids, async_req=True) - >>> result = thread.get() - - :param dataset_ids: (required) - :type dataset_ids: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetDataEnriched] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasets_enriched_query_by_ids_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasets_enriched_query_by_ids_with_http_info(dataset_ids, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasets_enriched_query_by_ids_with_http_info(self, dataset_ids : conlist(StrictStr), **kwargs) -> ApiResponse: # noqa: E501 - """get_datasets_enriched_query_by_ids # noqa: E501 - - Query for datasets enriched with additional information by their Ids. Includes team and shared datasets. Used for favorite resolving # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched_query_by_ids_with_http_info(dataset_ids, async_req=True) - >>> result = thread.get() - - :param dataset_ids: (required) - :type dataset_ids: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetDataEnriched], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_ids' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasets_enriched_query_by_ids" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('dataset_ids') is not None: # noqa: E501 - _query_params.append(( - 'datasetIds', - _params['dataset_ids'].value if hasattr(_params['dataset_ids'], 'value') else _params['dataset_ids'] - )) - _collection_formats['datasetIds'] = 'multi' - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetDataEnriched]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/enriched/query/ids', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasets_enriched_query_by_name(self, dataset_name : constr(strict=True, min_length=1), shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, exact : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which match the name exactly (not just by prefix)")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[DatasetDataEnriched]: # noqa: E501 - """get_datasets_enriched_query_by_name # noqa: E501 - - Query for datasets enriched with additional information by their name prefix unless exact flag is set # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched_query_by_name(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_name: (required) - :type dataset_name: str - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param exact: if set, only returns the datasets which match the name exactly (not just by prefix) - :type exact: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetDataEnriched] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasets_enriched_query_by_name_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasets_enriched_query_by_name_with_http_info(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasets_enriched_query_by_name_with_http_info(self, dataset_name : constr(strict=True, min_length=1), shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, exact : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which match the name exactly (not just by prefix)")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_datasets_enriched_query_by_name # noqa: E501 - - Query for datasets enriched with additional information by their name prefix unless exact flag is set # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_enriched_query_by_name_with_http_info(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_name: (required) - :type dataset_name: str - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param exact: if set, only returns the datasets which match the name exactly (not just by prefix) - :type exact: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetDataEnriched], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_name', - 'shared', - 'exact', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasets_enriched_query_by_name" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_name']: - _path_params['datasetName'] = _params['dataset_name'] - - - # process the query parameters - _query_params = [] - if _params.get('shared') is not None: # noqa: E501 - _query_params.append(( - 'shared', - _params['shared'].value if hasattr(_params['shared'], 'value') else _params['shared'] - )) - - if _params.get('exact') is not None: # noqa: E501 - _query_params.append(( - 'exact', - _params['exact'].value if hasattr(_params['exact'], 'value') else _params['exact'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetDataEnriched]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/enriched/query/name/{datasetName}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasets_query_by_name(self, dataset_name : constr(strict=True, min_length=1), shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, exact : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which match the name exactly (not just by prefix)")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[DatasetData]: # noqa: E501 - """get_datasets_query_by_name # noqa: E501 - - Query for datasets by their name prefix unless exact flag is set # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_query_by_name(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_name: (required) - :type dataset_name: str - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param exact: if set, only returns the datasets which match the name exactly (not just by prefix) - :type exact: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasets_query_by_name_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasets_query_by_name_with_http_info(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasets_query_by_name_with_http_info(self, dataset_name : constr(strict=True, min_length=1), shared : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which have been shared with the user")] = None, exact : Annotated[Optional[StrictBool], Field(description="if set, only returns the datasets which match the name exactly (not just by prefix)")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_datasets_query_by_name # noqa: E501 - - Query for datasets by their name prefix unless exact flag is set # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasets_query_by_name_with_http_info(dataset_name, shared, exact, get_assets_of_team, get_assets_of_team_inclusive_self, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_name: (required) - :type dataset_name: str - :param shared: if set, only returns the datasets which have been shared with the user - :type shared: bool - :param exact: if set, only returns the datasets which match the name exactly (not just by prefix) - :type exact: bool - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_name', - 'shared', - 'exact', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasets_query_by_name" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_name']: - _path_params['datasetName'] = _params['dataset_name'] - - - # process the query parameters - _query_params = [] - if _params.get('shared') is not None: # noqa: E501 - _query_params.append(( - 'shared', - _params['shared'].value if hasattr(_params['shared'], 'value') else _params['shared'] - )) - - if _params.get('exact') is not None: # noqa: E501 - _query_params.append(( - 'exact', - _params['exact'].value if hasattr(_params['exact'], 'value') else _params['exact'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/query/name/{datasetName}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def register_dataset_upload_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], job_status_meta : JobStatusMeta, **kwargs) -> None: # noqa: E501 - """register_dataset_upload_by_id # noqa: E501 - - Registers a job to track the dataset upload # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.register_dataset_upload_by_id(dataset_id, job_status_meta, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param job_status_meta: (required) - :type job_status_meta: JobStatusMeta - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the register_dataset_upload_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.register_dataset_upload_by_id_with_http_info(dataset_id, job_status_meta, **kwargs) # noqa: E501 - - @validate_arguments - def register_dataset_upload_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], job_status_meta : JobStatusMeta, **kwargs) -> ApiResponse: # noqa: E501 - """register_dataset_upload_by_id # noqa: E501 - - Registers a job to track the dataset upload # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.register_dataset_upload_by_id_with_http_info(dataset_id, job_status_meta, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param job_status_meta: (required) - :type job_status_meta: JobStatusMeta - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'job_status_meta' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method register_dataset_upload_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['job_status_meta'] is not None: - _body_params = _params['job_status_meta'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/registerDatasetUpload', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_dataset_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], dataset_update_request : Annotated[DatasetUpdateRequest, Field(..., description="updated data for dataset")], **kwargs) -> None: # noqa: E501 - """update_dataset_by_id # noqa: E501 - - Update a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_dataset_by_id(dataset_id, dataset_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param dataset_update_request: updated data for dataset (required) - :type dataset_update_request: DatasetUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_dataset_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_dataset_by_id_with_http_info(dataset_id, dataset_update_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_dataset_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], dataset_update_request : Annotated[DatasetUpdateRequest, Field(..., description="updated data for dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """update_dataset_by_id # noqa: E501 - - Update a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_dataset_by_id_with_http_info(dataset_id, dataset_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param dataset_update_request: updated data for dataset (required) - :type dataset_update_request: DatasetUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'dataset_update_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_dataset_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['dataset_update_request'] is not None: - _body_params = _params['dataset_update_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/datasources_api.py b/lightly/openapi_generated/swagger_client/api/datasources_api.py deleted file mode 100644 index 63d82eac1..000000000 --- a/lightly/openapi_generated/swagger_client/api/datasources_api.py +++ /dev/null @@ -1,2510 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictStr, conint, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.datasource_config import DatasourceConfig -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data import DatasourceConfigVerifyData -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_request import DatasourceProcessedUntilTimestampRequest -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_response import DatasourceProcessedUntilTimestampResponse -from lightly.openapi_generated.swagger_client.models.datasource_purpose import DatasourcePurpose -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data import DatasourceRawSamplesData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data import DatasourceRawSamplesMetadataData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data import DatasourceRawSamplesPredictionsData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class DatasourcesApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def get_custom_embedding_file_read_url_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the csv file within the embeddings folder to get the GET readUrl for")], **kwargs) -> str: # noqa: E501 - """get_custom_embedding_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a custom embedding csv file within the embeddings folder (e.g myCustomEmbedding.csv) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_custom_embedding_file_read_url_from_datasource_by_dataset_id(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the csv file within the embeddings folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_custom_embedding_file_read_url_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_custom_embedding_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_custom_embedding_file_read_url_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the csv file within the embeddings folder to get the GET readUrl for")], **kwargs) -> ApiResponse: # noqa: E501 - """get_custom_embedding_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a custom embedding csv file within the embeddings folder (e.g myCustomEmbedding.csv) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_custom_embedding_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the csv file within the embeddings folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_custom_embedding_file_read_url_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/embeddings/file', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], purpose : Annotated[Optional[DatasourcePurpose], Field(description="Which datasource with which purpose we want to get. Defaults to INPUT_OUTPUT")] = None, **kwargs) -> DatasourceConfig: # noqa: E501 - """(Deprecated) get_datasource_by_dataset_id # noqa: E501 - - DEPRECATED - use getDatasourcesByDatasetId. Get the datasource of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasource_by_dataset_id(dataset_id, purpose, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param purpose: Which datasource with which purpose we want to get. Defaults to INPUT_OUTPUT - :type purpose: DatasourcePurpose - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceConfig - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasource_by_dataset_id_with_http_info(dataset_id, purpose, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], purpose : Annotated[Optional[DatasourcePurpose], Field(description="Which datasource with which purpose we want to get. Defaults to INPUT_OUTPUT")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_datasource_by_dataset_id # noqa: E501 - - DEPRECATED - use getDatasourcesByDatasetId. Get the datasource of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasource_by_dataset_id_with_http_info(dataset_id, purpose, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param purpose: Which datasource with which purpose we want to get. Defaults to INPUT_OUTPUT - :type purpose: DatasourcePurpose - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceConfig, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/datasource is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'purpose' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('purpose') is not None: # noqa: E501 - _query_params.append(( - 'purpose', - _params['purpose'].value if hasattr(_params['purpose'], 'value') else _params['purpose'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceConfig", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasource_processed_until_timestamp_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> DatasourceProcessedUntilTimestampResponse: # noqa: E501 - """get_datasource_processed_until_timestamp_by_dataset_id # noqa: E501 - - Get timestamp of last treated resource # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasource_processed_until_timestamp_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceProcessedUntilTimestampResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasource_processed_until_timestamp_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasource_processed_until_timestamp_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasource_processed_until_timestamp_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_datasource_processed_until_timestamp_by_dataset_id # noqa: E501 - - Get timestamp of last treated resource # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasource_processed_until_timestamp_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceProcessedUntilTimestampResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasource_processed_until_timestamp_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceProcessedUntilTimestampResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/processedUntilTimestamp', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_datasources_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[DatasourceConfig]: # noqa: E501 - """get_datasources_by_dataset_id # noqa: E501 - - Get all the datasources of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasources_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasourceConfig] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_datasources_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_datasources_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_datasources_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_datasources_by_dataset_id # noqa: E501 - - Get all the datasources of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_datasources_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasourceConfig], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_datasources_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasourceConfig]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/all', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_head_file_read_url_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The name of the file within the the datasource to get a HEAD readUrl or GET readURL")], **kwargs) -> str: # noqa: E501 - """get_head_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get a HEAD ReadURL of a file within datasources. Can only be used for HEAD request, no GET requests. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_head_file_read_url_from_datasource_by_dataset_id(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the the datasource to get a HEAD readUrl or GET readURL (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_head_file_read_url_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_head_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_head_file_read_url_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The name of the file within the the datasource to get a HEAD readUrl or GET readURL")], **kwargs) -> ApiResponse: # noqa: E501 - """get_head_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get a HEAD ReadURL of a file within datasources. Can only be used for HEAD request, no GET requests. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_head_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the the datasource to get a HEAD readUrl or GET readURL (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_head_file_read_url_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/fileHEAD', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_list_of_raw_samples_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, **kwargs) -> DatasourceRawSamplesData: # noqa: E501 - """get_list_of_raw_samples_from_datasource_by_dataset_id # noqa: E501 - - Get list of raw samples from datasource # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_from_datasource_by_dataset_id(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceRawSamplesData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_list_of_raw_samples_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_list_of_raw_samples_from_datasource_by_dataset_id_with_http_info(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_list_of_raw_samples_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_list_of_raw_samples_from_datasource_by_dataset_id # noqa: E501 - - Get list of raw samples from datasource # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_from_datasource_by_dataset_id_with_http_info(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceRawSamplesData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'var_from', - 'to', - 'cursor', - 'use_redirected_read_url', - 'relevant_filenames_file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_list_of_raw_samples_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('var_from') is not None: # noqa: E501 - _query_params.append(( - 'from', - _params['var_from'].value if hasattr(_params['var_from'], 'value') else _params['var_from'] - )) - - if _params.get('to') is not None: # noqa: E501 - _query_params.append(( - 'to', - _params['to'].value if hasattr(_params['to'], 'value') else _params['to'] - )) - - if _params.get('cursor') is not None: # noqa: E501 - _query_params.append(( - 'cursor', - _params['cursor'].value if hasattr(_params['cursor'], 'value') else _params['cursor'] - )) - - if _params.get('use_redirected_read_url') is not None: # noqa: E501 - _query_params.append(( - 'useRedirectedReadUrl', - _params['use_redirected_read_url'].value if hasattr(_params['use_redirected_read_url'], 'value') else _params['use_redirected_read_url'] - )) - - if _params.get('relevant_filenames_file_name') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesFileName', - _params['relevant_filenames_file_name'].value if hasattr(_params['relevant_filenames_file_name'], 'value') else _params['relevant_filenames_file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceRawSamplesData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/list', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_list_of_raw_samples_metadata_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, relevant_filenames_run_id : Annotated[Optional[constr(strict=True)], Field(description="The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) ")] = None, relevant_filenames_artifact_id : Annotated[Optional[constr(strict=True)], Field(description="The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. ")] = None, **kwargs) -> DatasourceRawSamplesMetadataData: # noqa: E501 - """get_list_of_raw_samples_metadata_from_datasource_by_dataset_id # noqa: E501 - - Get list of the raw samples metadata from datasource for a specific taskName # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param relevant_filenames_run_id: The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) - :type relevant_filenames_run_id: str - :param relevant_filenames_artifact_id: The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. - :type relevant_filenames_artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceRawSamplesMetadataData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_list_of_raw_samples_metadata_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id_with_http_info(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_list_of_raw_samples_metadata_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, relevant_filenames_run_id : Annotated[Optional[constr(strict=True)], Field(description="The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) ")] = None, relevant_filenames_artifact_id : Annotated[Optional[constr(strict=True)], Field(description="The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_list_of_raw_samples_metadata_from_datasource_by_dataset_id # noqa: E501 - - Get list of the raw samples metadata from datasource for a specific taskName # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id_with_http_info(dataset_id, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param relevant_filenames_run_id: The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) - :type relevant_filenames_run_id: str - :param relevant_filenames_artifact_id: The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. - :type relevant_filenames_artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceRawSamplesMetadataData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'var_from', - 'to', - 'cursor', - 'use_redirected_read_url', - 'relevant_filenames_file_name', - 'relevant_filenames_run_id', - 'relevant_filenames_artifact_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_list_of_raw_samples_metadata_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('var_from') is not None: # noqa: E501 - _query_params.append(( - 'from', - _params['var_from'].value if hasattr(_params['var_from'], 'value') else _params['var_from'] - )) - - if _params.get('to') is not None: # noqa: E501 - _query_params.append(( - 'to', - _params['to'].value if hasattr(_params['to'], 'value') else _params['to'] - )) - - if _params.get('cursor') is not None: # noqa: E501 - _query_params.append(( - 'cursor', - _params['cursor'].value if hasattr(_params['cursor'], 'value') else _params['cursor'] - )) - - if _params.get('use_redirected_read_url') is not None: # noqa: E501 - _query_params.append(( - 'useRedirectedReadUrl', - _params['use_redirected_read_url'].value if hasattr(_params['use_redirected_read_url'], 'value') else _params['use_redirected_read_url'] - )) - - if _params.get('relevant_filenames_file_name') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesFileName', - _params['relevant_filenames_file_name'].value if hasattr(_params['relevant_filenames_file_name'], 'value') else _params['relevant_filenames_file_name'] - )) - - if _params.get('relevant_filenames_run_id') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesRunId', - _params['relevant_filenames_run_id'].value if hasattr(_params['relevant_filenames_run_id'], 'value') else _params['relevant_filenames_run_id'] - )) - - if _params.get('relevant_filenames_artifact_id') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesArtifactId', - _params['relevant_filenames_artifact_id'].value if hasattr(_params['relevant_filenames_artifact_id'], 'value') else _params['relevant_filenames_artifact_id'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceRawSamplesMetadataData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/metadata/list', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_list_of_raw_samples_predictions_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, relevant_filenames_run_id : Annotated[Optional[constr(strict=True)], Field(description="The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) ")] = None, relevant_filenames_artifact_id : Annotated[Optional[constr(strict=True)], Field(description="The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. ")] = None, **kwargs) -> DatasourceRawSamplesPredictionsData: # noqa: E501 - """get_list_of_raw_samples_predictions_from_datasource_by_dataset_id # noqa: E501 - - Get list of the raw samples predictions from datasource for a specific taskName # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id(dataset_id, task_name, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param relevant_filenames_run_id: The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) - :type relevant_filenames_run_id: str - :param relevant_filenames_artifact_id: The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. - :type relevant_filenames_artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceRawSamplesPredictionsData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_list_of_raw_samples_predictions_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id_with_http_info(dataset_id, task_name, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_list_of_raw_samples_predictions_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], var_from : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, to : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. ")] = None, cursor : Annotated[Optional[StrictStr], Field(description="Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. ")] = None, use_redirected_read_url : Annotated[Optional[StrictBool], Field(description="By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file ")] = None, relevant_filenames_file_name : Annotated[Optional[constr(strict=True, min_length=4)], Field(description="The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details ")] = None, relevant_filenames_run_id : Annotated[Optional[constr(strict=True)], Field(description="The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) ")] = None, relevant_filenames_artifact_id : Annotated[Optional[constr(strict=True)], Field(description="The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_list_of_raw_samples_predictions_from_datasource_by_dataset_id # noqa: E501 - - Get list of the raw samples predictions from datasource for a specific taskName # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id_with_http_info(dataset_id, task_name, var_from, to, cursor, use_redirected_read_url, relevant_filenames_file_name, relevant_filenames_run_id, relevant_filenames_artifact_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param var_from: Unix timestamp, only samples with a creation date after `from` will be returned. This parameter is ignored if `cursor` is specified. - :type var_from: int - :param to: Unix timestamp, only samples with a creation date before `to` will be returned. This parameter is ignored if `cursor` is specified. - :type to: int - :param cursor: Cursor from previous request, encodes `from` and `to` parameters. Specify to continue reading samples from the list. - :type cursor: str - :param use_redirected_read_url: By default this is set to false unless a S3DelegatedAccess is configured in which case its always true and this param has no effect. When true this will return RedirectedReadUrls instead of ReadUrls meaning that returned URLs allow for unlimited access to the file - :type use_redirected_read_url: bool - :param relevant_filenames_file_name: The name of the file within your datasource which contains a list of relevant filenames to list. See https://docs.lightly.ai/docker/getting_started/first_steps.html#specify-relevant-files for more details - :type relevant_filenames_file_name: str - :param relevant_filenames_run_id: The run id of the run which generated an artifact to be used as the relevant filenames file. (see DatasourceRelevantFilenamesArtifactIdParam) - :type relevant_filenames_run_id: str - :param relevant_filenames_artifact_id: The artifact id of the run provided by DatasourceRelevantFilenamesRunIdParam to be used as the relevant filenames file. - :type relevant_filenames_artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceRawSamplesPredictionsData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'task_name', - 'var_from', - 'to', - 'cursor', - 'use_redirected_read_url', - 'relevant_filenames_file_name', - 'relevant_filenames_run_id', - 'relevant_filenames_artifact_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_list_of_raw_samples_predictions_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('task_name') is not None: # noqa: E501 - _query_params.append(( - 'taskName', - _params['task_name'].value if hasattr(_params['task_name'], 'value') else _params['task_name'] - )) - - if _params.get('var_from') is not None: # noqa: E501 - _query_params.append(( - 'from', - _params['var_from'].value if hasattr(_params['var_from'], 'value') else _params['var_from'] - )) - - if _params.get('to') is not None: # noqa: E501 - _query_params.append(( - 'to', - _params['to'].value if hasattr(_params['to'], 'value') else _params['to'] - )) - - if _params.get('cursor') is not None: # noqa: E501 - _query_params.append(( - 'cursor', - _params['cursor'].value if hasattr(_params['cursor'], 'value') else _params['cursor'] - )) - - if _params.get('use_redirected_read_url') is not None: # noqa: E501 - _query_params.append(( - 'useRedirectedReadUrl', - _params['use_redirected_read_url'].value if hasattr(_params['use_redirected_read_url'], 'value') else _params['use_redirected_read_url'] - )) - - if _params.get('relevant_filenames_file_name') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesFileName', - _params['relevant_filenames_file_name'].value if hasattr(_params['relevant_filenames_file_name'], 'value') else _params['relevant_filenames_file_name'] - )) - - if _params.get('relevant_filenames_run_id') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesRunId', - _params['relevant_filenames_run_id'].value if hasattr(_params['relevant_filenames_run_id'], 'value') else _params['relevant_filenames_run_id'] - )) - - if _params.get('relevant_filenames_artifact_id') is not None: # noqa: E501 - _query_params.append(( - 'relevantFilenamesArtifactId', - _params['relevant_filenames_artifact_id'].value if hasattr(_params['relevant_filenames_artifact_id'], 'value') else _params['relevant_filenames_artifact_id'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceRawSamplesPredictionsData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/predictions/list', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_metadata_file_read_url_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=5), Field(..., description="The name of the file within the metadata folder to get the GET readUrl for")], **kwargs) -> str: # noqa: E501 - """get_metadata_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a file within the metadata folder (e.g. my_image.json or my_video-099-mp4.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_metadata_file_read_url_from_datasource_by_dataset_id(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the metadata folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_metadata_file_read_url_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_metadata_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_metadata_file_read_url_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=5), Field(..., description="The name of the file within the metadata folder to get the GET readUrl for")], **kwargs) -> ApiResponse: # noqa: E501 - """get_metadata_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a file within the metadata folder (e.g. my_image.json or my_video-099-mp4.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_metadata_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the metadata folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_metadata_file_read_url_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/metadata/file', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_prediction_file_read_url_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the file within the prediction folder to get the GET readUrl for")], **kwargs) -> str: # noqa: E501 - """get_prediction_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a file within the predictions folder (e.g tasks.json or my_classification_task/schema.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_file_read_url_from_datasource_by_dataset_id(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the prediction folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_prediction_file_read_url_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_prediction_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_prediction_file_read_url_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the file within the prediction folder to get the GET readUrl for")], **kwargs) -> ApiResponse: # noqa: E501 - """get_prediction_file_read_url_from_datasource_by_dataset_id # noqa: E501 - - Get the GET ReadURL of a file within the predictions folder (e.g tasks.json or my_classification_task/schema.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_file_read_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the prediction folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_prediction_file_read_url_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/predictions/file', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_prediction_file_write_url_from_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the file within the prediction folder to get the GET readUrl for")], **kwargs) -> str: # noqa: E501 - """get_prediction_file_write_url_from_datasource_by_dataset_id # noqa: E501 - - Get the WriteURL of a file within the predictions folder (e.g tasks.json or my_classification_task/schema.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_file_write_url_from_datasource_by_dataset_id(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the prediction folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_prediction_file_write_url_from_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_prediction_file_write_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_prediction_file_write_url_from_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[constr(strict=True, min_length=4), Field(..., description="The name of the file within the prediction folder to get the GET readUrl for")], **kwargs) -> ApiResponse: # noqa: E501 - """get_prediction_file_write_url_from_datasource_by_dataset_id # noqa: E501 - - Get the WriteURL of a file within the predictions folder (e.g tasks.json or my_classification_task/schema.json) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_file_write_url_from_datasource_by_dataset_id_with_http_info(dataset_id, file_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: The name of the file within the prediction folder to get the GET readUrl for (required) - :type file_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_prediction_file_write_url_from_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/predictions/writeUrl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_resource_read_url_redirect(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], path : Annotated[StrictStr, Field(..., description="the resource path")], **kwargs) -> None: # noqa: E501 - """get_resource_read_url_redirect # noqa: E501 - - This endpoint enables anyone given the correct credentials to access the actual image directly via a redirect. By creating a readURL for the resource and redirecting to that URL, the client can use this endpoint to always have a way to access the resource as there is no expiration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_resource_read_url_redirect(dataset_id, path, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param path: the resource path (required) - :type path: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_resource_read_url_redirect_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_resource_read_url_redirect_with_http_info(dataset_id, path, **kwargs) # noqa: E501 - - @validate_arguments - def get_resource_read_url_redirect_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], path : Annotated[StrictStr, Field(..., description="the resource path")], **kwargs) -> ApiResponse: # noqa: E501 - """get_resource_read_url_redirect # noqa: E501 - - This endpoint enables anyone given the correct credentials to access the actual image directly via a redirect. By creating a readURL for the resource and redirecting to that URL, the client can use this endpoint to always have a way to access the resource as there is no expiration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_resource_read_url_redirect_with_http_info(dataset_id, path, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param path: the resource path (required) - :type path: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'path' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_resource_read_url_redirect" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('path') is not None: # noqa: E501 - _query_params.append(( - 'path', - _params['path'].value if hasattr(_params['path'], 'value') else _params['path'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['ApiPublicJWTAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/readurlRedirect', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], datasource_config : Annotated[DatasourceConfig, Field(..., description="updated datasource configuration for a dataset")], **kwargs) -> None: # noqa: E501 - """update_datasource_by_dataset_id # noqa: E501 - - Update the datasource of a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_datasource_by_dataset_id(dataset_id, datasource_config, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param datasource_config: updated datasource configuration for a dataset (required) - :type datasource_config: DatasourceConfig - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_datasource_by_dataset_id_with_http_info(dataset_id, datasource_config, **kwargs) # noqa: E501 - - @validate_arguments - def update_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], datasource_config : Annotated[DatasourceConfig, Field(..., description="updated datasource configuration for a dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """update_datasource_by_dataset_id # noqa: E501 - - Update the datasource of a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_datasource_by_dataset_id_with_http_info(dataset_id, datasource_config, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param datasource_config: updated datasource configuration for a dataset (required) - :type datasource_config: DatasourceConfig - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'datasource_config' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['datasource_config'] is not None: - _body_params = _params['datasource_config'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_datasource_processed_until_timestamp_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], datasource_processed_until_timestamp_request : Annotated[DatasourceProcessedUntilTimestampRequest, Field(..., description="The updated timestamp to set")], **kwargs) -> None: # noqa: E501 - """update_datasource_processed_until_timestamp_by_dataset_id # noqa: E501 - - Update timestamp of last resource in datapool # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_datasource_processed_until_timestamp_by_dataset_id(dataset_id, datasource_processed_until_timestamp_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param datasource_processed_until_timestamp_request: The updated timestamp to set (required) - :type datasource_processed_until_timestamp_request: DatasourceProcessedUntilTimestampRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_datasource_processed_until_timestamp_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_datasource_processed_until_timestamp_by_dataset_id_with_http_info(dataset_id, datasource_processed_until_timestamp_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_datasource_processed_until_timestamp_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], datasource_processed_until_timestamp_request : Annotated[DatasourceProcessedUntilTimestampRequest, Field(..., description="The updated timestamp to set")], **kwargs) -> ApiResponse: # noqa: E501 - """update_datasource_processed_until_timestamp_by_dataset_id # noqa: E501 - - Update timestamp of last resource in datapool # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_datasource_processed_until_timestamp_by_dataset_id_with_http_info(dataset_id, datasource_processed_until_timestamp_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param datasource_processed_until_timestamp_request: The updated timestamp to set (required) - :type datasource_processed_until_timestamp_request: DatasourceProcessedUntilTimestampRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'datasource_processed_until_timestamp_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_datasource_processed_until_timestamp_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['datasource_processed_until_timestamp_request'] is not None: - _body_params = _params['datasource_processed_until_timestamp_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/processedUntilTimestamp', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def verify_datasource_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> DatasourceConfigVerifyData: # noqa: E501 - """verify_datasource_by_dataset_id # noqa: E501 - - Test and verify that the configured datasource can be accessed correctly # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.verify_datasource_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DatasourceConfigVerifyData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the verify_datasource_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.verify_datasource_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def verify_datasource_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """verify_datasource_by_dataset_id # noqa: E501 - - Test and verify that the configured datasource can be accessed correctly # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.verify_datasource_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DatasourceConfigVerifyData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method verify_datasource_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DatasourceConfigVerifyData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/datasource/verify', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/docker_api.py b/lightly/openapi_generated/swagger_client/api/docker_api.py deleted file mode 100644 index e73bedb8e..000000000 --- a/lightly/openapi_generated/swagger_client/api/docker_api.py +++ /dev/null @@ -1,6188 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictStr, conint, conlist, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.create_docker_worker_registry_entry_request import CreateDockerWorkerRegistryEntryRequest -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.docker_authorization_request import DockerAuthorizationRequest -from lightly.openapi_generated.swagger_client.models.docker_authorization_response import DockerAuthorizationResponse -from lightly.openapi_generated.swagger_client.models.docker_license_information import DockerLicenseInformation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_create_request import DockerRunArtifactCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_created_data import DockerRunArtifactCreatedData -from lightly.openapi_generated.swagger_client.models.docker_run_create_request import DockerRunCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_data import DockerRunData -from lightly.openapi_generated.swagger_client.models.docker_run_log_create_entry_data import DockerRunLogCreateEntryData -from lightly.openapi_generated.swagger_client.models.docker_run_log_data import DockerRunLogData -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_create_request import DockerRunScheduledCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_data import DockerRunScheduledData -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_state import DockerRunScheduledState -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_update_request import DockerRunScheduledUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_update_request import DockerRunUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_user_stats import DockerUserStats -from lightly.openapi_generated.swagger_client.models.docker_worker_authorization_request import DockerWorkerAuthorizationRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_create_request import DockerWorkerConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request import DockerWorkerConfigOmniVXCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data import DockerWorkerConfigV0Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_create_request import DockerWorkerConfigV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data import DockerWorkerConfigV2Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_create_request import DockerWorkerConfigV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data import DockerWorkerConfigV3Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data import DockerWorkerConfigVXData -from lightly.openapi_generated.swagger_client.models.docker_worker_registry_entry_data import DockerWorkerRegistryEntryData -from lightly.openapi_generated.swagger_client.models.tag_data import TagData -from lightly.openapi_generated.swagger_client.models.update_docker_worker_registry_entry_request import UpdateDockerWorkerRegistryEntryRequest - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class DockerApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def cancel_scheduled_docker_run_state_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], **kwargs) -> None: # noqa: E501 - """cancel_scheduled_docker_run_state_by_id # noqa: E501 - - Cancel a scheduled run. This will fail if the state of the scheduled run is no longer OPEN (e.g when it is LOCKED) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.cancel_scheduled_docker_run_state_by_id(dataset_id, scheduled_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the cancel_scheduled_docker_run_state_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.cancel_scheduled_docker_run_state_by_id_with_http_info(dataset_id, scheduled_id, **kwargs) # noqa: E501 - - @validate_arguments - def cancel_scheduled_docker_run_state_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], **kwargs) -> ApiResponse: # noqa: E501 - """cancel_scheduled_docker_run_state_by_id # noqa: E501 - - Cancel a scheduled run. This will fail if the state of the scheduled run is no longer OPEN (e.g when it is LOCKED) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.cancel_scheduled_docker_run_state_by_id_with_http_info(dataset_id, scheduled_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'scheduled_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method cancel_scheduled_docker_run_state_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['scheduled_id']: - _path_params['scheduledId'] = _params['scheduled_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/docker/worker/schedule/{scheduledId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def confirm_docker_run_artifact_creation(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], artifact_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the artifact of the docker run")], **kwargs) -> None: # noqa: E501 - """confirm_docker_run_artifact_creation # noqa: E501 - - confirm that the docker run artifact has been uploaded and is available # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.confirm_docker_run_artifact_creation(run_id, artifact_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param artifact_id: ObjectId of the artifact of the docker run (required) - :type artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the confirm_docker_run_artifact_creation_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.confirm_docker_run_artifact_creation_with_http_info(run_id, artifact_id, **kwargs) # noqa: E501 - - @validate_arguments - def confirm_docker_run_artifact_creation_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], artifact_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the artifact of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """confirm_docker_run_artifact_creation # noqa: E501 - - confirm that the docker run artifact has been uploaded and is available # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.confirm_docker_run_artifact_creation_with_http_info(run_id, artifact_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param artifact_id: ObjectId of the artifact of the docker run (required) - :type artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'artifact_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method confirm_docker_run_artifact_creation" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - if _params['artifact_id']: - _path_params['artifactId'] = _params['artifact_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/artifacts/{artifactId}/confirmUpload', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_run(self, docker_run_create_request : DockerRunCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_docker_run # noqa: E501 - - Creates a new docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run(docker_run_create_request, async_req=True) - >>> result = thread.get() - - :param docker_run_create_request: (required) - :type docker_run_create_request: DockerRunCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_run_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_run_with_http_info(docker_run_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_run_with_http_info(self, docker_run_create_request : DockerRunCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_docker_run # noqa: E501 - - Creates a new docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_with_http_info(docker_run_create_request, async_req=True) - >>> result = thread.get() - - :param docker_run_create_request: (required) - :type docker_run_create_request: DockerRunCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'docker_run_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_run" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_create_request'] is not None: - _body_params = _params['docker_run_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_run_artifact(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_artifact_create_request : DockerRunArtifactCreateRequest, **kwargs) -> DockerRunArtifactCreatedData: # noqa: E501 - """create_docker_run_artifact # noqa: E501 - - creates a docker run artifact and returns the writeUrl and artifactId to upload and confirm # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_artifact(run_id, docker_run_artifact_create_request, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_artifact_create_request: (required) - :type docker_run_artifact_create_request: DockerRunArtifactCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerRunArtifactCreatedData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_run_artifact_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_run_artifact_with_http_info(run_id, docker_run_artifact_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_run_artifact_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_artifact_create_request : DockerRunArtifactCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_docker_run_artifact # noqa: E501 - - creates a docker run artifact and returns the writeUrl and artifactId to upload and confirm # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_artifact_with_http_info(run_id, docker_run_artifact_create_request, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_artifact_create_request: (required) - :type docker_run_artifact_create_request: DockerRunArtifactCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerRunArtifactCreatedData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'docker_run_artifact_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_run_artifact" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_artifact_create_request'] is not None: - _body_params = _params['docker_run_artifact_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "DockerRunArtifactCreatedData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/artifacts', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_run_log_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_log_create_entry_data : conlist(DockerRunLogCreateEntryData), **kwargs) -> None: # noqa: E501 - """create_docker_run_log_by_id # noqa: E501 - - Creates a new log msg for a docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_log_by_id(run_id, docker_run_log_create_entry_data, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_log_create_entry_data: (required) - :type docker_run_log_create_entry_data: List[DockerRunLogCreateEntryData] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_run_log_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_run_log_by_id_with_http_info(run_id, docker_run_log_create_entry_data, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_run_log_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_log_create_entry_data : conlist(DockerRunLogCreateEntryData), **kwargs) -> ApiResponse: # noqa: E501 - """create_docker_run_log_by_id # noqa: E501 - - Creates a new log msg for a docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_log_by_id_with_http_info(run_id, docker_run_log_create_entry_data, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_log_create_entry_data: (required) - :type docker_run_log_create_entry_data: List[DockerRunLogCreateEntryData] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'docker_run_log_create_entry_data' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_run_log_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_log_create_entry_data'] is not None: - _body_params = _params['docker_run_log_create_entry_data'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/logs', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_run_scheduled_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], docker_run_scheduled_create_request : DockerRunScheduledCreateRequest, disable_config_validation : Annotated[Optional[StrictBool], Field(description="if set, disables the sanity check and validation where we check if the provided configuration can run on your datasource e.g if predictions are used, we check that the bucket structure + tasks.json, schema.json are correct if metadata is used, we check that the bucket structure + schema.json are correct if relevantFilenamesFile is set, we check that the file exists ")] = None, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_docker_run_scheduled_by_dataset_id # noqa: E501 - - Schedule a docker run by dataset id. With docker runs it's possible to process unlabeled images from a datasource and use active learning to select the most relevant samples for further processing and visualization in the web app # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_scheduled_by_dataset_id(dataset_id, docker_run_scheduled_create_request, disable_config_validation, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param docker_run_scheduled_create_request: (required) - :type docker_run_scheduled_create_request: DockerRunScheduledCreateRequest - :param disable_config_validation: if set, disables the sanity check and validation where we check if the provided configuration can run on your datasource e.g if predictions are used, we check that the bucket structure + tasks.json, schema.json are correct if metadata is used, we check that the bucket structure + schema.json are correct if relevantFilenamesFile is set, we check that the file exists - :type disable_config_validation: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_run_scheduled_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_run_scheduled_by_dataset_id_with_http_info(dataset_id, docker_run_scheduled_create_request, disable_config_validation, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_run_scheduled_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], docker_run_scheduled_create_request : DockerRunScheduledCreateRequest, disable_config_validation : Annotated[Optional[StrictBool], Field(description="if set, disables the sanity check and validation where we check if the provided configuration can run on your datasource e.g if predictions are used, we check that the bucket structure + tasks.json, schema.json are correct if metadata is used, we check that the bucket structure + schema.json are correct if relevantFilenamesFile is set, we check that the file exists ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """create_docker_run_scheduled_by_dataset_id # noqa: E501 - - Schedule a docker run by dataset id. With docker runs it's possible to process unlabeled images from a datasource and use active learning to select the most relevant samples for further processing and visualization in the web app # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_run_scheduled_by_dataset_id_with_http_info(dataset_id, docker_run_scheduled_create_request, disable_config_validation, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param docker_run_scheduled_create_request: (required) - :type docker_run_scheduled_create_request: DockerRunScheduledCreateRequest - :param disable_config_validation: if set, disables the sanity check and validation where we check if the provided configuration can run on your datasource e.g if predictions are used, we check that the bucket structure + tasks.json, schema.json are correct if metadata is used, we check that the bucket structure + schema.json are correct if relevantFilenamesFile is set, we check that the file exists - :type disable_config_validation: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'docker_run_scheduled_create_request', - 'disable_config_validation' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_run_scheduled_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('disable_config_validation') is not None: # noqa: E501 - _query_params.append(( - 'disableConfigValidation', - _params['disable_config_validation'].value if hasattr(_params['disable_config_validation'], 'value') else _params['disable_config_validation'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_scheduled_create_request'] is not None: - _body_params = _params['docker_run_scheduled_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/docker/worker/schedule', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_worker_config(self, docker_worker_config_create_request : DockerWorkerConfigCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config # noqa: E501 - - Creates a docker worker configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config(docker_worker_config_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_create_request: (required) - :type docker_worker_config_create_request: DockerWorkerConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_worker_config_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_worker_config_with_http_info(docker_worker_config_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_worker_config_with_http_info(self, docker_worker_config_create_request : DockerWorkerConfigCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config # noqa: E501 - - Creates a docker worker configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_with_http_info(docker_worker_config_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_create_request: (required) - :type docker_worker_config_create_request: DockerWorkerConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("POST /v1/docker/worker/config is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'docker_worker_config_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_worker_config" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_config_create_request'] is not None: - _body_params = _params['docker_worker_config_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_worker_config_v2(self, docker_worker_config_v2_create_request : DockerWorkerConfigV2CreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config_v2 # noqa: E501 - - Creates a docker worker v2 configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_v2(docker_worker_config_v2_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_v2_create_request: (required) - :type docker_worker_config_v2_create_request: DockerWorkerConfigV2CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_worker_config_v2_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_worker_config_v2_with_http_info(docker_worker_config_v2_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_worker_config_v2_with_http_info(self, docker_worker_config_v2_create_request : DockerWorkerConfigV2CreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config_v2 # noqa: E501 - - Creates a docker worker v2 configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_v2_with_http_info(docker_worker_config_v2_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_v2_create_request: (required) - :type docker_worker_config_v2_create_request: DockerWorkerConfigV2CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("POST /v1/docker/worker/config/v2 is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'docker_worker_config_v2_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_worker_config_v2" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_config_v2_create_request'] is not None: - _body_params = _params['docker_worker_config_v2_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/v2', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_worker_config_v3(self, docker_worker_config_v3_create_request : DockerWorkerConfigV3CreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config_v3 # noqa: E501 - - Creates a docker worker v3 configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_v3(docker_worker_config_v3_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_v3_create_request: (required) - :type docker_worker_config_v3_create_request: DockerWorkerConfigV3CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_worker_config_v3_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_worker_config_v3_with_http_info(docker_worker_config_v3_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_worker_config_v3_with_http_info(self, docker_worker_config_v3_create_request : DockerWorkerConfigV3CreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) create_docker_worker_config_v3 # noqa: E501 - - Creates a docker worker v3 configuration. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_v3_with_http_info(docker_worker_config_v3_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_v3_create_request: (required) - :type docker_worker_config_v3_create_request: DockerWorkerConfigV3CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("POST /v1/docker/worker/config/v3 is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'docker_worker_config_v3_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_worker_config_v3" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_config_v3_create_request'] is not None: - _body_params = _params['docker_worker_config_v3_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/v3', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_docker_worker_config_vx(self, docker_worker_config_omni_vx_create_request : DockerWorkerConfigOmniVXCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_docker_worker_config_vx # noqa: E501 - - Creates a docker worker configuration for any version. Can either be V2, V3, V4, V5 etc. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_vx(docker_worker_config_omni_vx_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_omni_vx_create_request: (required) - :type docker_worker_config_omni_vx_create_request: DockerWorkerConfigOmniVXCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_docker_worker_config_vx_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_docker_worker_config_vx_with_http_info(docker_worker_config_omni_vx_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_docker_worker_config_vx_with_http_info(self, docker_worker_config_omni_vx_create_request : DockerWorkerConfigOmniVXCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_docker_worker_config_vx # noqa: E501 - - Creates a docker worker configuration for any version. Can either be V2, V3, V4, V5 etc. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_docker_worker_config_vx_with_http_info(docker_worker_config_omni_vx_create_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_config_omni_vx_create_request: (required) - :type docker_worker_config_omni_vx_create_request: DockerWorkerConfigOmniVXCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'docker_worker_config_omni_vx_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_docker_worker_config_vx" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_config_omni_vx_create_request'] is not None: - _body_params = _params['docker_worker_config_omni_vx_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/vX', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def delete_docker_worker_registry_entry_by_id(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], **kwargs) -> None: # noqa: E501 - """delete_docker_worker_registry_entry_by_id # noqa: E501 - - Deletes a worker registry entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_docker_worker_registry_entry_by_id(worker_id, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_docker_worker_registry_entry_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_docker_worker_registry_entry_by_id_with_http_info(worker_id, **kwargs) # noqa: E501 - - @validate_arguments - def delete_docker_worker_registry_entry_by_id_with_http_info(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], **kwargs) -> ApiResponse: # noqa: E501 - """delete_docker_worker_registry_entry_by_id # noqa: E501 - - Deletes a worker registry entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_docker_worker_registry_entry_by_id_with_http_info(worker_id, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'worker_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_docker_worker_registry_entry_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['worker_id']: - _path_params['workerId'] = _params['worker_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/worker/{workerId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_license_information(self, **kwargs) -> DockerLicenseInformation: # noqa: E501 - """get_docker_license_information # noqa: E501 - - Requests license information to run the container. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_license_information(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerLicenseInformation - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_license_information_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_license_information_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def get_docker_license_information_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_license_information # noqa: E501 - - Requests license information to run the container. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_license_information_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerLicenseInformation, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_license_information" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerLicenseInformation", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/licenseInformation', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_artifact_read_url_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], artifact_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the artifact of the docker run")], **kwargs) -> str: # noqa: E501 - """get_docker_run_artifact_read_url_by_id # noqa: E501 - - Get the url of a specific docker runs artifact # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_artifact_read_url_by_id(run_id, artifact_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param artifact_id: ObjectId of the artifact of the docker run (required) - :type artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_artifact_read_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_artifact_read_url_by_id_with_http_info(run_id, artifact_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_artifact_read_url_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], artifact_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the artifact of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_run_artifact_read_url_by_id # noqa: E501 - - Get the url of a specific docker runs artifact # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_artifact_read_url_by_id_with_http_info(run_id, artifact_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param artifact_id: ObjectId of the artifact of the docker run (required) - :type artifact_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'artifact_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_artifact_read_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - if _params['artifact_id']: - _path_params['artifactId'] = _params['artifact_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/artifacts/{artifactId}/readurl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> DockerRunData: # noqa: E501 - """get_docker_run_by_id # noqa: E501 - - Gets a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_by_id(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerRunData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_by_id_with_http_info(run_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_run_by_id # noqa: E501 - - Gets a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_by_id_with_http_info(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerRunData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'run_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerRunData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_by_scheduled_id(self, scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], **kwargs) -> DockerRunData: # noqa: E501 - """get_docker_run_by_scheduled_id # noqa: E501 - - Retrieves the associated docker run of a scheduled run; returns the docker run by the id of the scheduled run which caused this docker run. If a scheduled docker run has not yet started being processed by a worker, a 404 will be returned. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_by_scheduled_id(scheduled_id, async_req=True) - >>> result = thread.get() - - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerRunData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_by_scheduled_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_by_scheduled_id_with_http_info(scheduled_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_by_scheduled_id_with_http_info(self, scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_run_by_scheduled_id # noqa: E501 - - Retrieves the associated docker run of a scheduled run; returns the docker run by the id of the scheduled run which caused this docker run. If a scheduled docker run has not yet started being processed by a worker, a 404 will be returned. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_by_scheduled_id_with_http_info(scheduled_id, async_req=True) - >>> result = thread.get() - - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerRunData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'scheduled_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_by_scheduled_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['scheduled_id']: - _path_params['scheduledId'] = _params['scheduled_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerRunData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/schedule/{scheduledId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_logs_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], cursor : Annotated[Optional[conint(strict=True, ge=0)], Field(description="the cursor of where the logs last were")] = None, **kwargs) -> DockerRunLogData: # noqa: E501 - """get_docker_run_logs_by_id # noqa: E501 - - Gets the logs of a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_logs_by_id(run_id, cursor, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param cursor: the cursor of where the logs last were - :type cursor: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerRunLogData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_logs_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_logs_by_id_with_http_info(run_id, cursor, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_logs_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], cursor : Annotated[Optional[conint(strict=True, ge=0)], Field(description="the cursor of where the logs last were")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_run_logs_by_id # noqa: E501 - - Gets the logs of a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_logs_by_id_with_http_info(run_id, cursor, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param cursor: the cursor of where the logs last were - :type cursor: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerRunLogData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'cursor' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_logs_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - if _params.get('cursor') is not None: # noqa: E501 - _query_params.append(( - 'cursor', - _params['cursor'].value if hasattr(_params['cursor'], 'value') else _params['cursor'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerRunLogData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/logs', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_report_read_url_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> str: # noqa: E501 - """(Deprecated) get_docker_run_report_read_url_by_id # noqa: E501 - - DEPRECATED, use getDockerRunArtifactReadUrlById - Get the url of a specific docker runs report # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_report_read_url_by_id(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_report_read_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_report_read_url_by_id_with_http_info(run_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_report_read_url_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_run_report_read_url_by_id # noqa: E501 - - DEPRECATED, use getDockerRunArtifactReadUrlById - Get the url of a specific docker runs report # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_report_read_url_by_id_with_http_info(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/runs/{runId}/readReportUrl is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'run_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_report_read_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/readReportUrl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_report_write_url_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> str: # noqa: E501 - """(Deprecated) get_docker_run_report_write_url_by_id # noqa: E501 - - DEPRECATED, use createDockerRunArtifact - Get the signed url to upload a report of a docker run # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_report_write_url_by_id(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_report_write_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_report_write_url_by_id_with_http_info(run_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_report_write_url_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_run_report_write_url_by_id # noqa: E501 - - DEPRECATED, use createDockerRunArtifact - Get the signed url to upload a report of a docker run # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_report_write_url_by_id_with_http_info(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/runs/{runId}/writeReportUrl is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'run_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_report_write_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/writeReportUrl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_run_tags(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> List[TagData]: # noqa: E501 - """get_docker_run_tags # noqa: E501 - - Gets all tags which were created from a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_tags(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[TagData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_run_tags_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_run_tags_with_http_info(run_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_run_tags_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_run_tags # noqa: E501 - - Gets all tags which were created from a docker run by docker run id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_run_tags_with_http_info(run_id, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[TagData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'run_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_run_tags" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[TagData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/{runId}/tags', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs(self, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, show_archived : Annotated[Optional[StrictBool], Field(description="if this flag is true, we also get the archived assets")] = None, **kwargs) -> List[DockerRunData]: # noqa: E501 - """get_docker_runs # noqa: E501 - - Gets all docker runs for a user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs(page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, async_req=True) - >>> result = thread.get() - - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param show_archived: if this flag is true, we also get the archived assets - :type show_archived: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerRunData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_with_http_info(page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_with_http_info(self, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, show_archived : Annotated[Optional[StrictBool], Field(description="if this flag is true, we also get the archived assets")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs # noqa: E501 - - Gets all docker runs for a user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_with_http_info(page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, async_req=True) - >>> result = thread.get() - - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param show_archived: if this flag is true, we also get the archived assets - :type show_archived: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerRunData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'page_size', - 'page_offset', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'show_archived' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('show_archived') is not None: # noqa: E501 - _query_params.append(( - 'showArchived', - _params['show_archived'].value if hasattr(_params['show_archived'], 'value') else _params['show_archived'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerRunData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs_count(self, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, show_archived : Annotated[Optional[StrictBool], Field(description="if this flag is true, we also get the archived assets")] = None, **kwargs) -> str: # noqa: E501 - """get_docker_runs_count # noqa: E501 - - Gets the total count of the amount of runs existing for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_count(get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, async_req=True) - >>> result = thread.get() - - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param show_archived: if this flag is true, we also get the archived assets - :type show_archived: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_count_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_count_with_http_info(get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_count_with_http_info(self, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, show_archived : Annotated[Optional[StrictBool], Field(description="if this flag is true, we also get the archived assets")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs_count # noqa: E501 - - Gets the total count of the amount of runs existing for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_count_with_http_info(get_assets_of_team, get_assets_of_team_inclusive_self, show_archived, async_req=True) - >>> result = thread.get() - - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param show_archived: if this flag is true, we also get the archived assets - :type show_archived: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self', - 'show_archived' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs_count" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - if _params.get('show_archived') is not None: # noqa: E501 - _query_params.append(( - 'showArchived', - _params['show_archived'].value if hasattr(_params['show_archived'], 'value') else _params['show_archived'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain', 'application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/count', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs_query_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> List[DockerRunData]: # noqa: E501 - """get_docker_runs_query_by_dataset_id # noqa: E501 - - Get all docker runs of a user by dataset id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_query_by_dataset_id(dataset_id, page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerRunData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_query_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_query_by_dataset_id_with_http_info(dataset_id, page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_query_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs_query_by_dataset_id # noqa: E501 - - Get all docker runs of a user by dataset id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_query_by_dataset_id_with_http_info(dataset_id, page_size, page_offset, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerRunData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'page_size', - 'page_offset', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs_query_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerRunData]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/runs/query/datasetId/{datasetId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs_scheduled_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], state : Optional[DockerRunScheduledState] = None, **kwargs) -> List[DockerRunScheduledData]: # noqa: E501 - """get_docker_runs_scheduled_by_dataset_id # noqa: E501 - - Get all scheduled docker runs by dataset id. If no state is specified, returns runs which have not yet finished (neither DONE or CANCELED). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_dataset_id(dataset_id, state, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param state: - :type state: DockerRunScheduledState - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerRunScheduledData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_scheduled_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_scheduled_by_dataset_id_with_http_info(dataset_id, state, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_scheduled_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], state : Optional[DockerRunScheduledState] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs_scheduled_by_dataset_id # noqa: E501 - - Get all scheduled docker runs by dataset id. If no state is specified, returns runs which have not yet finished (neither DONE or CANCELED). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_dataset_id_with_http_info(dataset_id, state, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param state: - :type state: DockerRunScheduledState - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerRunScheduledData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'state' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs_scheduled_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('state') is not None: # noqa: E501 - _query_params.append(( - 'state', - _params['state'].value if hasattr(_params['state'], 'value') else _params['state'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerRunScheduledData]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/docker/worker/schedule', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs_scheduled_by_state_and_labels(self, state : Optional[DockerRunScheduledState] = None, labels : Optional[conlist(StrictStr)] = None, version : Optional[StrictStr] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> List[DockerRunScheduledData]: # noqa: E501 - """get_docker_runs_scheduled_by_state_and_labels # noqa: E501 - - Get all scheduled docker runs of the user. Additionally, you can filter by state. Furthermore, you can filter by only providing labels and only return scheduled runs whose runsOn labels are included in the provided labels. Runs are filtered by the provided version parameter. Version parameter set to * returns all configs # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_state_and_labels(state, labels, version, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param state: - :type state: DockerRunScheduledState - :param labels: - :type labels: List[str] - :param version: - :type version: str - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerRunScheduledData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_scheduled_by_state_and_labels_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_scheduled_by_state_and_labels_with_http_info(state, labels, version, get_assets_of_team, get_assets_of_team_inclusive_self, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_scheduled_by_state_and_labels_with_http_info(self, state : Optional[DockerRunScheduledState] = None, labels : Optional[conlist(StrictStr)] = None, version : Optional[StrictStr] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs_scheduled_by_state_and_labels # noqa: E501 - - Get all scheduled docker runs of the user. Additionally, you can filter by state. Furthermore, you can filter by only providing labels and only return scheduled runs whose runsOn labels are included in the provided labels. Runs are filtered by the provided version parameter. Version parameter set to * returns all configs # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_state_and_labels_with_http_info(state, labels, version, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param state: - :type state: DockerRunScheduledState - :param labels: - :type labels: List[str] - :param version: - :type version: str - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerRunScheduledData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'state', - 'labels', - 'version', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs_scheduled_by_state_and_labels" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('state') is not None: # noqa: E501 - _query_params.append(( - 'state', - _params['state'].value if hasattr(_params['state'], 'value') else _params['state'] - )) - - if _params.get('labels') is not None: # noqa: E501 - _query_params.append(( - 'labels', - _params['labels'].value if hasattr(_params['labels'], 'value') else _params['labels'] - )) - _collection_formats['labels'] = 'multi' - - if _params.get('version') is not None: # noqa: E501 - _query_params.append(( - 'version', - _params['version'].value if hasattr(_params['version'], 'value') else _params['version'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerRunScheduledData]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/schedule', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_runs_scheduled_by_worker_id(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], state : Optional[DockerRunScheduledState] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> List[DockerRunScheduledData]: # noqa: E501 - """get_docker_runs_scheduled_by_worker_id # noqa: E501 - - Get all scheduled runs that might be picked up by the worker with that workerId. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_worker_id(worker_id, state, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param state: - :type state: DockerRunScheduledState - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerRunScheduledData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_runs_scheduled_by_worker_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_runs_scheduled_by_worker_id_with_http_info(worker_id, state, get_assets_of_team, get_assets_of_team_inclusive_self, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_runs_scheduled_by_worker_id_with_http_info(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], state : Optional[DockerRunScheduledState] = None, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_runs_scheduled_by_worker_id # noqa: E501 - - Get all scheduled runs that might be picked up by the worker with that workerId. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_runs_scheduled_by_worker_id_with_http_info(worker_id, state, get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param state: - :type state: DockerRunScheduledState - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerRunScheduledData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'worker_id', - 'state', - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_runs_scheduled_by_worker_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['worker_id']: - _path_params['workerId'] = _params['worker_id'] - - - # process the query parameters - _query_params = [] - if _params.get('state') is not None: # noqa: E501 - _query_params.append(( - 'state', - _params['state'].value if hasattr(_params['state'], 'value') else _params['state'] - )) - - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerRunScheduledData]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/{workerId}/schedule', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_config_by_id(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> DockerWorkerConfigV0Data: # noqa: E501 - """(Deprecated) get_docker_worker_config_by_id # noqa: E501 - - Gets a docker worker configuration by id. It will try to return the config version but expects (and will fail if not) the config to be of v0 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_by_id(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerWorkerConfigV0Data - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_config_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_config_by_id_with_http_info(config_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_config_by_id_with_http_info(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_worker_config_by_id # noqa: E501 - - Gets a docker worker configuration by id. It will try to return the config version but expects (and will fail if not) the config to be of v0 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_by_id_with_http_info(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerWorkerConfigV0Data, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/worker/config/{configId} is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'config_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_config_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['config_id']: - _path_params['configId'] = _params['config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerWorkerConfigV0Data", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/{configId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_config_v2_by_id(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> DockerWorkerConfigV2Data: # noqa: E501 - """(Deprecated) get_docker_worker_config_v2_by_id # noqa: E501 - - Gets a docker worker configuration by id which needs to be v2 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_v2_by_id(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerWorkerConfigV2Data - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_config_v2_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_config_v2_by_id_with_http_info(config_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_config_v2_by_id_with_http_info(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_worker_config_v2_by_id # noqa: E501 - - Gets a docker worker configuration by id which needs to be v2 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_v2_by_id_with_http_info(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerWorkerConfigV2Data, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/worker/config/v2/{configId} is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'config_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_config_v2_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['config_id']: - _path_params['configId'] = _params['config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerWorkerConfigV2Data", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/v2/{configId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_config_v3_by_id(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> DockerWorkerConfigV3Data: # noqa: E501 - """(Deprecated) get_docker_worker_config_v3_by_id # noqa: E501 - - Gets a docker worker configuration by id which needs to be v3 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_v3_by_id(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerWorkerConfigV3Data - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_config_v3_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_config_v3_by_id_with_http_info(config_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_config_v3_by_id_with_http_info(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_worker_config_v3_by_id # noqa: E501 - - Gets a docker worker configuration by id which needs to be v3 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_v3_by_id_with_http_info(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerWorkerConfigV3Data, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/worker/config/v3/{configId} is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'config_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_config_v3_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['config_id']: - _path_params['configId'] = _params['config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerWorkerConfigV3Data", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/v3/{configId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_config_vxby_id(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> DockerWorkerConfigVXData: # noqa: E501 - """get_docker_worker_config_vxby_id # noqa: E501 - - Gets a docker worker configuration by id. It will return whichever config version the configId corresponds to. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_vxby_id(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerWorkerConfigVXData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_config_vxby_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_config_vxby_id_with_http_info(config_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_config_vxby_id_with_http_info(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_worker_config_vxby_id # noqa: E501 - - Gets a docker worker configuration by id. It will return whichever config version the configId corresponds to. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_config_vxby_id_with_http_info(config_id, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerWorkerConfigVXData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'config_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_config_vxby_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['config_id']: - _path_params['configId'] = _params['config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerWorkerConfigVXData", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config/vX/{configId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_configs(self, **kwargs) -> List[DockerWorkerConfigV0Data]: # noqa: E501 - """(Deprecated) get_docker_worker_configs # noqa: E501 - - Get docker worker configurations. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_configs(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerWorkerConfigV0Data] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_configs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_configs_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_configs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_docker_worker_configs # noqa: E501 - - Get docker worker configurations. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_configs_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerWorkerConfigV0Data], status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/docker/worker/config is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_configs" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerWorkerConfigV0Data]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/config', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_registry_entries(self, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> List[DockerWorkerRegistryEntryData]: # noqa: E501 - """get_docker_worker_registry_entries # noqa: E501 - - Returns all worker registry entries for a given user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_registry_entries(get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DockerWorkerRegistryEntryData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_registry_entries_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_registry_entries_with_http_info(get_assets_of_team, get_assets_of_team_inclusive_self, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_registry_entries_with_http_info(self, get_assets_of_team : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user")] = None, get_assets_of_team_inclusive_self : Annotated[Optional[StrictBool], Field(description="if this flag is true, we get the relevant asset of the team of the user including the assets of the user")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_worker_registry_entries # noqa: E501 - - Returns all worker registry entries for a given user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_registry_entries_with_http_info(get_assets_of_team, get_assets_of_team_inclusive_self, async_req=True) - >>> result = thread.get() - - :param get_assets_of_team: if this flag is true, we get the relevant asset of the team of the user rather than the assets of the user - :type get_assets_of_team: bool - :param get_assets_of_team_inclusive_self: if this flag is true, we get the relevant asset of the team of the user including the assets of the user - :type get_assets_of_team_inclusive_self: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DockerWorkerRegistryEntryData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'get_assets_of_team', - 'get_assets_of_team_inclusive_self' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_registry_entries" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('get_assets_of_team') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeam', - _params['get_assets_of_team'].value if hasattr(_params['get_assets_of_team'], 'value') else _params['get_assets_of_team'] - )) - - if _params.get('get_assets_of_team_inclusive_self') is not None: # noqa: E501 - _query_params.append(( - 'getAssetsOfTeamInclusiveSelf', - _params['get_assets_of_team_inclusive_self'].value if hasattr(_params['get_assets_of_team_inclusive_self'], 'value') else _params['get_assets_of_team_inclusive_self'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DockerWorkerRegistryEntryData]", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_docker_worker_registry_entry_by_id(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], **kwargs) -> DockerWorkerRegistryEntryData: # noqa: E501 - """get_docker_worker_registry_entry_by_id # noqa: E501 - - Returns worker registry entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_registry_entry_by_id(worker_id, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerWorkerRegistryEntryData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_docker_worker_registry_entry_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_docker_worker_registry_entry_by_id_with_http_info(worker_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_docker_worker_registry_entry_by_id_with_http_info(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], **kwargs) -> ApiResponse: # noqa: E501 - """get_docker_worker_registry_entry_by_id # noqa: E501 - - Returns worker registry entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_docker_worker_registry_entry_by_id_with_http_info(worker_id, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerWorkerRegistryEntryData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'worker_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_docker_worker_registry_entry_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['worker_id']: - _path_params['workerId'] = _params['worker_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerWorkerRegistryEntryData", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker/{workerId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def post_docker_authorization_request(self, docker_authorization_request : DockerAuthorizationRequest, **kwargs) -> DockerAuthorizationResponse: # noqa: E501 - """post_docker_authorization_request # noqa: E501 - - Performs an authorization to run the container. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_authorization_request(docker_authorization_request, async_req=True) - >>> result = thread.get() - - :param docker_authorization_request: (required) - :type docker_authorization_request: DockerAuthorizationRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DockerAuthorizationResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the post_docker_authorization_request_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.post_docker_authorization_request_with_http_info(docker_authorization_request, **kwargs) # noqa: E501 - - @validate_arguments - def post_docker_authorization_request_with_http_info(self, docker_authorization_request : DockerAuthorizationRequest, **kwargs) -> ApiResponse: # noqa: E501 - """post_docker_authorization_request # noqa: E501 - - Performs an authorization to run the container. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_authorization_request_with_http_info(docker_authorization_request, async_req=True) - >>> result = thread.get() - - :param docker_authorization_request: (required) - :type docker_authorization_request: DockerAuthorizationRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DockerAuthorizationResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'docker_authorization_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method post_docker_authorization_request" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_authorization_request'] is not None: - _body_params = _params['docker_authorization_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "DockerAuthorizationResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/authorization', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def post_docker_usage_stats(self, docker_user_stats : DockerUserStats, **kwargs) -> None: # noqa: E501 - """post_docker_usage_stats # noqa: E501 - - Adds a diagnostic entry of user stats. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_usage_stats(docker_user_stats, async_req=True) - >>> result = thread.get() - - :param docker_user_stats: (required) - :type docker_user_stats: DockerUserStats - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the post_docker_usage_stats_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.post_docker_usage_stats_with_http_info(docker_user_stats, **kwargs) # noqa: E501 - - @validate_arguments - def post_docker_usage_stats_with_http_info(self, docker_user_stats : DockerUserStats, **kwargs) -> ApiResponse: # noqa: E501 - """post_docker_usage_stats # noqa: E501 - - Adds a diagnostic entry of user stats. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_usage_stats_with_http_info(docker_user_stats, async_req=True) - >>> result = thread.get() - - :param docker_user_stats: (required) - :type docker_user_stats: DockerUserStats - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'docker_user_stats' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method post_docker_usage_stats" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_user_stats'] is not None: - _body_params = _params['docker_user_stats'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def post_docker_worker_authorization_request(self, docker_worker_authorization_request : DockerWorkerAuthorizationRequest, **kwargs) -> str: # noqa: E501 - """post_docker_worker_authorization_request # noqa: E501 - - Performs an authorization to run the Lightly Worker. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_worker_authorization_request(docker_worker_authorization_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_authorization_request: (required) - :type docker_worker_authorization_request: DockerWorkerAuthorizationRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the post_docker_worker_authorization_request_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.post_docker_worker_authorization_request_with_http_info(docker_worker_authorization_request, **kwargs) # noqa: E501 - - @validate_arguments - def post_docker_worker_authorization_request_with_http_info(self, docker_worker_authorization_request : DockerWorkerAuthorizationRequest, **kwargs) -> ApiResponse: # noqa: E501 - """post_docker_worker_authorization_request # noqa: E501 - - Performs an authorization to run the Lightly Worker. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.post_docker_worker_authorization_request_with_http_info(docker_worker_authorization_request, async_req=True) - >>> result = thread.get() - - :param docker_worker_authorization_request: (required) - :type docker_worker_authorization_request: DockerWorkerAuthorizationRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'docker_worker_authorization_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method post_docker_worker_authorization_request" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_authorization_request'] is not None: - _body_params = _params['docker_worker_authorization_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain', 'application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/workerAuthorization', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def register_docker_worker(self, create_docker_worker_registry_entry_request : CreateDockerWorkerRegistryEntryRequest, for_user_id : Annotated[Optional[StrictStr], Field(description="The userId for which we want to create the worker for. This is only allowed for users within the same team.")] = None, **kwargs) -> CreateEntityResponse: # noqa: E501 - """register_docker_worker # noqa: E501 - - Registers a worker for a user. If a worker with the same name is passed that already exists, the same workerId will be returned # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.register_docker_worker(create_docker_worker_registry_entry_request, for_user_id, async_req=True) - >>> result = thread.get() - - :param create_docker_worker_registry_entry_request: (required) - :type create_docker_worker_registry_entry_request: CreateDockerWorkerRegistryEntryRequest - :param for_user_id: The userId for which we want to create the worker for. This is only allowed for users within the same team. - :type for_user_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the register_docker_worker_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.register_docker_worker_with_http_info(create_docker_worker_registry_entry_request, for_user_id, **kwargs) # noqa: E501 - - @validate_arguments - def register_docker_worker_with_http_info(self, create_docker_worker_registry_entry_request : CreateDockerWorkerRegistryEntryRequest, for_user_id : Annotated[Optional[StrictStr], Field(description="The userId for which we want to create the worker for. This is only allowed for users within the same team.")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """register_docker_worker # noqa: E501 - - Registers a worker for a user. If a worker with the same name is passed that already exists, the same workerId will be returned # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.register_docker_worker_with_http_info(create_docker_worker_registry_entry_request, for_user_id, async_req=True) - >>> result = thread.get() - - :param create_docker_worker_registry_entry_request: (required) - :type create_docker_worker_registry_entry_request: CreateDockerWorkerRegistryEntryRequest - :param for_user_id: The userId for which we want to create the worker for. This is only allowed for users within the same team. - :type for_user_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'create_docker_worker_registry_entry_request', - 'for_user_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method register_docker_worker" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('for_user_id') is not None: # noqa: E501 - _query_params.append(( - 'forUserId', - _params['for_user_id'].value if hasattr(_params['for_user_id'], 'value') else _params['for_user_id'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['create_docker_worker_registry_entry_request'] is not None: - _body_params = _params['create_docker_worker_registry_entry_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/docker/worker', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_docker_run_by_id(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_update_request : DockerRunUpdateRequest, **kwargs) -> None: # noqa: E501 - """update_docker_run_by_id # noqa: E501 - - Updates a docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_run_by_id(run_id, docker_run_update_request, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_update_request: (required) - :type docker_run_update_request: DockerRunUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_docker_run_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_docker_run_by_id_with_http_info(run_id, docker_run_update_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_docker_run_by_id_with_http_info(self, run_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker run")], docker_run_update_request : DockerRunUpdateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """update_docker_run_by_id # noqa: E501 - - Updates a docker run database entry. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_run_by_id_with_http_info(run_id, docker_run_update_request, async_req=True) - >>> result = thread.get() - - :param run_id: ObjectId of the docker run (required) - :type run_id: str - :param docker_run_update_request: (required) - :type docker_run_update_request: DockerRunUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'run_id', - 'docker_run_update_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_docker_run_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['run_id']: - _path_params['runId'] = _params['run_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_update_request'] is not None: - _body_params = _params['docker_run_update_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/runs/{runId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_docker_worker_config_by_id(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], docker_worker_config_create_request : DockerWorkerConfigCreateRequest, **kwargs) -> None: # noqa: E501 - """(Deprecated) update_docker_worker_config_by_id # noqa: E501 - - DEPRECATED, DONT USE. Updates a docker worker configuration by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_worker_config_by_id(config_id, docker_worker_config_create_request, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param docker_worker_config_create_request: (required) - :type docker_worker_config_create_request: DockerWorkerConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_docker_worker_config_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_docker_worker_config_by_id_with_http_info(config_id, docker_worker_config_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_docker_worker_config_by_id_with_http_info(self, config_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker config")], docker_worker_config_create_request : DockerWorkerConfigCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) update_docker_worker_config_by_id # noqa: E501 - - DEPRECATED, DONT USE. Updates a docker worker configuration by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_worker_config_by_id_with_http_info(config_id, docker_worker_config_create_request, async_req=True) - >>> result = thread.get() - - :param config_id: ObjectId of the docker worker config (required) - :type config_id: str - :param docker_worker_config_create_request: (required) - :type docker_worker_config_create_request: DockerWorkerConfigCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - warnings.warn("PUT /v1/docker/worker/config/{configId} is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'config_id', - 'docker_worker_config_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_docker_worker_config_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['config_id']: - _path_params['configId'] = _params['config_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_worker_config_create_request'] is not None: - _body_params = _params['docker_worker_config_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/worker/config/{configId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_docker_worker_registry_entry_by_id(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], update_docker_worker_registry_entry_request : UpdateDockerWorkerRegistryEntryRequest, **kwargs) -> None: # noqa: E501 - """update_docker_worker_registry_entry_by_id # noqa: E501 - - Updates the worker status by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_worker_registry_entry_by_id(worker_id, update_docker_worker_registry_entry_request, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param update_docker_worker_registry_entry_request: (required) - :type update_docker_worker_registry_entry_request: UpdateDockerWorkerRegistryEntryRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_docker_worker_registry_entry_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_docker_worker_registry_entry_by_id_with_http_info(worker_id, update_docker_worker_registry_entry_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_docker_worker_registry_entry_by_id_with_http_info(self, worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], update_docker_worker_registry_entry_request : UpdateDockerWorkerRegistryEntryRequest, **kwargs) -> ApiResponse: # noqa: E501 - """update_docker_worker_registry_entry_by_id # noqa: E501 - - Updates the worker status by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_docker_worker_registry_entry_by_id_with_http_info(worker_id, update_docker_worker_registry_entry_request, async_req=True) - >>> result = thread.get() - - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param update_docker_worker_registry_entry_request: (required) - :type update_docker_worker_registry_entry_request: UpdateDockerWorkerRegistryEntryRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'worker_id', - 'update_docker_worker_registry_entry_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_docker_worker_registry_entry_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['worker_id']: - _path_params['workerId'] = _params['worker_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['update_docker_worker_registry_entry_request'] is not None: - _body_params = _params['update_docker_worker_registry_entry_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/docker/worker/{workerId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_scheduled_docker_run_state_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], docker_run_scheduled_update_request : DockerRunScheduledUpdateRequest, **kwargs) -> None: # noqa: E501 - """update_scheduled_docker_run_state_by_id # noqa: E501 - - Update the state of a scheduled run. This will fail if the state of the scheduled run is LOCKED. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_scheduled_docker_run_state_by_id(dataset_id, worker_id, scheduled_id, docker_run_scheduled_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param docker_run_scheduled_update_request: (required) - :type docker_run_scheduled_update_request: DockerRunScheduledUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_scheduled_docker_run_state_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_scheduled_docker_run_state_by_id_with_http_info(dataset_id, worker_id, scheduled_id, docker_run_scheduled_update_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_scheduled_docker_run_state_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], worker_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker")], scheduled_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the docker worker run")], docker_run_scheduled_update_request : DockerRunScheduledUpdateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """update_scheduled_docker_run_state_by_id # noqa: E501 - - Update the state of a scheduled run. This will fail if the state of the scheduled run is LOCKED. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_scheduled_docker_run_state_by_id_with_http_info(dataset_id, worker_id, scheduled_id, docker_run_scheduled_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param worker_id: ObjectId of the docker worker (required) - :type worker_id: str - :param scheduled_id: ObjectId of the docker worker run (required) - :type scheduled_id: str - :param docker_run_scheduled_update_request: (required) - :type docker_run_scheduled_update_request: DockerRunScheduledUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'worker_id', - 'scheduled_id', - 'docker_run_scheduled_update_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_scheduled_docker_run_state_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['worker_id']: - _path_params['workerId'] = _params['worker_id'] - - if _params['scheduled_id']: - _path_params['scheduledId'] = _params['scheduled_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['docker_run_scheduled_update_request'] is not None: - _body_params = _params['docker_run_scheduled_update_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/docker/worker/{workerId}/schedule/{scheduledId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/embeddings2d_api.py b/lightly/openapi_generated/swagger_client/api/embeddings2d_api.py deleted file mode 100644 index 401055db0..000000000 --- a/lightly/openapi_generated/swagger_client/api/embeddings2d_api.py +++ /dev/null @@ -1,525 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, constr, validator - -from typing import List - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.embedding2d_create_request import Embedding2dCreateRequest -from lightly.openapi_generated.swagger_client.models.embedding2d_data import Embedding2dData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class Embeddings2dApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_embeddings2d_by_embedding_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], embedding2d_create_request : Embedding2dCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_embeddings2d_by_embedding_id # noqa: E501 - - Create a new 2d embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_embeddings2d_by_embedding_id(dataset_id, embedding_id, embedding2d_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param embedding2d_create_request: (required) - :type embedding2d_create_request: Embedding2dCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_embeddings2d_by_embedding_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_embeddings2d_by_embedding_id_with_http_info(dataset_id, embedding_id, embedding2d_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_embeddings2d_by_embedding_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], embedding2d_create_request : Embedding2dCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_embeddings2d_by_embedding_id # noqa: E501 - - Create a new 2d embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_embeddings2d_by_embedding_id_with_http_info(dataset_id, embedding_id, embedding2d_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param embedding2d_create_request: (required) - :type embedding2d_create_request: Embedding2dCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id', - 'embedding2d_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_embeddings2d_by_embedding_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['embedding2d_create_request'] is not None: - _body_params = _params['embedding2d_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/2d', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embedding2d_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], embedding2d_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the 2d embedding")], **kwargs) -> Embedding2dData: # noqa: E501 - """get_embedding2d_by_id # noqa: E501 - - Get the 2d embeddings by id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embedding2d_by_id(dataset_id, embedding_id, embedding2d_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param embedding2d_id: ObjectId of the 2d embedding (required) - :type embedding2d_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Embedding2dData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embedding2d_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embedding2d_by_id_with_http_info(dataset_id, embedding_id, embedding2d_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_embedding2d_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], embedding2d_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the 2d embedding")], **kwargs) -> ApiResponse: # noqa: E501 - """get_embedding2d_by_id # noqa: E501 - - Get the 2d embeddings by id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embedding2d_by_id_with_http_info(dataset_id, embedding_id, embedding2d_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param embedding2d_id: ObjectId of the 2d embedding (required) - :type embedding2d_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Embedding2dData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id', - 'embedding2d_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embedding2d_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - if _params['embedding2d_id']: - _path_params['embedding2dId'] = _params['embedding2d_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "Embedding2dData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/2d/{embedding2dId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embeddings2d_by_embedding_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> List[Embedding2dData]: # noqa: E501 - """get_embeddings2d_by_embedding_id # noqa: E501 - - Get all 2d embeddings of an embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings2d_by_embedding_id(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[Embedding2dData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embeddings2d_by_embedding_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embeddings2d_by_embedding_id_with_http_info(dataset_id, embedding_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_embeddings2d_by_embedding_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> ApiResponse: # noqa: E501 - """get_embeddings2d_by_embedding_id # noqa: E501 - - Get all 2d embeddings of an embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings2d_by_embedding_id_with_http_info(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[Embedding2dData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embeddings2d_by_embedding_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[Embedding2dData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/2d', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/embeddings_api.py b/lightly/openapi_generated/swagger_client/api/embeddings_api.py deleted file mode 100644 index c38036884..000000000 --- a/lightly/openapi_generated/swagger_client/api/embeddings_api.py +++ /dev/null @@ -1,1126 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictStr, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.dataset_embedding_data import DatasetEmbeddingData -from lightly.openapi_generated.swagger_client.models.embedding_data import EmbeddingData -from lightly.openapi_generated.swagger_client.models.set_embeddings_is_processed_flag_by_id_body_request import SetEmbeddingsIsProcessedFlagByIdBodyRequest -from lightly.openapi_generated.swagger_client.models.trigger2d_embedding_job_request import Trigger2dEmbeddingJobRequest -from lightly.openapi_generated.swagger_client.models.write_csv_url_data import WriteCSVUrlData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class EmbeddingsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def delete_embedding_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> None: # noqa: E501 - """delete_embedding_by_id # noqa: E501 - - Deletes a embedding entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_embedding_by_id(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_embedding_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_embedding_by_id_with_http_info(dataset_id, embedding_id, **kwargs) # noqa: E501 - - @validate_arguments - def delete_embedding_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> ApiResponse: # noqa: E501 - """delete_embedding_by_id # noqa: E501 - - Deletes a embedding entry by id. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_embedding_by_id_with_http_info(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_embedding_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embeddings_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[DatasetEmbeddingData]: # noqa: E501 - """get_embeddings_by_dataset_id # noqa: E501 - - Get all embeddings of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[DatasetEmbeddingData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embeddings_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embeddings_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_embeddings_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_embeddings_by_dataset_id # noqa: E501 - - Get all embeddings of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[DatasetEmbeddingData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embeddings_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[DatasetEmbeddingData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embeddings_by_sample_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], mode : Annotated[Optional[StrictStr], Field(description="if we want everything (full) or just the summaries")] = None, **kwargs) -> List[EmbeddingData]: # noqa: E501 - """get_embeddings_by_sample_id # noqa: E501 - - Get all embeddings of a datasets sample # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_by_sample_id(dataset_id, sample_id, mode, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param mode: if we want everything (full) or just the summaries - :type mode: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[EmbeddingData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embeddings_by_sample_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embeddings_by_sample_id_with_http_info(dataset_id, sample_id, mode, **kwargs) # noqa: E501 - - @validate_arguments - def get_embeddings_by_sample_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], mode : Annotated[Optional[StrictStr], Field(description="if we want everything (full) or just the summaries")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_embeddings_by_sample_id # noqa: E501 - - Get all embeddings of a datasets sample # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_by_sample_id_with_http_info(dataset_id, sample_id, mode, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param mode: if we want everything (full) or just the summaries - :type mode: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[EmbeddingData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'mode' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embeddings_by_sample_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('mode') is not None: # noqa: E501 - _query_params.append(( - 'mode', - _params['mode'].value if hasattr(_params['mode'], 'value') else _params['mode'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[EmbeddingData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/users/datasets/{datasetId}/samples/{sampleId}/embeddings', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embeddings_csv_read_url_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> str: # noqa: E501 - """get_embeddings_csv_read_url_by_id # noqa: E501 - - Get the url of a specific embeddings CSV # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_csv_read_url_by_id(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embeddings_csv_read_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embeddings_csv_read_url_by_id_with_http_info(dataset_id, embedding_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_embeddings_csv_read_url_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], **kwargs) -> ApiResponse: # noqa: E501 - """get_embeddings_csv_read_url_by_id # noqa: E501 - - Get the url of a specific embeddings CSV # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_csv_read_url_by_id_with_http_info(dataset_id, embedding_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embeddings_csv_read_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/readCSVUrl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_embeddings_csv_write_url_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], name : Annotated[Optional[StrictStr], Field(description="the sampling requests name to create a signed url for")] = None, **kwargs) -> WriteCSVUrlData: # noqa: E501 - """get_embeddings_csv_write_url_by_id # noqa: E501 - - Get the signed url to upload an CSVembedding to for a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_csv_write_url_by_id(dataset_id, name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param name: the sampling requests name to create a signed url for - :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: WriteCSVUrlData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_embeddings_csv_write_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_embeddings_csv_write_url_by_id_with_http_info(dataset_id, name, **kwargs) # noqa: E501 - - @validate_arguments - def get_embeddings_csv_write_url_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], name : Annotated[Optional[StrictStr], Field(description="the sampling requests name to create a signed url for")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_embeddings_csv_write_url_by_id # noqa: E501 - - Get the signed url to upload an CSVembedding to for a specific dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_embeddings_csv_write_url_by_id_with_http_info(dataset_id, name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param name: the sampling requests name to create a signed url for - :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(WriteCSVUrlData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_embeddings_csv_write_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('name') is not None: # noqa: E501 - _query_params.append(( - 'name', - _params['name'].value if hasattr(_params['name'], 'value') else _params['name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "WriteCSVUrlData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/writeCSVUrl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def set_embeddings_is_processed_flag_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], set_embeddings_is_processed_flag_by_id_body_request : SetEmbeddingsIsProcessedFlagByIdBodyRequest, **kwargs) -> None: # noqa: E501 - """set_embeddings_is_processed_flag_by_id # noqa: E501 - - Sets the isProcessed flag of the specified embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.set_embeddings_is_processed_flag_by_id(dataset_id, embedding_id, set_embeddings_is_processed_flag_by_id_body_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param set_embeddings_is_processed_flag_by_id_body_request: (required) - :type set_embeddings_is_processed_flag_by_id_body_request: SetEmbeddingsIsProcessedFlagByIdBodyRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the set_embeddings_is_processed_flag_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.set_embeddings_is_processed_flag_by_id_with_http_info(dataset_id, embedding_id, set_embeddings_is_processed_flag_by_id_body_request, **kwargs) # noqa: E501 - - @validate_arguments - def set_embeddings_is_processed_flag_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], set_embeddings_is_processed_flag_by_id_body_request : SetEmbeddingsIsProcessedFlagByIdBodyRequest, **kwargs) -> ApiResponse: # noqa: E501 - """set_embeddings_is_processed_flag_by_id # noqa: E501 - - Sets the isProcessed flag of the specified embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.set_embeddings_is_processed_flag_by_id_with_http_info(dataset_id, embedding_id, set_embeddings_is_processed_flag_by_id_body_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param set_embeddings_is_processed_flag_by_id_body_request: (required) - :type set_embeddings_is_processed_flag_by_id_body_request: SetEmbeddingsIsProcessedFlagByIdBodyRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id', - 'set_embeddings_is_processed_flag_by_id_body_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method set_embeddings_is_processed_flag_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['set_embeddings_is_processed_flag_by_id_body_request'] is not None: - _body_params = _params['set_embeddings_is_processed_flag_by_id_body_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/isProcessed', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def trigger2d_embeddings_job(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], trigger2d_embedding_job_request : Trigger2dEmbeddingJobRequest, **kwargs) -> None: # noqa: E501 - """trigger2d_embeddings_job # noqa: E501 - - Trigger job to get 2d embeddings from embeddings # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.trigger2d_embeddings_job(dataset_id, embedding_id, trigger2d_embedding_job_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param trigger2d_embedding_job_request: (required) - :type trigger2d_embedding_job_request: Trigger2dEmbeddingJobRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the trigger2d_embeddings_job_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.trigger2d_embeddings_job_with_http_info(dataset_id, embedding_id, trigger2d_embedding_job_request, **kwargs) # noqa: E501 - - @validate_arguments - def trigger2d_embeddings_job_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], trigger2d_embedding_job_request : Trigger2dEmbeddingJobRequest, **kwargs) -> ApiResponse: # noqa: E501 - """trigger2d_embeddings_job # noqa: E501 - - Trigger job to get 2d embeddings from embeddings # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.trigger2d_embeddings_job_with_http_info(dataset_id, embedding_id, trigger2d_embedding_job_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param trigger2d_embedding_job_request: (required) - :type trigger2d_embedding_job_request: Trigger2dEmbeddingJobRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id', - 'trigger2d_embedding_job_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method trigger2d_embeddings_job" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['trigger2d_embedding_job_request'] is not None: - _body_params = _params['trigger2d_embedding_job_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/trigger2dEmbeddingsJob', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/jobs_api.py b/lightly/openapi_generated/swagger_client/api/jobs_api.py deleted file mode 100644 index a42a4a599..000000000 --- a/lightly/openapi_generated/swagger_client/api/jobs_api.py +++ /dev/null @@ -1,326 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictStr - -from typing import List - -from lightly.openapi_generated.swagger_client.models.job_status_data import JobStatusData -from lightly.openapi_generated.swagger_client.models.jobs_data import JobsData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class JobsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def get_job_status_by_id(self, job_id : Annotated[StrictStr, Field(..., description="id of the job")], **kwargs) -> JobStatusData: # noqa: E501 - """get_job_status_by_id # noqa: E501 - - Get status of a specific job # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_job_status_by_id(job_id, async_req=True) - >>> result = thread.get() - - :param job_id: id of the job (required) - :type job_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: JobStatusData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_job_status_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_job_status_by_id_with_http_info(job_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_job_status_by_id_with_http_info(self, job_id : Annotated[StrictStr, Field(..., description="id of the job")], **kwargs) -> ApiResponse: # noqa: E501 - """get_job_status_by_id # noqa: E501 - - Get status of a specific job # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_job_status_by_id_with_http_info(job_id, async_req=True) - >>> result = thread.get() - - :param job_id: id of the job (required) - :type job_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(JobStatusData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'job_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_job_status_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['job_id']: - _path_params['jobId'] = _params['job_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "JobStatusData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/jobs/{jobId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_jobs(self, **kwargs) -> List[JobsData]: # noqa: E501 - """get_jobs # noqa: E501 - - Get all jobs you have created # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_jobs(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[JobsData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_jobs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_jobs_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def get_jobs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """get_jobs # noqa: E501 - - Get all jobs you have created # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_jobs_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[JobsData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_jobs" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[JobsData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/jobs', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/mappings_api.py b/lightly/openapi_generated/swagger_client/api/mappings_api.py deleted file mode 100644 index 31455414c..000000000 --- a/lightly/openapi_generated/swagger_client/api/mappings_api.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictStr, conint, constr, validator - -from typing import List, Optional - - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class MappingsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def get_sample_mappings_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], field : Annotated[StrictStr, Field(..., description="the field to return as the value")], page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[str]: # noqa: E501 - """get_sample_mappings_by_dataset_id # noqa: E501 - - Get all samples of a dataset as a list. List index is the index of the sample2bitmask mapping and the value is the 'field' you wanted (e.g _id, fileName) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_mappings_by_dataset_id(dataset_id, field, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param field: the field to return as the value (required) - :type field: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[str] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_mappings_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_mappings_by_dataset_id_with_http_info(dataset_id, field, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_mappings_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], field : Annotated[StrictStr, Field(..., description="the field to return as the value")], page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_mappings_by_dataset_id # noqa: E501 - - Get all samples of a dataset as a list. List index is the index of the sample2bitmask mapping and the value is the 'field' you wanted (e.g _id, fileName) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_mappings_by_dataset_id_with_http_info(dataset_id, field, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param field: the field to return as the value (required) - :type field: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[str], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'field', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_mappings_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - if _params.get('field') is not None: # noqa: E501 - _query_params.append(( - 'field', - _params['field'].value if hasattr(_params['field'], 'value') else _params['field'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[str]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/mappings', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/meta_data_configurations_api.py b/lightly/openapi_generated/swagger_client/api/meta_data_configurations_api.py deleted file mode 100644 index c9f1c055c..000000000 --- a/lightly/openapi_generated/swagger_client/api/meta_data_configurations_api.py +++ /dev/null @@ -1,661 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, constr, validator - -from typing import List - -from lightly.openapi_generated.swagger_client.models.configuration_data import ConfigurationData -from lightly.openapi_generated.swagger_client.models.configuration_set_request import ConfigurationSetRequest -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class MetaDataConfigurationsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_meta_data_configuration(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_set_request : ConfigurationSetRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_meta_data_configuration # noqa: E501 - - Create a new metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_meta_data_configuration(dataset_id, configuration_set_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_set_request: (required) - :type configuration_set_request: ConfigurationSetRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_meta_data_configuration_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_meta_data_configuration_with_http_info(dataset_id, configuration_set_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_meta_data_configuration_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_set_request : ConfigurationSetRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_meta_data_configuration # noqa: E501 - - Create a new metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_meta_data_configuration_with_http_info(dataset_id, configuration_set_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_set_request: (required) - :type configuration_set_request: ConfigurationSetRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'configuration_set_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_meta_data_configuration" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['configuration_set_request'] is not None: - _body_params = _params['configuration_set_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/configuration/metadata', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_meta_data_configuration_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the metadata configuration")], **kwargs) -> ConfigurationData: # noqa: E501 - """get_meta_data_configuration_by_id # noqa: E501 - - Get a specific metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_meta_data_configuration_by_id(dataset_id, configuration_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_id: ObjectId of the metadata configuration (required) - :type configuration_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ConfigurationData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_meta_data_configuration_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_meta_data_configuration_by_id_with_http_info(dataset_id, configuration_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_meta_data_configuration_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the metadata configuration")], **kwargs) -> ApiResponse: # noqa: E501 - """get_meta_data_configuration_by_id # noqa: E501 - - Get a specific metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_meta_data_configuration_by_id_with_http_info(dataset_id, configuration_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_id: ObjectId of the metadata configuration (required) - :type configuration_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ConfigurationData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'configuration_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_meta_data_configuration_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['configuration_id']: - _path_params['configurationId'] = _params['configuration_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "ConfigurationData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/configuration/metadata/{configurationId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_meta_data_configurations(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[ConfigurationData]: # noqa: E501 - """get_meta_data_configurations # noqa: E501 - - Get the all metadata configurations that exist for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_meta_data_configurations(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[ConfigurationData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_meta_data_configurations_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_meta_data_configurations_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_meta_data_configurations_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_meta_data_configurations # noqa: E501 - - Get the all metadata configurations that exist for a user # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_meta_data_configurations_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[ConfigurationData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_meta_data_configurations" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[ConfigurationData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/configuration/metadata', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_meta_data_configuration_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the metadata configuration")], configuration_set_request : ConfigurationSetRequest, **kwargs) -> None: # noqa: E501 - """update_meta_data_configuration_by_id # noqa: E501 - - update a specific metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_meta_data_configuration_by_id(dataset_id, configuration_id, configuration_set_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_id: ObjectId of the metadata configuration (required) - :type configuration_id: str - :param configuration_set_request: (required) - :type configuration_set_request: ConfigurationSetRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_meta_data_configuration_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_meta_data_configuration_by_id_with_http_info(dataset_id, configuration_id, configuration_set_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_meta_data_configuration_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], configuration_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the metadata configuration")], configuration_set_request : ConfigurationSetRequest, **kwargs) -> ApiResponse: # noqa: E501 - """update_meta_data_configuration_by_id # noqa: E501 - - update a specific metadata configuration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_meta_data_configuration_by_id_with_http_info(dataset_id, configuration_id, configuration_set_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param configuration_id: ObjectId of the metadata configuration (required) - :type configuration_id: str - :param configuration_set_request: (required) - :type configuration_set_request: ConfigurationSetRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'configuration_id', - 'configuration_set_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_meta_data_configuration_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['configuration_id']: - _path_params['configurationId'] = _params['configuration_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['configuration_set_request'] is not None: - _body_params = _params['configuration_set_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/configuration/metadata/{configurationId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/predictions_api.py b/lightly/openapi_generated/swagger_client/api/predictions_api.py deleted file mode 100644 index c188f45fc..000000000 --- a/lightly/openapi_generated/swagger_client/api/predictions_api.py +++ /dev/null @@ -1,1038 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, conint, conlist, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.prediction_singleton import PredictionSingleton -from lightly.openapi_generated.swagger_client.models.prediction_task_schema import PredictionTaskSchema -from lightly.openapi_generated.swagger_client.models.prediction_task_schemas import PredictionTaskSchemas - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class PredictionsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_or_update_prediction_by_sample_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], prediction_singleton : conlist(PredictionSingleton), prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_or_update_prediction_by_sample_id # noqa: E501 - - Create/Update all the prediction singletons per taskName for a sampleId in the order/index of them being discovered # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_prediction_by_sample_id(dataset_id, sample_id, prediction_singleton, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param prediction_singleton: (required) - :type prediction_singleton: List[PredictionSingleton] - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_or_update_prediction_by_sample_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_or_update_prediction_by_sample_id_with_http_info(dataset_id, sample_id, prediction_singleton, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def create_or_update_prediction_by_sample_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], prediction_singleton : conlist(PredictionSingleton), prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """create_or_update_prediction_by_sample_id # noqa: E501 - - Create/Update all the prediction singletons per taskName for a sampleId in the order/index of them being discovered # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_prediction_by_sample_id_with_http_info(dataset_id, sample_id, prediction_singleton, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param prediction_singleton: (required) - :type prediction_singleton: List[PredictionSingleton] - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'prediction_singleton', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_or_update_prediction_by_sample_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['prediction_singleton'] is not None: - _body_params = _params['prediction_singleton'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/samples/{sampleId}', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_or_update_prediction_task_schema_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_task_schema : PredictionTaskSchema, prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_or_update_prediction_task_schema_by_dataset_id # noqa: E501 - - Creates/updates a prediction task schema with the task name # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_prediction_task_schema_by_dataset_id(dataset_id, prediction_task_schema, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_task_schema: (required) - :type prediction_task_schema: PredictionTaskSchema - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_or_update_prediction_task_schema_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_or_update_prediction_task_schema_by_dataset_id_with_http_info(dataset_id, prediction_task_schema, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def create_or_update_prediction_task_schema_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_task_schema : PredictionTaskSchema, prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """create_or_update_prediction_task_schema_by_dataset_id # noqa: E501 - - Creates/updates a prediction task schema with the task name # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_prediction_task_schema_by_dataset_id_with_http_info(dataset_id, prediction_task_schema, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_task_schema: (required) - :type prediction_task_schema: PredictionTaskSchema - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'prediction_task_schema', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_or_update_prediction_task_schema_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['prediction_task_schema'] is not None: - _body_params = _params['prediction_task_schema'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/tasks', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_prediction_task_schema_by_task_name(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> PredictionTaskSchema: # noqa: E501 - """get_prediction_task_schema_by_task_name # noqa: E501 - - Get a prediction task schemas named taskName for a datasetId # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_task_schema_by_task_name(dataset_id, task_name, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: PredictionTaskSchema - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_prediction_task_schema_by_task_name_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_prediction_task_schema_by_task_name_with_http_info(dataset_id, task_name, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def get_prediction_task_schema_by_task_name_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_prediction_task_schema_by_task_name # noqa: E501 - - Get a prediction task schemas named taskName for a datasetId # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_task_schema_by_task_name_with_http_info(dataset_id, task_name, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(PredictionTaskSchema, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'task_name', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_prediction_task_schema_by_task_name" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['task_name']: - _path_params['taskName'] = _params['task_name'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "PredictionTaskSchema", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/tasks/{taskName}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_prediction_task_schemas_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> PredictionTaskSchemas: # noqa: E501 - """get_prediction_task_schemas_by_dataset_id # noqa: E501 - - Get list of all the prediction task schemas for a datasetId at a specific predictionUUIDTimestamp. If no predictionUUIDTimestamp is set, it defaults to the newest # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_task_schemas_by_dataset_id(dataset_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: PredictionTaskSchemas - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_prediction_task_schemas_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_prediction_task_schemas_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def get_prediction_task_schemas_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_prediction_task_schemas_by_dataset_id # noqa: E501 - - Get list of all the prediction task schemas for a datasetId at a specific predictionUUIDTimestamp. If no predictionUUIDTimestamp is set, it defaults to the newest # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_prediction_task_schemas_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(PredictionTaskSchemas, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_prediction_task_schemas_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "PredictionTaskSchemas", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/tasks', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_predictions_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, task_name : Annotated[Optional[constr(strict=True, min_length=1)], Field(description="If provided, only gets all prediction singletons of all samples of a dataset that were yielded by a specific prediction task name")] = None, **kwargs) -> List[List]: # noqa: E501 - """get_predictions_by_dataset_id # noqa: E501 - - Get all prediction singletons of all samples of a dataset ordered by the sample mapping # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_predictions_by_dataset_id(dataset_id, prediction_uuid_timestamp, task_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param task_name: If provided, only gets all prediction singletons of all samples of a dataset that were yielded by a specific prediction task name - :type task_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[List] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_predictions_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_predictions_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, task_name, **kwargs) # noqa: E501 - - @validate_arguments - def get_predictions_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, task_name : Annotated[Optional[constr(strict=True, min_length=1)], Field(description="If provided, only gets all prediction singletons of all samples of a dataset that were yielded by a specific prediction task name")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_predictions_by_dataset_id # noqa: E501 - - Get all prediction singletons of all samples of a dataset ordered by the sample mapping # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_predictions_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, task_name, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param task_name: If provided, only gets all prediction singletons of all samples of a dataset that were yielded by a specific prediction task name - :type task_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[List], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'prediction_uuid_timestamp', - 'task_name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_predictions_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - if _params.get('task_name') is not None: # noqa: E501 - _query_params.append(( - 'taskName', - _params['task_name'].value if hasattr(_params['task_name'], 'value') else _params['task_name'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[List]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/samples', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_predictions_by_sample_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> List[PredictionSingleton]: # noqa: E501 - """get_predictions_by_sample_id # noqa: E501 - - Get all prediction singletons of all tasks for a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_predictions_by_sample_id(dataset_id, sample_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[PredictionSingleton] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_predictions_by_sample_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_predictions_by_sample_id_with_http_info(dataset_id, sample_id, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def get_predictions_by_sample_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_predictions_by_sample_id # noqa: E501 - - Get all prediction singletons of all tasks for a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_predictions_by_sample_id_with_http_info(dataset_id, sample_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[PredictionSingleton], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_predictions_by_sample_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[PredictionSingleton]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/samples/{sampleId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/quota_api.py b/lightly/openapi_generated/swagger_client/api/quota_api.py deleted file mode 100644 index 2fda61dba..000000000 --- a/lightly/openapi_generated/swagger_client/api/quota_api.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class QuotaApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def get_quota_maximum_dataset_size(self, **kwargs) -> str: # noqa: E501 - """get_quota_maximum_dataset_size # noqa: E501 - - Get quota of the current user for the maximum dataset size # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_quota_maximum_dataset_size(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_quota_maximum_dataset_size_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_quota_maximum_dataset_size_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def get_quota_maximum_dataset_size_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """get_quota_maximum_dataset_size # noqa: E501 - - Get quota of the current user for the maximum dataset size # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_quota_maximum_dataset_size_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_quota_maximum_dataset_size" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/quota', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/samples_api.py b/lightly/openapi_generated/swagger_client/api/samples_api.py deleted file mode 100644 index 85be18c03..000000000 --- a/lightly/openapi_generated/swagger_client/api/samples_api.py +++ /dev/null @@ -1,1698 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictStr, conint, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.create_sample_with_write_urls_response import CreateSampleWithWriteUrlsResponse -from lightly.openapi_generated.swagger_client.models.sample_create_request import SampleCreateRequest -from lightly.openapi_generated.swagger_client.models.sample_data import SampleData -from lightly.openapi_generated.swagger_client.models.sample_data_modes import SampleDataModes -from lightly.openapi_generated.swagger_client.models.sample_partial_mode import SamplePartialMode -from lightly.openapi_generated.swagger_client.models.sample_sort_by import SampleSortBy -from lightly.openapi_generated.swagger_client.models.sample_update_request import SampleUpdateRequest -from lightly.openapi_generated.swagger_client.models.sample_write_urls import SampleWriteUrls - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class SamplesApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_sample_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_create_request : SampleCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_sample_by_dataset_id # noqa: E501 - - Create a new sample in a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_sample_by_dataset_id(dataset_id, sample_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_create_request: (required) - :type sample_create_request: SampleCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_sample_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_sample_by_dataset_id_with_http_info(dataset_id, sample_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_sample_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_create_request : SampleCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_sample_by_dataset_id # noqa: E501 - - Create a new sample in a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_sample_by_dataset_id_with_http_info(dataset_id, sample_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_create_request: (required) - :type sample_create_request: SampleCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_sample_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['sample_create_request'] is not None: - _body_params = _params['sample_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_sample_with_write_urls_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_create_request : SampleCreateRequest, **kwargs) -> CreateSampleWithWriteUrlsResponse: # noqa: E501 - """create_sample_with_write_urls_by_dataset_id # noqa: E501 - - Create a sample and immediately receive write URLs (full image and thumbnail) to upload images # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_sample_with_write_urls_by_dataset_id(dataset_id, sample_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_create_request: (required) - :type sample_create_request: SampleCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateSampleWithWriteUrlsResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_sample_with_write_urls_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_sample_with_write_urls_by_dataset_id_with_http_info(dataset_id, sample_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_sample_with_write_urls_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_create_request : SampleCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_sample_with_write_urls_by_dataset_id # noqa: E501 - - Create a sample and immediately receive write URLs (full image and thumbnail) to upload images # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_sample_with_write_urls_by_dataset_id_with_http_info(dataset_id, sample_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_create_request: (required) - :type sample_create_request: SampleCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateSampleWithWriteUrlsResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_sample_with_write_urls_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['sample_create_request'] is not None: - _body_params = _params['sample_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateSampleWithWriteUrlsResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/withWriteUrls', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_sample_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], **kwargs) -> SampleData: # noqa: E501 - """get_sample_by_id # noqa: E501 - - Get a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_by_id(dataset_id, sample_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: SampleData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_by_id_with_http_info(dataset_id, sample_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_by_id # noqa: E501 - - Get a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_by_id_with_http_info(dataset_id, sample_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(SampleData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "SampleData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_sample_image_read_url_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], type : Annotated[Optional[StrictStr], Field(description="if we want to get the full image or just the thumbnail")] = None, **kwargs) -> str: # noqa: E501 - """get_sample_image_read_url_by_id # noqa: E501 - - Get the image path of a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_read_url_by_id(dataset_id, sample_id, type, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param type: if we want to get the full image or just the thumbnail - :type type: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_image_read_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_image_read_url_by_id_with_http_info(dataset_id, sample_id, type, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_image_read_url_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], type : Annotated[Optional[StrictStr], Field(description="if we want to get the full image or just the thumbnail")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_image_read_url_by_id # noqa: E501 - - Get the image path of a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_read_url_by_id_with_http_info(dataset_id, sample_id, type, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param type: if we want to get the full image or just the thumbnail - :type type: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'type' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_image_read_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('type') is not None: # noqa: E501 - _query_params.append(( - 'type', - _params['type'].value if hasattr(_params['type'], 'value') else _params['type'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}/readurl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_sample_image_resource_redirect_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], type : Annotated[StrictStr, Field(..., description="if we want to get the full image or just the thumbnail")], **kwargs) -> None: # noqa: E501 - """get_sample_image_resource_redirect_by_id # noqa: E501 - - This endpoint enables anyone given the correct credentials to access the actual image directly. By creating a readURL for the resource and redirecting to that URL, the client can use this endpoint to always have a way to access the resource as there is no expiration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_resource_redirect_by_id(dataset_id, sample_id, type, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param type: if we want to get the full image or just the thumbnail (required) - :type type: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_image_resource_redirect_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_image_resource_redirect_by_id_with_http_info(dataset_id, sample_id, type, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_image_resource_redirect_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], type : Annotated[StrictStr, Field(..., description="if we want to get the full image or just the thumbnail")], **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_image_resource_redirect_by_id # noqa: E501 - - This endpoint enables anyone given the correct credentials to access the actual image directly. By creating a readURL for the resource and redirecting to that URL, the client can use this endpoint to always have a way to access the resource as there is no expiration # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_resource_redirect_by_id_with_http_info(dataset_id, sample_id, type, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param type: if we want to get the full image or just the thumbnail (required) - :type type: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'type' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_image_resource_redirect_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('type') is not None: # noqa: E501 - _query_params.append(( - 'type', - _params['type'].value if hasattr(_params['type'], 'value') else _params['type'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['ApiPublicJWTAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}/readurlRedirect', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_sample_image_write_url_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], is_thumbnail : Annotated[StrictBool, Field(..., description="Whether or not the image to upload is a thumbnail")], **kwargs) -> str: # noqa: E501 - """get_sample_image_write_url_by_id # noqa: E501 - - Get the signed url to upload an image to for a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_write_url_by_id(dataset_id, sample_id, is_thumbnail, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param is_thumbnail: Whether or not the image to upload is a thumbnail (required) - :type is_thumbnail: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_image_write_url_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_image_write_url_by_id_with_http_info(dataset_id, sample_id, is_thumbnail, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_image_write_url_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], is_thumbnail : Annotated[StrictBool, Field(..., description="Whether or not the image to upload is a thumbnail")], **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_image_write_url_by_id # noqa: E501 - - Get the signed url to upload an image to for a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_write_url_by_id_with_http_info(dataset_id, sample_id, is_thumbnail, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param is_thumbnail: Whether or not the image to upload is a thumbnail (required) - :type is_thumbnail: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'is_thumbnail' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_image_write_url_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('is_thumbnail') is not None: # noqa: E501 - _query_params.append(( - 'isThumbnail', - _params['is_thumbnail'].value if hasattr(_params['is_thumbnail'], 'value') else _params['is_thumbnail'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}/writeurl', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_sample_image_write_urls_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], **kwargs) -> SampleWriteUrls: # noqa: E501 - """get_sample_image_write_urls_by_id # noqa: E501 - - Get all signed write URLs to upload all images (full image and thumbnail) of a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_write_urls_by_id(dataset_id, sample_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: SampleWriteUrls - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_sample_image_write_urls_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_sample_image_write_urls_by_id_with_http_info(dataset_id, sample_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_sample_image_write_urls_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], **kwargs) -> ApiResponse: # noqa: E501 - """get_sample_image_write_urls_by_id # noqa: E501 - - Get all signed write URLs to upload all images (full image and thumbnail) of a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_sample_image_write_urls_by_id_with_http_info(dataset_id, sample_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(SampleWriteUrls, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_sample_image_write_urls_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "SampleWriteUrls", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}/writeurls', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_samples_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[Optional[StrictStr], Field(description="DEPRECATED, use without and filter yourself - Filter the samples by filename")] = None, sort_by : Annotated[Optional[SampleSortBy], Field(description="sort the samples")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[SampleData]: # noqa: E501 - """get_samples_by_dataset_id # noqa: E501 - - Get all samples of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_samples_by_dataset_id(dataset_id, file_name, sort_by, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: DEPRECATED, use without and filter yourself - Filter the samples by filename - :type file_name: str - :param sort_by: sort the samples - :type sort_by: SampleSortBy - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[SampleData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_samples_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_samples_by_dataset_id_with_http_info(dataset_id, file_name, sort_by, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_samples_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], file_name : Annotated[Optional[StrictStr], Field(description="DEPRECATED, use without and filter yourself - Filter the samples by filename")] = None, sort_by : Annotated[Optional[SampleSortBy], Field(description="sort the samples")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_samples_by_dataset_id # noqa: E501 - - Get all samples of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_samples_by_dataset_id_with_http_info(dataset_id, file_name, sort_by, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param file_name: DEPRECATED, use without and filter yourself - Filter the samples by filename - :type file_name: str - :param sort_by: sort the samples - :type sort_by: SampleSortBy - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[SampleData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'file_name', - 'sort_by', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_samples_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - if _params.get('sort_by') is not None: # noqa: E501 - _query_params.append(( - 'sortBy', - _params['sort_by'].value if hasattr(_params['sort_by'], 'value') else _params['sort_by'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[SampleData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_samples_partial_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], mode : Optional[SamplePartialMode] = None, file_name : Annotated[Optional[StrictStr], Field(description="filter the samples by filename")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[SampleDataModes]: # noqa: E501 - """get_samples_partial_by_dataset_id # noqa: E501 - - Get partial information of all samples of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_samples_partial_by_dataset_id(dataset_id, mode, file_name, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param mode: - :type mode: SamplePartialMode - :param file_name: filter the samples by filename - :type file_name: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[SampleDataModes] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_samples_partial_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_samples_partial_by_dataset_id_with_http_info(dataset_id, mode, file_name, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def get_samples_partial_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], mode : Optional[SamplePartialMode] = None, file_name : Annotated[Optional[StrictStr], Field(description="filter the samples by filename")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_samples_partial_by_dataset_id # noqa: E501 - - Get partial information of all samples of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_samples_partial_by_dataset_id_with_http_info(dataset_id, mode, file_name, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param mode: - :type mode: SamplePartialMode - :param file_name: filter the samples by filename - :type file_name: str - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[SampleDataModes], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'mode', - 'file_name', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_samples_partial_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('mode') is not None: # noqa: E501 - _query_params.append(( - 'mode', - _params['mode'].value if hasattr(_params['mode'], 'value') else _params['mode'] - )) - - if _params.get('file_name') is not None: # noqa: E501 - _query_params.append(( - 'fileName', - _params['file_name'].value if hasattr(_params['file_name'], 'value') else _params['file_name'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[SampleDataModes]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/partial', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_sample_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], sample_update_request : Annotated[SampleUpdateRequest, Field(..., description="The updated sample to set")], enable_dataset_update : Optional[StrictBool] = None, **kwargs) -> None: # noqa: E501 - """update_sample_by_id # noqa: E501 - - update a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_sample_by_id(dataset_id, sample_id, sample_update_request, enable_dataset_update, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param sample_update_request: The updated sample to set (required) - :type sample_update_request: SampleUpdateRequest - :param enable_dataset_update: - :type enable_dataset_update: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_sample_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_sample_by_id_with_http_info(dataset_id, sample_id, sample_update_request, enable_dataset_update, **kwargs) # noqa: E501 - - @validate_arguments - def update_sample_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], sample_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the sample")], sample_update_request : Annotated[SampleUpdateRequest, Field(..., description="The updated sample to set")], enable_dataset_update : Optional[StrictBool] = None, **kwargs) -> ApiResponse: # noqa: E501 - """update_sample_by_id # noqa: E501 - - update a specific sample of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_sample_by_id_with_http_info(dataset_id, sample_id, sample_update_request, enable_dataset_update, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param sample_id: ObjectId of the sample (required) - :type sample_id: str - :param sample_update_request: The updated sample to set (required) - :type sample_update_request: SampleUpdateRequest - :param enable_dataset_update: - :type enable_dataset_update: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'sample_id', - 'sample_update_request', - 'enable_dataset_update' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_sample_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['sample_id']: - _path_params['sampleId'] = _params['sample_id'] - - - # process the query parameters - _query_params = [] - if _params.get('enable_dataset_update') is not None: # noqa: E501 - _query_params.append(( - 'enableDatasetUpdate', - _params['enable_dataset_update'].value if hasattr(_params['enable_dataset_update'], 'value') else _params['enable_dataset_update'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['sample_update_request'] is not None: - _body_params = _params['sample_update_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/samples/{sampleId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/samplings_api.py b/lightly/openapi_generated/swagger_client/api/samplings_api.py deleted file mode 100644 index 41658f741..000000000 --- a/lightly/openapi_generated/swagger_client/api/samplings_api.py +++ /dev/null @@ -1,212 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, constr, validator - -from lightly.openapi_generated.swagger_client.models.async_task_data import AsyncTaskData -from lightly.openapi_generated.swagger_client.models.sampling_create_request import SamplingCreateRequest - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class SamplingsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def trigger_sampling_by_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], sampling_create_request : SamplingCreateRequest, **kwargs) -> AsyncTaskData: # noqa: E501 - """trigger_sampling_by_id # noqa: E501 - - Trigger a sampling on a specific tag of a dataset with specific prior uploaded csv embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.trigger_sampling_by_id(dataset_id, embedding_id, sampling_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param sampling_create_request: (required) - :type sampling_create_request: SamplingCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: AsyncTaskData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the trigger_sampling_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.trigger_sampling_by_id_with_http_info(dataset_id, embedding_id, sampling_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def trigger_sampling_by_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], embedding_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the embedding")], sampling_create_request : SamplingCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """trigger_sampling_by_id # noqa: E501 - - Trigger a sampling on a specific tag of a dataset with specific prior uploaded csv embedding # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.trigger_sampling_by_id_with_http_info(dataset_id, embedding_id, sampling_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param embedding_id: ObjectId of the embedding (required) - :type embedding_id: str - :param sampling_create_request: (required) - :type sampling_create_request: SamplingCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(AsyncTaskData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'embedding_id', - 'sampling_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method trigger_sampling_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['embedding_id']: - _path_params['embeddingId'] = _params['embedding_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['sampling_create_request'] is not None: - _body_params = _params['sampling_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "AsyncTaskData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/embeddings/{embeddingId}/sampling', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/scores_api.py b/lightly/openapi_generated/swagger_client/api/scores_api.py deleted file mode 100644 index fadd3efcc..000000000 --- a/lightly/openapi_generated/swagger_client/api/scores_api.py +++ /dev/null @@ -1,1019 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, conint, constr, validator - -from typing import List, Optional - -from lightly.openapi_generated.swagger_client.models.active_learning_score_create_request import ActiveLearningScoreCreateRequest -from lightly.openapi_generated.swagger_client.models.active_learning_score_data import ActiveLearningScoreData -from lightly.openapi_generated.swagger_client.models.active_learning_score_types_v2_data import ActiveLearningScoreTypesV2Data -from lightly.openapi_generated.swagger_client.models.active_learning_score_v2_data import ActiveLearningScoreV2Data -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.tag_active_learning_scores_data import TagActiveLearningScoresData - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class ScoresApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_or_update_active_learning_score_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], active_learning_score_create_request : ActiveLearningScoreCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """(Deprecated) create_or_update_active_learning_score_by_tag_id # noqa: E501 - - Create or update active learning score object by tag id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_active_learning_score_by_tag_id(dataset_id, tag_id, active_learning_score_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param active_learning_score_create_request: (required) - :type active_learning_score_create_request: ActiveLearningScoreCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_or_update_active_learning_score_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_or_update_active_learning_score_by_tag_id_with_http_info(dataset_id, tag_id, active_learning_score_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_or_update_active_learning_score_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], active_learning_score_create_request : ActiveLearningScoreCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) create_or_update_active_learning_score_by_tag_id # noqa: E501 - - Create or update active learning score object by tag id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_active_learning_score_by_tag_id_with_http_info(dataset_id, tag_id, active_learning_score_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param active_learning_score_create_request: (required) - :type active_learning_score_create_request: ActiveLearningScoreCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("POST /v1/datasets/{datasetId}/tags/{tagId}/scores is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'active_learning_score_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_or_update_active_learning_score_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['active_learning_score_create_request'] is not None: - _body_params = _params['active_learning_score_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/scores', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_or_update_active_learning_v2_score_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], active_learning_score_create_request : ActiveLearningScoreCreateRequest, prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_or_update_active_learning_v2_score_by_dataset_id # noqa: E501 - - Create or update active learning score object for a dataset, taskName, predictionUUIDTimestamp # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_active_learning_v2_score_by_dataset_id(dataset_id, task_name, active_learning_score_create_request, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param active_learning_score_create_request: (required) - :type active_learning_score_create_request: ActiveLearningScoreCreateRequest - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_or_update_active_learning_v2_score_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_or_update_active_learning_v2_score_by_dataset_id_with_http_info(dataset_id, task_name, active_learning_score_create_request, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def create_or_update_active_learning_v2_score_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], task_name : Annotated[constr(strict=True, min_length=1), Field(..., description="The prediction task name for which one wants to list the predictions")], active_learning_score_create_request : ActiveLearningScoreCreateRequest, prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """create_or_update_active_learning_v2_score_by_dataset_id # noqa: E501 - - Create or update active learning score object for a dataset, taskName, predictionUUIDTimestamp # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_or_update_active_learning_v2_score_by_dataset_id_with_http_info(dataset_id, task_name, active_learning_score_create_request, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param task_name: The prediction task name for which one wants to list the predictions (required) - :type task_name: str - :param active_learning_score_create_request: (required) - :type active_learning_score_create_request: ActiveLearningScoreCreateRequest - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'task_name', - 'active_learning_score_create_request', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_or_update_active_learning_v2_score_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('task_name') is not None: # noqa: E501 - _query_params.append(( - 'taskName', - _params['task_name'].value if hasattr(_params['task_name'], 'value') else _params['task_name'] - )) - - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['active_learning_score_create_request'] is not None: - _body_params = _params['active_learning_score_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/scores', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_active_learning_score_by_score_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], score_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the scores")], **kwargs) -> ActiveLearningScoreData: # noqa: E501 - """(Deprecated) get_active_learning_score_by_score_id # noqa: E501 - - Get active learning score object by id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_score_by_score_id(dataset_id, tag_id, score_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param score_id: ObjectId of the scores (required) - :type score_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ActiveLearningScoreData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_active_learning_score_by_score_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_active_learning_score_by_score_id_with_http_info(dataset_id, tag_id, score_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_active_learning_score_by_score_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], score_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the scores")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_active_learning_score_by_score_id # noqa: E501 - - Get active learning score object by id # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_score_by_score_id_with_http_info(dataset_id, tag_id, score_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param score_id: ObjectId of the scores (required) - :type score_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ActiveLearningScoreData, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/tags/{tagId}/scores/{scoreId} is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'score_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_active_learning_score_by_score_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - if _params['score_id']: - _path_params['scoreId'] = _params['score_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "ActiveLearningScoreData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/scores/{scoreId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_active_learning_scores_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> List[TagActiveLearningScoresData]: # noqa: E501 - """(Deprecated) get_active_learning_scores_by_tag_id # noqa: E501 - - Get all scoreIds for the given tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_scores_by_tag_id(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[TagActiveLearningScoresData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_active_learning_scores_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_active_learning_scores_by_tag_id_with_http_info(dataset_id, tag_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_active_learning_scores_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_active_learning_scores_by_tag_id # noqa: E501 - - Get all scoreIds for the given tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_scores_by_tag_id_with_http_info(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[TagActiveLearningScoresData], status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/tags/{tagId}/scores is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_active_learning_scores_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[TagActiveLearningScoresData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/scores', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_active_learning_v2_score_by_dataset_and_score_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], score_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the scores")], **kwargs) -> ActiveLearningScoreV2Data: # noqa: E501 - """get_active_learning_v2_score_by_dataset_and_score_id # noqa: E501 - - Get active learning scores by scoreId # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_v2_score_by_dataset_and_score_id(dataset_id, score_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param score_id: ObjectId of the scores (required) - :type score_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ActiveLearningScoreV2Data - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_active_learning_v2_score_by_dataset_and_score_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_active_learning_v2_score_by_dataset_and_score_id_with_http_info(dataset_id, score_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_active_learning_v2_score_by_dataset_and_score_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], score_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the scores")], **kwargs) -> ApiResponse: # noqa: E501 - """get_active_learning_v2_score_by_dataset_and_score_id # noqa: E501 - - Get active learning scores by scoreId # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_v2_score_by_dataset_and_score_id_with_http_info(dataset_id, score_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param score_id: ObjectId of the scores (required) - :type score_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ActiveLearningScoreV2Data, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'score_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_active_learning_v2_score_by_dataset_and_score_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['score_id']: - _path_params['scoreId'] = _params['score_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "ActiveLearningScoreV2Data", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/scores/{scoreId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_active_learning_v2_scores_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> List[ActiveLearningScoreTypesV2Data]: # noqa: E501 - """get_active_learning_v2_scores_by_dataset_id # noqa: E501 - - Get all AL score types by datasetId and predictionUUIDTimestamp # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_v2_scores_by_dataset_id(dataset_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[ActiveLearningScoreTypesV2Data] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_active_learning_v2_scores_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_active_learning_v2_scores_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, **kwargs) # noqa: E501 - - @validate_arguments - def get_active_learning_v2_scores_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], prediction_uuid_timestamp : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. ")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_active_learning_v2_scores_by_dataset_id # noqa: E501 - - Get all AL score types by datasetId and predictionUUIDTimestamp # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_active_learning_v2_scores_by_dataset_id_with_http_info(dataset_id, prediction_uuid_timestamp, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param prediction_uuid_timestamp: Deprecated, currently ignored. The timestamp of when the actual predictions were created. This is used as a peg to version predictions. E.g one could upload predictions on day 1 and then create new predictions with an improved model on day 30. One can then upload the new predictions to the same dataset. - :type prediction_uuid_timestamp: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[ActiveLearningScoreTypesV2Data], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'prediction_uuid_timestamp' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_active_learning_v2_scores_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - if _params.get('prediction_uuid_timestamp') is not None: # noqa: E501 - _query_params.append(( - 'predictionUUIDTimestamp', - _params['prediction_uuid_timestamp'].value if hasattr(_params['prediction_uuid_timestamp'], 'value') else _params['prediction_uuid_timestamp'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[ActiveLearningScoreTypesV2Data]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/predictions/scores', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/tags_api.py b/lightly/openapi_generated/swagger_client/api/tags_api.py deleted file mode 100644 index 428c23c98..000000000 --- a/lightly/openapi_generated/swagger_client/api/tags_api.py +++ /dev/null @@ -1,3152 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictInt, StrictStr, conint, constr, validator - -from typing import List, Optional, Union - -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.file_name_format import FileNameFormat -from lightly.openapi_generated.swagger_client.models.file_output_format import FileOutputFormat -from lightly.openapi_generated.swagger_client.models.filename_and_read_url import FilenameAndReadUrl -from lightly.openapi_generated.swagger_client.models.initial_tag_create_request import InitialTagCreateRequest -from lightly.openapi_generated.swagger_client.models.label_box_data_row import LabelBoxDataRow -from lightly.openapi_generated.swagger_client.models.label_box_v4_data_row import LabelBoxV4DataRow -from lightly.openapi_generated.swagger_client.models.label_studio_task import LabelStudioTask -from lightly.openapi_generated.swagger_client.models.sama_task import SamaTask -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_request import TagArithmeticsRequest -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_response import TagArithmeticsResponse -from lightly.openapi_generated.swagger_client.models.tag_bit_mask_response import TagBitMaskResponse -from lightly.openapi_generated.swagger_client.models.tag_create_request import TagCreateRequest -from lightly.openapi_generated.swagger_client.models.tag_data import TagData -from lightly.openapi_generated.swagger_client.models.tag_update_request import TagUpdateRequest -from lightly.openapi_generated.swagger_client.models.tag_upsize_request import TagUpsizeRequest - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class TagsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def create_initial_tag_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], initial_tag_create_request : InitialTagCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_initial_tag_by_dataset_id # noqa: E501 - - create the intitial tag for a dataset which then locks the dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_initial_tag_by_dataset_id(dataset_id, initial_tag_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param initial_tag_create_request: (required) - :type initial_tag_create_request: InitialTagCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_initial_tag_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_initial_tag_by_dataset_id_with_http_info(dataset_id, initial_tag_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_initial_tag_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], initial_tag_create_request : InitialTagCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_initial_tag_by_dataset_id # noqa: E501 - - create the intitial tag for a dataset which then locks the dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_initial_tag_by_dataset_id_with_http_info(dataset_id, initial_tag_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param initial_tag_create_request: (required) - :type initial_tag_create_request: InitialTagCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'initial_tag_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_initial_tag_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['initial_tag_create_request'] is not None: - _body_params = _params['initial_tag_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/initial', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def create_tag_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_create_request : TagCreateRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """create_tag_by_dataset_id # noqa: E501 - - create new tag for dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_tag_by_dataset_id(dataset_id, tag_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_create_request: (required) - :type tag_create_request: TagCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the create_tag_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.create_tag_by_dataset_id_with_http_info(dataset_id, tag_create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_tag_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_create_request : TagCreateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """create_tag_by_dataset_id # noqa: E501 - - create new tag for dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_tag_by_dataset_id_with_http_info(dataset_id, tag_create_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_create_request: (required) - :type tag_create_request: TagCreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_create_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_tag_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['tag_create_request'] is not None: - _body_params = _params['tag_create_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def delete_tag_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> None: # noqa: E501 - """delete_tag_by_tag_id # noqa: E501 - - delete a specific tag if its a leaf-tag (e.g is not a dependency of another tag) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_tag_by_tag_id(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_tag_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_tag_by_tag_id_with_http_info(dataset_id, tag_id, **kwargs) # noqa: E501 - - @validate_arguments - def delete_tag_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> ApiResponse: # noqa: E501 - """delete_tag_by_tag_id # noqa: E501 - - delete a specific tag if its a leaf-tag (e.g is not a dependency of another tag) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_tag_by_tag_id_with_http_info(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_tag_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def download_zip_of_samples_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> bytearray: # noqa: E501 - """(Deprecated) download_zip_of_samples_by_tag_id # noqa: E501 - - DEPRECATED - Download a zip file of the samples of a tag. Limited to 1000 images # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.download_zip_of_samples_by_tag_id(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: bytearray - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the download_zip_of_samples_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.download_zip_of_samples_by_tag_id_with_http_info(dataset_id, tag_id, **kwargs) # noqa: E501 - - @validate_arguments - def download_zip_of_samples_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) download_zip_of_samples_by_tag_id # noqa: E501 - - DEPRECATED - Download a zip file of the samples of a tag. Limited to 1000 images # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.download_zip_of_samples_by_tag_id_with_http_info(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/tags/{tagId}/export/zip is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method download_zip_of_samples_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/zip', 'application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "bytearray", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - '413': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/zip', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_basic_filenames(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> str: # noqa: E501 - """export_tag_to_basic_filenames # noqa: E501 - - Export the samples filenames of a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_basic_filenames(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_basic_filenames_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_basic_filenames_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_basic_filenames_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """export_tag_to_basic_filenames # noqa: E501 - - Export the samples filenames of a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_basic_filenames_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'expires_in', - 'access_control', - 'file_name_format', - 'include_meta_data', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_basic_filenames" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('expires_in') is not None: # noqa: E501 - _query_params.append(( - 'expiresIn', - _params['expires_in'].value if hasattr(_params['expires_in'], 'value') else _params['expires_in'] - )) - - if _params.get('access_control') is not None: # noqa: E501 - _query_params.append(( - 'accessControl', - _params['access_control'].value if hasattr(_params['access_control'], 'value') else _params['access_control'] - )) - - if _params.get('file_name_format') is not None: # noqa: E501 - _query_params.append(( - 'fileNameFormat', - _params['file_name_format'].value if hasattr(_params['file_name_format'], 'value') else _params['file_name_format'] - )) - - if _params.get('include_meta_data') is not None: # noqa: E501 - _query_params.append(( - 'includeMetaData', - _params['include_meta_data'].value if hasattr(_params['include_meta_data'], 'value') else _params['include_meta_data'] - )) - - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain', 'application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/basic/filenames', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_basic_filenames_and_read_urls(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[FilenameAndReadUrl]: # noqa: E501 - """export_tag_to_basic_filenames_and_read_urls # noqa: E501 - - Export the samples filenames to map with their readURL. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_basic_filenames_and_read_urls(dataset_id, tag_id, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[FilenameAndReadUrl] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_basic_filenames_and_read_urls_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_basic_filenames_and_read_urls_with_http_info(dataset_id, tag_id, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_basic_filenames_and_read_urls_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """export_tag_to_basic_filenames_and_read_urls # noqa: E501 - - Export the samples filenames to map with their readURL. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_basic_filenames_and_read_urls_with_http_info(dataset_id, tag_id, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[FilenameAndReadUrl], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_basic_filenames_and_read_urls" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[FilenameAndReadUrl]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/basic/filenamesAndReadUrls', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_label_box_data_rows(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[LabelBoxDataRow]: # noqa: E501 - """(Deprecated) export_tag_to_label_box_data_rows # noqa: E501 - - DEPRECATED - Please use V4 unless there is a specific need to use the LabelBox V3 API. Export samples of a tag as a json for importing into LabelBox as outlined here; https://docs.labelbox.com/v3/reference/image ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_box_data_rows(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[LabelBoxDataRow] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_label_box_data_rows_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_label_box_data_rows_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_label_box_data_rows_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) export_tag_to_label_box_data_rows # noqa: E501 - - DEPRECATED - Please use V4 unless there is a specific need to use the LabelBox V3 API. Export samples of a tag as a json for importing into LabelBox as outlined here; https://docs.labelbox.com/v3/reference/image ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_box_data_rows_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[LabelBoxDataRow], status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/tags/{tagId}/export/LabelBox/datarows is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'expires_in', - 'access_control', - 'file_name_format', - 'include_meta_data', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_label_box_data_rows" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('expires_in') is not None: # noqa: E501 - _query_params.append(( - 'expiresIn', - _params['expires_in'].value if hasattr(_params['expires_in'], 'value') else _params['expires_in'] - )) - - if _params.get('access_control') is not None: # noqa: E501 - _query_params.append(( - 'accessControl', - _params['access_control'].value if hasattr(_params['access_control'], 'value') else _params['access_control'] - )) - - if _params.get('file_name_format') is not None: # noqa: E501 - _query_params.append(( - 'fileNameFormat', - _params['file_name_format'].value if hasattr(_params['file_name_format'], 'value') else _params['file_name_format'] - )) - - if _params.get('include_meta_data') is not None: # noqa: E501 - _query_params.append(( - 'includeMetaData', - _params['include_meta_data'].value if hasattr(_params['include_meta_data'], 'value') else _params['include_meta_data'] - )) - - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[LabelBoxDataRow]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/LabelBox/datarows', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_label_box_v4_data_rows(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[LabelBoxV4DataRow]: # noqa: E501 - """export_tag_to_label_box_v4_data_rows # noqa: E501 - - Export samples of a tag as a json for importing into LabelBox as outlined here; https://docs.labelbox.com/v4/reference/image ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_box_v4_data_rows(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[LabelBoxV4DataRow] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_label_box_v4_data_rows_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_label_box_v4_data_rows_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_label_box_v4_data_rows_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """export_tag_to_label_box_v4_data_rows # noqa: E501 - - Export samples of a tag as a json for importing into LabelBox as outlined here; https://docs.labelbox.com/v4/reference/image ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_box_v4_data_rows_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[LabelBoxV4DataRow], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'expires_in', - 'access_control', - 'file_name_format', - 'include_meta_data', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_label_box_v4_data_rows" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('expires_in') is not None: # noqa: E501 - _query_params.append(( - 'expiresIn', - _params['expires_in'].value if hasattr(_params['expires_in'], 'value') else _params['expires_in'] - )) - - if _params.get('access_control') is not None: # noqa: E501 - _query_params.append(( - 'accessControl', - _params['access_control'].value if hasattr(_params['access_control'], 'value') else _params['access_control'] - )) - - if _params.get('file_name_format') is not None: # noqa: E501 - _query_params.append(( - 'fileNameFormat', - _params['file_name_format'].value if hasattr(_params['file_name_format'], 'value') else _params['file_name_format'] - )) - - if _params.get('include_meta_data') is not None: # noqa: E501 - _query_params.append(( - 'includeMetaData', - _params['include_meta_data'].value if hasattr(_params['include_meta_data'], 'value') else _params['include_meta_data'] - )) - - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[LabelBoxV4DataRow]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/LabelBoxV4/datarows', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_label_studio_tasks(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[LabelStudioTask]: # noqa: E501 - """export_tag_to_label_studio_tasks # noqa: E501 - - Export samples of a tag as a json for importing into LabelStudio as outlined here; https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_studio_tasks(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[LabelStudioTask] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_label_studio_tasks_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_label_studio_tasks_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_label_studio_tasks_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """export_tag_to_label_studio_tasks # noqa: E501 - - Export samples of a tag as a json for importing into LabelStudio as outlined here; https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_label_studio_tasks_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[LabelStudioTask], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'expires_in', - 'access_control', - 'file_name_format', - 'include_meta_data', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_label_studio_tasks" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('expires_in') is not None: # noqa: E501 - _query_params.append(( - 'expiresIn', - _params['expires_in'].value if hasattr(_params['expires_in'], 'value') else _params['expires_in'] - )) - - if _params.get('access_control') is not None: # noqa: E501 - _query_params.append(( - 'accessControl', - _params['access_control'].value if hasattr(_params['access_control'], 'value') else _params['access_control'] - )) - - if _params.get('file_name_format') is not None: # noqa: E501 - _query_params.append(( - 'fileNameFormat', - _params['file_name_format'].value if hasattr(_params['file_name_format'], 'value') else _params['file_name_format'] - )) - - if _params.get('include_meta_data') is not None: # noqa: E501 - _query_params.append(( - 'includeMetaData', - _params['include_meta_data'].value if hasattr(_params['include_meta_data'], 'value') else _params['include_meta_data'] - )) - - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[LabelStudioTask]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/LabelStudio/tasks', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def export_tag_to_sama_tasks(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> List[SamaTask]: # noqa: E501 - """export_tag_to_sama_tasks # noqa: E501 - - Export samples of a tag as a json for importing into Sama as tasks with the upload form or via the API as outlined here; - https://docs.sama.com/reference/taskcreate - https://docs.sama.com/reference/createbatch ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_sama_tasks(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[SamaTask] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the export_tag_to_sama_tasks_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.export_tag_to_sama_tasks_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, **kwargs) # noqa: E501 - - @validate_arguments - def export_tag_to_sama_tasks_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], expires_in : Annotated[Optional[StrictInt], Field(description="If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. ")] = None, access_control : Annotated[Optional[StrictStr], Field(description="which access control name to be used")] = None, file_name_format : Optional[FileNameFormat] = None, include_meta_data : Annotated[Optional[StrictBool], Field(description="if true, will also include metadata")] = None, format : Optional[FileOutputFormat] = None, preview_example : Annotated[Optional[StrictBool], Field(description="if true, will generate a preview example of how the structure will look")] = None, page_size : Annotated[Optional[conint(strict=True, ge=1)], Field(description="pagination size/limit of the number of samples to return")] = None, page_offset : Annotated[Optional[conint(strict=True, ge=0)], Field(description="pagination offset")] = None, **kwargs) -> ApiResponse: # noqa: E501 - """export_tag_to_sama_tasks # noqa: E501 - - Export samples of a tag as a json for importing into Sama as tasks with the upload form or via the API as outlined here; - https://docs.sama.com/reference/taskcreate - https://docs.sama.com/reference/createbatch ```openapi\\+warning The image URLs are special in that the resource can be accessed by anyone in possession of said URL for the time specified by the expiresIn query param ``` # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.export_tag_to_sama_tasks_with_http_info(dataset_id, tag_id, expires_in, access_control, file_name_format, include_meta_data, format, preview_example, page_size, page_offset, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param expires_in: If defined, the URLs provided will only be valid for amount of seconds from time of issuence. If not defined, the URls will be valid indefinitely. - :type expires_in: int - :param access_control: which access control name to be used - :type access_control: str - :param file_name_format: - :type file_name_format: FileNameFormat - :param include_meta_data: if true, will also include metadata - :type include_meta_data: bool - :param format: - :type format: FileOutputFormat - :param preview_example: if true, will generate a preview example of how the structure will look - :type preview_example: bool - :param page_size: pagination size/limit of the number of samples to return - :type page_size: int - :param page_offset: pagination offset - :type page_offset: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[SamaTask], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'expires_in', - 'access_control', - 'file_name_format', - 'include_meta_data', - 'format', - 'preview_example', - 'page_size', - 'page_offset' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method export_tag_to_sama_tasks" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - if _params.get('expires_in') is not None: # noqa: E501 - _query_params.append(( - 'expiresIn', - _params['expires_in'].value if hasattr(_params['expires_in'], 'value') else _params['expires_in'] - )) - - if _params.get('access_control') is not None: # noqa: E501 - _query_params.append(( - 'accessControl', - _params['access_control'].value if hasattr(_params['access_control'], 'value') else _params['access_control'] - )) - - if _params.get('file_name_format') is not None: # noqa: E501 - _query_params.append(( - 'fileNameFormat', - _params['file_name_format'].value if hasattr(_params['file_name_format'], 'value') else _params['file_name_format'] - )) - - if _params.get('include_meta_data') is not None: # noqa: E501 - _query_params.append(( - 'includeMetaData', - _params['include_meta_data'].value if hasattr(_params['include_meta_data'], 'value') else _params['include_meta_data'] - )) - - if _params.get('format') is not None: # noqa: E501 - _query_params.append(( - 'format', - _params['format'].value if hasattr(_params['format'], 'value') else _params['format'] - )) - - if _params.get('preview_example') is not None: # noqa: E501 - _query_params.append(( - 'previewExample', - _params['preview_example'].value if hasattr(_params['preview_example'], 'value') else _params['preview_example'] - )) - - if _params.get('page_size') is not None: # noqa: E501 - _query_params.append(( - 'pageSize', - _params['page_size'].value if hasattr(_params['page_size'], 'value') else _params['page_size'] - )) - - if _params.get('page_offset') is not None: # noqa: E501 - _query_params.append(( - 'pageOffset', - _params['page_offset'].value if hasattr(_params['page_offset'], 'value') else _params['page_offset'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[SamaTask]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/export/Sama/tasks', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_filenames_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> List[str]: # noqa: E501 - """(Deprecated) get_filenames_by_tag_id # noqa: E501 - - DEPRECATED, please use exportTagToBasicFilenames - Get list of filenames by tag. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_filenames_by_tag_id(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[str] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_filenames_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_filenames_by_tag_id_with_http_info(dataset_id, tag_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_filenames_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) get_filenames_by_tag_id # noqa: E501 - - DEPRECATED, please use exportTagToBasicFilenames - Get list of filenames by tag. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_filenames_by_tag_id_with_http_info(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[str], status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("GET /v1/datasets/{datasetId}/tags/{tagId}/filenames is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_filenames_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain', 'application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[str]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}/filenames', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_tag_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> TagData: # noqa: E501 - """get_tag_by_tag_id # noqa: E501 - - Get information about a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_tag_by_tag_id(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: TagData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_tag_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_tag_by_tag_id_with_http_info(dataset_id, tag_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_tag_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], **kwargs) -> ApiResponse: # noqa: E501 - """get_tag_by_tag_id # noqa: E501 - - Get information about a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_tag_by_tag_id_with_http_info(dataset_id, tag_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(TagData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_tag_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "TagData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_tags_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> List[TagData]: # noqa: E501 - """get_tags_by_dataset_id # noqa: E501 - - Get all tags of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_tags_by_dataset_id(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[TagData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_tags_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_tags_by_dataset_id_with_http_info(dataset_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_tags_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], **kwargs) -> ApiResponse: # noqa: E501 - """get_tags_by_dataset_id # noqa: E501 - - Get all tags of a dataset # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_tags_by_dataset_id_with_http_info(dataset_id, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[TagData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_tags_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[TagData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def perform_tag_arithmetics(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_arithmetics_request : TagArithmeticsRequest, **kwargs) -> TagArithmeticsResponse: # noqa: E501 - """perform_tag_arithmetics # noqa: E501 - - performs tag arithmetics to compute a new bitmask out of two existing tags and optionally create a tag for it # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.perform_tag_arithmetics(dataset_id, tag_arithmetics_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_arithmetics_request: (required) - :type tag_arithmetics_request: TagArithmeticsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: TagArithmeticsResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the perform_tag_arithmetics_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.perform_tag_arithmetics_with_http_info(dataset_id, tag_arithmetics_request, **kwargs) # noqa: E501 - - @validate_arguments - def perform_tag_arithmetics_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_arithmetics_request : TagArithmeticsRequest, **kwargs) -> ApiResponse: # noqa: E501 - """perform_tag_arithmetics # noqa: E501 - - performs tag arithmetics to compute a new bitmask out of two existing tags and optionally create a tag for it # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.perform_tag_arithmetics_with_http_info(dataset_id, tag_arithmetics_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_arithmetics_request: (required) - :type tag_arithmetics_request: TagArithmeticsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(TagArithmeticsResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_arithmetics_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method perform_tag_arithmetics" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['tag_arithmetics_request'] is not None: - _body_params = _params['tag_arithmetics_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "TagArithmeticsResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/arithmetics', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def perform_tag_arithmetics_bitmask(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_arithmetics_request : TagArithmeticsRequest, **kwargs) -> TagBitMaskResponse: # noqa: E501 - """(Deprecated) perform_tag_arithmetics_bitmask # noqa: E501 - - DEPRECATED, use performTagArithmetics - Performs tag arithmetics to compute a new bitmask out of two existing tags. Does not create a new tag regardless if newTagName is provided # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.perform_tag_arithmetics_bitmask(dataset_id, tag_arithmetics_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_arithmetics_request: (required) - :type tag_arithmetics_request: TagArithmeticsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: TagBitMaskResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the perform_tag_arithmetics_bitmask_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.perform_tag_arithmetics_bitmask_with_http_info(dataset_id, tag_arithmetics_request, **kwargs) # noqa: E501 - - @validate_arguments - def perform_tag_arithmetics_bitmask_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_arithmetics_request : TagArithmeticsRequest, **kwargs) -> ApiResponse: # noqa: E501 - """(Deprecated) perform_tag_arithmetics_bitmask # noqa: E501 - - DEPRECATED, use performTagArithmetics - Performs tag arithmetics to compute a new bitmask out of two existing tags. Does not create a new tag regardless if newTagName is provided # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.perform_tag_arithmetics_bitmask_with_http_info(dataset_id, tag_arithmetics_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_arithmetics_request: (required) - :type tag_arithmetics_request: TagArithmeticsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(TagBitMaskResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - warnings.warn("POST /v1/datasets/{datasetId}/tags/arithmetics/bitmask is deprecated.", DeprecationWarning) - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_arithmetics_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method perform_tag_arithmetics_bitmask" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['tag_arithmetics_request'] is not None: - _body_params = _params['tag_arithmetics_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "TagBitMaskResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/arithmetics/bitmask', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_tag_by_tag_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], tag_update_request : Annotated[TagUpdateRequest, Field(..., description="updated data for tag")], **kwargs) -> None: # noqa: E501 - """update_tag_by_tag_id # noqa: E501 - - update information about a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_tag_by_tag_id(dataset_id, tag_id, tag_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param tag_update_request: updated data for tag (required) - :type tag_update_request: TagUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_tag_by_tag_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_tag_by_tag_id_with_http_info(dataset_id, tag_id, tag_update_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_tag_by_tag_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the tag")], tag_update_request : Annotated[TagUpdateRequest, Field(..., description="updated data for tag")], **kwargs) -> ApiResponse: # noqa: E501 - """update_tag_by_tag_id # noqa: E501 - - update information about a specific tag # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_tag_by_tag_id_with_http_info(dataset_id, tag_id, tag_update_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_id: ObjectId of the tag (required) - :type tag_id: str - :param tag_update_request: updated data for tag (required) - :type tag_update_request: TagUpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_id', - 'tag_update_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_tag_by_tag_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - if _params['tag_id']: - _path_params['tagId'] = _params['tag_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['tag_update_request'] is not None: - _body_params = _params['tag_update_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/{tagId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def upsize_tags_by_dataset_id(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_upsize_request : TagUpsizeRequest, **kwargs) -> CreateEntityResponse: # noqa: E501 - """upsize_tags_by_dataset_id # noqa: E501 - - Upsize all tags for the dataset to the current size of the dataset. Use this after adding more samples to a dataset with an initial-tag. | Creates a new tag holding all samples which are not yet in the initial-tag. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.upsize_tags_by_dataset_id(dataset_id, tag_upsize_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_upsize_request: (required) - :type tag_upsize_request: TagUpsizeRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CreateEntityResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the upsize_tags_by_dataset_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.upsize_tags_by_dataset_id_with_http_info(dataset_id, tag_upsize_request, **kwargs) # noqa: E501 - - @validate_arguments - def upsize_tags_by_dataset_id_with_http_info(self, dataset_id : Annotated[constr(strict=True), Field(..., description="ObjectId of the dataset")], tag_upsize_request : TagUpsizeRequest, **kwargs) -> ApiResponse: # noqa: E501 - """upsize_tags_by_dataset_id # noqa: E501 - - Upsize all tags for the dataset to the current size of the dataset. Use this after adding more samples to a dataset with an initial-tag. | Creates a new tag holding all samples which are not yet in the initial-tag. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.upsize_tags_by_dataset_id_with_http_info(dataset_id, tag_upsize_request, async_req=True) - >>> result = thread.get() - - :param dataset_id: ObjectId of the dataset (required) - :type dataset_id: str - :param tag_upsize_request: (required) - :type tag_upsize_request: TagUpsizeRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CreateEntityResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'dataset_id', - 'tag_upsize_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method upsize_tags_by_dataset_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['dataset_id']: - _path_params['datasetId'] = _params['dataset_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['tag_upsize_request'] is not None: - _body_params = _params['tag_upsize_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '201': "CreateEntityResponse", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/datasets/{datasetId}/tags/upsize', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/teams_api.py b/lightly/openapi_generated/swagger_client/api/teams_api.py deleted file mode 100644 index 7eed9b158..000000000 --- a/lightly/openapi_generated/swagger_client/api/teams_api.py +++ /dev/null @@ -1,943 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import Field, StrictStr, constr, validator - -from typing import List - -from lightly.openapi_generated.swagger_client.models.create_team_membership_request import CreateTeamMembershipRequest -from lightly.openapi_generated.swagger_client.models.profile_basic_data import ProfileBasicData -from lightly.openapi_generated.swagger_client.models.service_account_basic_data import ServiceAccountBasicData -from lightly.openapi_generated.swagger_client.models.team_data import TeamData -from lightly.openapi_generated.swagger_client.models.update_team_membership_request import UpdateTeamMembershipRequest - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class TeamsApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def add_team_member(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], create_team_membership_request : CreateTeamMembershipRequest, **kwargs) -> str: # noqa: E501 - """add_team_member # noqa: E501 - - Add a team member. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.add_team_member(team_id, create_team_membership_request, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param create_team_membership_request: (required) - :type create_team_membership_request: CreateTeamMembershipRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the add_team_member_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.add_team_member_with_http_info(team_id, create_team_membership_request, **kwargs) # noqa: E501 - - @validate_arguments - def add_team_member_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], create_team_membership_request : CreateTeamMembershipRequest, **kwargs) -> ApiResponse: # noqa: E501 - """add_team_member # noqa: E501 - - Add a team member. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.add_team_member_with_http_info(team_id, create_team_membership_request, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param create_team_membership_request: (required) - :type create_team_membership_request: CreateTeamMembershipRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'team_id', - 'create_team_membership_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method add_team_member" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['create_team_membership_request'] is not None: - _body_params = _params['create_team_membership_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain', 'application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/teams/{teamId}/members', 'POST', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def delete_team_member_by_id(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], user_id : Annotated[StrictStr, Field(..., description="id of the user")], **kwargs) -> None: # noqa: E501 - """delete_team_member_by_id # noqa: E501 - - Deletes a member from a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_team_member_by_id(team_id, user_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param user_id: id of the user (required) - :type user_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the delete_team_member_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.delete_team_member_by_id_with_http_info(team_id, user_id, **kwargs) # noqa: E501 - - @validate_arguments - def delete_team_member_by_id_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], user_id : Annotated[StrictStr, Field(..., description="id of the user")], **kwargs) -> ApiResponse: # noqa: E501 - """delete_team_member_by_id # noqa: E501 - - Deletes a member from a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_team_member_by_id_with_http_info(team_id, user_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param user_id: id of the user (required) - :type user_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'team_id', - 'user_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_team_member_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - if _params['user_id']: - _path_params['userId'] = _params['user_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/teams/{teamId}/members/{userId}', 'DELETE', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_service_accounts_by_team_id(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> List[ServiceAccountBasicData]: # noqa: E501 - """get_service_accounts_by_team_id # noqa: E501 - - Get the service accounts of a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_service_accounts_by_team_id(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[ServiceAccountBasicData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_service_accounts_by_team_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_service_accounts_by_team_id_with_http_info(team_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_service_accounts_by_team_id_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> ApiResponse: # noqa: E501 - """get_service_accounts_by_team_id # noqa: E501 - - Get the service accounts of a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_service_accounts_by_team_id_with_http_info(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[ServiceAccountBasicData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'team_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_service_accounts_by_team_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[ServiceAccountBasicData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/teams/{teamId}/serviceaccounts', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_team_by_id(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> TeamData: # noqa: E501 - """get_team_by_id # noqa: E501 - - Get basic team information by ID. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_team_by_id(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: TeamData - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_team_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_team_by_id_with_http_info(team_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_team_by_id_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> ApiResponse: # noqa: E501 - """get_team_by_id # noqa: E501 - - Get basic team information by ID. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_team_by_id_with_http_info(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(TeamData, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'team_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_team_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "TeamData", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/teams/{teamId}', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_team_members_by_id(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> List[ProfileBasicData]: # noqa: E501 - """get_team_members_by_id # noqa: E501 - - Get the members of a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_team_members_by_id(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[ProfileBasicData] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_team_members_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_team_members_by_id_with_http_info(team_id, **kwargs) # noqa: E501 - - @validate_arguments - def get_team_members_by_id_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], **kwargs) -> ApiResponse: # noqa: E501 - """get_team_members_by_id # noqa: E501 - - Get the members of a team. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_team_members_by_id_with_http_info(team_id, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[ProfileBasicData], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'team_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_team_members_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = { - '200': "List[ProfileBasicData]", - '400': "ApiErrorResponse", - '401': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/teams/{teamId}/members', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def update_team_member_by_id(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], user_id : Annotated[StrictStr, Field(..., description="id of the user")], update_team_membership_request : UpdateTeamMembershipRequest, **kwargs) -> None: # noqa: E501 - """update_team_member_by_id # noqa: E501 - - Update the team membership of a user. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_team_member_by_id(team_id, user_id, update_team_membership_request, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param user_id: id of the user (required) - :type user_id: str - :param update_team_membership_request: (required) - :type update_team_membership_request: UpdateTeamMembershipRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the update_team_member_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.update_team_member_by_id_with_http_info(team_id, user_id, update_team_membership_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_team_member_by_id_with_http_info(self, team_id : Annotated[constr(strict=True), Field(..., description="id of the team")], user_id : Annotated[StrictStr, Field(..., description="id of the user")], update_team_membership_request : UpdateTeamMembershipRequest, **kwargs) -> ApiResponse: # noqa: E501 - """update_team_member_by_id # noqa: E501 - - Update the team membership of a user. One needs to be part of the team to do so. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_team_member_by_id_with_http_info(team_id, user_id, update_team_membership_request, async_req=True) - >>> result = thread.get() - - :param team_id: id of the team (required) - :type team_id: str - :param user_id: id of the user (required) - :type user_id: str - :param update_team_membership_request: (required) - :type update_team_membership_request: UpdateTeamMembershipRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'team_id', - 'user_id', - 'update_team_membership_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_team_member_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params['team_id']: - _path_params['teamId'] = _params['team_id'] - - if _params['user_id']: - _path_params['userId'] = _params['user_id'] - - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params['update_team_membership_request'] is not None: - _body_params = _params['update_team_membership_request'] - - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings = ['auth0Bearer', 'ApiKeyAuth'] # noqa: E501 - - _response_types_map = {} - - return self.api_client.call_api( - '/v1/teams/{teamId}/members/{userId}', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api/versioning_api.py b/lightly/openapi_generated/swagger_client/api/versioning_api.py deleted file mode 100644 index 908d0d8f3..000000000 --- a/lightly/openapi_generated/swagger_client/api/versioning_api.py +++ /dev/null @@ -1,325 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated - -from pydantic import StrictStr - -from typing import Optional - - -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -from lightly.openapi_generated.swagger_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class VersioningApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - @validate_arguments - def get_latest_pip_version(self, current_version : Optional[StrictStr] = None, **kwargs) -> str: # noqa: E501 - """get_latest_pip_version # noqa: E501 - - Get latest pip version available # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_latest_pip_version(current_version, async_req=True) - >>> result = thread.get() - - :param current_version: - :type current_version: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_latest_pip_version_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_latest_pip_version_with_http_info(current_version, **kwargs) # noqa: E501 - - @validate_arguments - def get_latest_pip_version_with_http_info(self, current_version : Optional[StrictStr] = None, **kwargs) -> ApiResponse: # noqa: E501 - """get_latest_pip_version # noqa: E501 - - Get latest pip version available # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_latest_pip_version_with_http_info(current_version, async_req=True) - >>> result = thread.get() - - :param current_version: - :type current_version: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'current_version' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_latest_pip_version" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get('current_version') is not None: # noqa: E501 - _query_params.append(( - 'currentVersion', - _params['current_version'].value if hasattr(_params['current_version'], 'value') else _params['current_version'] - )) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = [] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/versions/pip/latest', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_minimum_compatible_pip_version(self, **kwargs) -> str: # noqa: E501 - """get_minimum_compatible_pip_version # noqa: E501 - - Get minimum pip version needed for compatability # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_minimum_compatible_pip_version(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_minimum_compatible_pip_version_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") - return self.get_minimum_compatible_pip_version_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def get_minimum_compatible_pip_version_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """get_minimum_compatible_pip_version # noqa: E501 - - Get minimum pip version needed for compatability # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_minimum_compatible_pip_version_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_minimum_compatible_pip_version" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = [] # noqa: E501 - - _response_types_map = { - '200': "str", - '400': "ApiErrorResponse", - '403': "ApiErrorResponse", - '404': "ApiErrorResponse", - } - - return self.api_client.call_api( - '/v1/versions/pip/minimum', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) diff --git a/lightly/openapi_generated/swagger_client/api_client.py b/lightly/openapi_generated/swagger_client/api_client.py deleted file mode 100644 index 74cb202e6..000000000 --- a/lightly/openapi_generated/swagger_client/api_client.py +++ /dev/null @@ -1,756 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import atexit -import datetime -from dateutil.parser import parse -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -from urllib.parse import quote - -from lightly.openapi_generated.swagger_client.configuration import Configuration -from lightly.openapi_generated.swagger_client.api_response import ApiResponse -import lightly.openapi_generated.swagger_client.models -from lightly.openapi_generated.swagger_client import rest -from lightly.openapi_generated.swagger_client.exceptions import ApiValueError, ApiException - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - PRIMITIVE_TYPES = (float, bool, bytes, str, int) - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int, # TODO remove as only py3 is supported? - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - _pool = None - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): - # use default configuration if none is provided - if configuration is None: - configuration = Configuration.get_default() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.0/python' - self.client_side_validation = configuration.client_side_validation - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - - _default = None - - @classmethod - def get_default(cls): - """Return new instance of ApiClient. - - This method returns newly created, based on default constructor, - object of ApiClient class or returns a copy of default - ApiClient. - - :return: The ApiClient object. - """ - if cls._default is None: - cls._default = ApiClient() - return cls._default - - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. - - It stores default ApiClient. - - :param default: object of ApiClient. - """ - cls._default = default - - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - post_params.extend(self.files_parameters(files)) - - # auth setting - self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) - url += "?" + url_query - - try: - # perform request and return response - response_data = self.request( - method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') - raise e - - self.last_response = response_data - - return_data = None # assuming derialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = obj.to_dict(by_alias=True) - - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in data.items()} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(lightly.openapi_generated.swagger_client.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_types_map, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host, - _request_auth) - - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, _request_auth)) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def parameters_to_url_query(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: URL query string (e.g. a=Hello%20World&b=123) - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) - if isinstance(v, bool): - v = str(v).lower() - if isinstance(v, dict): - v = json.dumps(v) - - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) - else: - new_params.append((k, quote(str(v)))) - - return "&".join(["=".join(item) for item in new_params]) - - def files_parameters(self, files=None): - """Builds form parameters. - - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if files: - for k, v in files.items(): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - for accept in accepts: - if re.search('json', accept, re.IGNORECASE): - return accept - - return accepts[0] - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return None - - for content_type in content_types: - if re.search('json', content_type, re.IGNORECASE): - return content_type - - return content_types[0] - - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param request_auth: if set, the provided settings will - override the token in the configuration. - """ - if not auth_settings: - return - - if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): - """Updates the request parameters based on a single auth_setting - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param auth_setting: auth settings for the endpoint - """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return an original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datetime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) - ) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - return klass.from_dict(data) diff --git a/lightly/openapi_generated/swagger_client/api_response.py b/lightly/openapi_generated/swagger_client/api_response.py deleted file mode 100644 index d81c2ff58..000000000 --- a/lightly/openapi_generated/swagger_client/api_response.py +++ /dev/null @@ -1,25 +0,0 @@ -"""API response object.""" - -from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr - -class ApiResponse: - """ - API response object - """ - - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") - - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None): - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data diff --git a/lightly/openapi_generated/swagger_client/configuration.py b/lightly/openapi_generated/swagger_client/configuration.py deleted file mode 100644 index 5f6e4b662..000000000 --- a/lightly/openapi_generated/swagger_client/configuration.py +++ /dev/null @@ -1,520 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import http.client as httplib -from lightly.openapi_generated.swagger_client.exceptions import ApiValueError - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' -} - -class Configuration(object): - """This class contains various settings of the API client. - - :param host: Base url. - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer). - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication. - :param password: Password for HTTP basic authentication. - :param access_token: Access token. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format. - - :Example: - - API Key Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - cookieAuth: # name for the security scheme - type: apiKey - in: cookie - name: JSESSIONID # cookie name - - You can programmatically set the cookie: - -conf = lightly.openapi_generated.swagger_client.Configuration( - api_key={'cookieAuth': 'abc123'} - api_key_prefix={'cookieAuth': 'JSESSIONID'} -) - - The following cookie will be added to the HTTP request: - Cookie: JSESSIONID abc123 - """ - - _default = None - - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - access_token=None, - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, - ): - """Constructor - """ - self._base_path = "https://api.lightly.ai" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.access_token = access_token - """Access token - """ - self.access_token = None - """access token for OAuth/Bearer - """ - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("lightly.openapi_generated.swagger_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = ssl_ca_cert - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - self.tls_server_name = None - """SSL/TLS Server Name Indication (SNI) - Set this to the SNI value expected by the server. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - self.socket_options = None - """Options to pass down to the underlying urllib3 socket - """ - - self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" - """datetime format - """ - - self.date_format = "%Y-%m-%d" - """date format - """ - - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler', 'logger_stream_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name, value): - object.__setattr__(self, name, value) - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = default - - @classmethod - def get_default_copy(cls): - """Deprecated. Please use `get_default` instead. - - Deprecated. Please use `get_default` instead. - - :return: The configuration object. - """ - return cls.get_default() - - @classmethod - def get_default(cls): - """Return the default configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration. - - :return: The configuration object. - """ - if cls._default is None: - cls._default = Configuration() - return cls._default - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} - if self.access_token is not None: - auth['auth0Bearer'] = { - 'type': 'bearer', - 'in': 'header', - 'format': 'JWT', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - if 'ApiPublicJWTAuth' in self.api_key: - auth['ApiPublicJWTAuth'] = { - 'type': 'api_key', - 'in': 'query', - 'key': 'publicToken', - 'value': self.get_api_key_with_prefix( - 'ApiPublicJWTAuth', - ), - } - if 'ApiKeyAuth' in self.api_key: - auth['ApiKeyAuth'] = { - 'type': 'api_key', - 'in': 'query', - 'key': 'token', - 'value': self.get_api_key_with_prefix( - 'ApiKeyAuth', - ), - } - if 'InternalKeyAuth' in self.api_key: - auth['InternalKeyAuth'] = { - 'type': 'api_key', - 'in': 'query', - 'key': 'secret', - 'value': self.get_api_key_with_prefix( - 'InternalKeyAuth', - ), - } - return auth - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0\n"\ - "SDK Package Version: 1.0.0".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - 'url': "https://api.lightly.ai", - 'description': "No description provided", - }, - { - 'url': "https://api-staging.lightly.ai", - 'description': "No description provided", - }, - { - 'url': "https://api-dev.lightly.ai", - 'description': "No description provided", - }, - { - 'url': "https://api.dev.lightly.ai", - 'description': "No description provided", - }, - { - 'url': "http://localhost:5000", - 'description': "No description provided", - } - ] - - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path - - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) - - url = server['url'] - - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) - - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) - - url = url.replace("{" + variable_name + "}", used_value) - - return url - - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None diff --git a/lightly/openapi_generated/swagger_client/exceptions.py b/lightly/openapi_generated/swagger_client/exceptions.py deleted file mode 100644 index 8e0933dd9..000000000 --- a/lightly/openapi_generated/swagger_client/exceptions.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" - - -class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None): - """ Raises an exception for TypeErrors - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) - - -class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ - - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) - - -class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None): - """ - Raised when an attribute reference or assignment fails. - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiAttributeError, self).__init__(full_msg) - - -class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) - - -class ApiException(OpenApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message - - -class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ServiceException, self).__init__(status, reason, http_resp) - - -def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, int): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result diff --git a/lightly/openapi_generated/swagger_client/models/__init__.py b/lightly/openapi_generated/swagger_client/models/__init__.py deleted file mode 100644 index fd3becb3c..000000000 --- a/lightly/openapi_generated/swagger_client/models/__init__.py +++ /dev/null @@ -1,268 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -# import models into model package -from lightly.openapi_generated.swagger_client.models.active_learning_score_create_request import ActiveLearningScoreCreateRequest -from lightly.openapi_generated.swagger_client.models.active_learning_score_data import ActiveLearningScoreData -from lightly.openapi_generated.swagger_client.models.active_learning_score_types_v2_data import ActiveLearningScoreTypesV2Data -from lightly.openapi_generated.swagger_client.models.active_learning_score_v2_data import ActiveLearningScoreV2Data -from lightly.openapi_generated.swagger_client.models.api_error_code import ApiErrorCode -from lightly.openapi_generated.swagger_client.models.api_error_response import ApiErrorResponse -from lightly.openapi_generated.swagger_client.models.async_task_data import AsyncTaskData -from lightly.openapi_generated.swagger_client.models.configuration_data import ConfigurationData -from lightly.openapi_generated.swagger_client.models.configuration_entry import ConfigurationEntry -from lightly.openapi_generated.swagger_client.models.configuration_set_request import ConfigurationSetRequest -from lightly.openapi_generated.swagger_client.models.configuration_value_data_type import ConfigurationValueDataType -from lightly.openapi_generated.swagger_client.models.create_cf_bucket_activity_request import CreateCFBucketActivityRequest -from lightly.openapi_generated.swagger_client.models.create_docker_worker_registry_entry_request import CreateDockerWorkerRegistryEntryRequest -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.create_sample_with_write_urls_response import CreateSampleWithWriteUrlsResponse -from lightly.openapi_generated.swagger_client.models.create_team_membership_request import CreateTeamMembershipRequest -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.crop_data import CropData -from lightly.openapi_generated.swagger_client.models.dataset_create_request import DatasetCreateRequest -from lightly.openapi_generated.swagger_client.models.dataset_creator import DatasetCreator -from lightly.openapi_generated.swagger_client.models.dataset_data import DatasetData -from lightly.openapi_generated.swagger_client.models.dataset_data_enriched import DatasetDataEnriched -from lightly.openapi_generated.swagger_client.models.dataset_embedding_data import DatasetEmbeddingData -from lightly.openapi_generated.swagger_client.models.dataset_type import DatasetType -from lightly.openapi_generated.swagger_client.models.dataset_update_request import DatasetUpdateRequest -from lightly.openapi_generated.swagger_client.models.datasource_config import DatasourceConfig -from lightly.openapi_generated.swagger_client.models.datasource_config_azure import DatasourceConfigAzure -from lightly.openapi_generated.swagger_client.models.datasource_config_azure_all_of import DatasourceConfigAzureAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase -from lightly.openapi_generated.swagger_client.models.datasource_config_base_full_path import DatasourceConfigBaseFullPath -from lightly.openapi_generated.swagger_client.models.datasource_config_gcs import DatasourceConfigGCS -from lightly.openapi_generated.swagger_client.models.datasource_config_gcs_all_of import DatasourceConfigGCSAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_lightly import DatasourceConfigLIGHTLY -from lightly.openapi_generated.swagger_client.models.datasource_config_local import DatasourceConfigLOCAL -from lightly.openapi_generated.swagger_client.models.datasource_config_local_all_of import DatasourceConfigLOCALAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_obs import DatasourceConfigOBS -from lightly.openapi_generated.swagger_client.models.datasource_config_obs_all_of import DatasourceConfigOBSAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_s3 import DatasourceConfigS3 -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_all_of import DatasourceConfigS3AllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_delegated_access import DatasourceConfigS3DelegatedAccess -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_delegated_access_all_of import DatasourceConfigS3DelegatedAccessAllOf -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data import DatasourceConfigVerifyData -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data_errors import DatasourceConfigVerifyDataErrors -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_request import DatasourceProcessedUntilTimestampRequest -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_response import DatasourceProcessedUntilTimestampResponse -from lightly.openapi_generated.swagger_client.models.datasource_purpose import DatasourcePurpose -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data import DatasourceRawSamplesData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data_row import DatasourceRawSamplesDataRow -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data import DatasourceRawSamplesMetadataData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data_row import DatasourceRawSamplesMetadataDataRow -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data import DatasourceRawSamplesPredictionsData -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data_row import DatasourceRawSamplesPredictionsDataRow -from lightly.openapi_generated.swagger_client.models.delegated_access_external_ids_inner import DelegatedAccessExternalIdsInner -from lightly.openapi_generated.swagger_client.models.dimensionality_reduction_method import DimensionalityReductionMethod -from lightly.openapi_generated.swagger_client.models.docker_license_information import DockerLicenseInformation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_create_request import DockerRunArtifactCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_created_data import DockerRunArtifactCreatedData -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_data import DockerRunArtifactData -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_storage_location import DockerRunArtifactStorageLocation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_type import DockerRunArtifactType -from lightly.openapi_generated.swagger_client.models.docker_run_create_request import DockerRunCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_data import DockerRunData -from lightly.openapi_generated.swagger_client.models.docker_run_log_create_entry_data import DockerRunLogCreateEntryData -from lightly.openapi_generated.swagger_client.models.docker_run_log_data import DockerRunLogData -from lightly.openapi_generated.swagger_client.models.docker_run_log_docker_load import DockerRunLogDockerLoad -from lightly.openapi_generated.swagger_client.models.docker_run_log_entry_data import DockerRunLogEntryData -from lightly.openapi_generated.swagger_client.models.docker_run_log_entry_data_base import DockerRunLogEntryDataBase -from lightly.openapi_generated.swagger_client.models.docker_run_log_level import DockerRunLogLevel -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_create_request import DockerRunScheduledCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_data import DockerRunScheduledData -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_priority import DockerRunScheduledPriority -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_state import DockerRunScheduledState -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_update_request import DockerRunScheduledUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState -from lightly.openapi_generated.swagger_client.models.docker_run_update_request import DockerRunUpdateRequest -from lightly.openapi_generated.swagger_client.models.docker_task_description import DockerTaskDescription -from lightly.openapi_generated.swagger_client.models.docker_user_stats import DockerUserStats -from lightly.openapi_generated.swagger_client.models.docker_worker_config import DockerWorkerConfig -from lightly.openapi_generated.swagger_client.models.docker_worker_config_create_request import DockerWorkerConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v2_create_request import DockerWorkerConfigOmniV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v2_create_request_all_of import DockerWorkerConfigOmniV2CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v3_create_request import DockerWorkerConfigOmniV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v3_create_request_all_of import DockerWorkerConfigOmniV3CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v4_create_request import DockerWorkerConfigOmniV4CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v4_create_request_all_of import DockerWorkerConfigOmniV4CreateRequestAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request import DockerWorkerConfigOmniVXCreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request_base import DockerWorkerConfigOmniVXCreateRequestBase -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data import DockerWorkerConfigV0Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data_all_of import DockerWorkerConfigV0DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_create_request import DockerWorkerConfigV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data import DockerWorkerConfigV2Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data_all_of import DockerWorkerConfigV2DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker import DockerWorkerConfigV2Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_datasource import DockerWorkerConfigV2DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_object_level import DockerWorkerConfigV2DockerObjectLevel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_stopping_condition import DockerWorkerConfigV2DockerStoppingCondition -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly import DockerWorkerConfigV2Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_collate import DockerWorkerConfigV2LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_model import DockerWorkerConfigV2LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_trainer import DockerWorkerConfigV2LightlyTrainer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_create_request import DockerWorkerConfigV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data import DockerWorkerConfigV3Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data_all_of import DockerWorkerConfigV3DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_datasource_input_expiration import DockerWorkerConfigV3DatasourceInputExpiration -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker import DockerWorkerConfigV3Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_corruptness_check import DockerWorkerConfigV3DockerCorruptnessCheck -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_datasource import DockerWorkerConfigV3DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_training import DockerWorkerConfigV3DockerTraining -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly import DockerWorkerConfigV3Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_checkpoint_callback import DockerWorkerConfigV3LightlyCheckpointCallback -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_collate import DockerWorkerConfigV3LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_criterion import DockerWorkerConfigV3LightlyCriterion -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_loader import DockerWorkerConfigV3LightlyLoader -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_model import DockerWorkerConfigV3LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_optimizer import DockerWorkerConfigV3LightlyOptimizer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_trainer import DockerWorkerConfigV3LightlyTrainer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_data import DockerWorkerConfigV4Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_data_all_of import DockerWorkerConfigV4DataAllOf -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_docker import DockerWorkerConfigV4Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data import DockerWorkerConfigVXData -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase -from lightly.openapi_generated.swagger_client.models.docker_worker_registry_entry_data import DockerWorkerRegistryEntryData -from lightly.openapi_generated.swagger_client.models.docker_worker_state import DockerWorkerState -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.embedding2d_create_request import Embedding2dCreateRequest -from lightly.openapi_generated.swagger_client.models.embedding2d_data import Embedding2dData -from lightly.openapi_generated.swagger_client.models.embedding_data import EmbeddingData -from lightly.openapi_generated.swagger_client.models.expiry_handling_strategy_v3 import ExpiryHandlingStrategyV3 -from lightly.openapi_generated.swagger_client.models.file_name_format import FileNameFormat -from lightly.openapi_generated.swagger_client.models.file_output_format import FileOutputFormat -from lightly.openapi_generated.swagger_client.models.filename_and_read_url import FilenameAndReadUrl -from lightly.openapi_generated.swagger_client.models.image_type import ImageType -from lightly.openapi_generated.swagger_client.models.initial_tag_create_request import InitialTagCreateRequest -from lightly.openapi_generated.swagger_client.models.job_result_type import JobResultType -from lightly.openapi_generated.swagger_client.models.job_state import JobState -from lightly.openapi_generated.swagger_client.models.job_status_data import JobStatusData -from lightly.openapi_generated.swagger_client.models.job_status_data_result import JobStatusDataResult -from lightly.openapi_generated.swagger_client.models.job_status_meta import JobStatusMeta -from lightly.openapi_generated.swagger_client.models.job_status_upload_method import JobStatusUploadMethod -from lightly.openapi_generated.swagger_client.models.jobs_data import JobsData -from lightly.openapi_generated.swagger_client.models.label_box_data_row import LabelBoxDataRow -from lightly.openapi_generated.swagger_client.models.label_box_v4_data_row import LabelBoxV4DataRow -from lightly.openapi_generated.swagger_client.models.label_studio_task import LabelStudioTask -from lightly.openapi_generated.swagger_client.models.label_studio_task_data import LabelStudioTaskData -from lightly.openapi_generated.swagger_client.models.lightly_docker_selection_method import LightlyDockerSelectionMethod -from lightly.openapi_generated.swagger_client.models.lightly_model_v2 import LightlyModelV2 -from lightly.openapi_generated.swagger_client.models.lightly_model_v3 import LightlyModelV3 -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v2 import LightlyTrainerPrecisionV2 -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v3 import LightlyTrainerPrecisionV3 -from lightly.openapi_generated.swagger_client.models.prediction_singleton import PredictionSingleton -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase -from lightly.openapi_generated.swagger_client.models.prediction_singleton_classification import PredictionSingletonClassification -from lightly.openapi_generated.swagger_client.models.prediction_singleton_classification_all_of import PredictionSingletonClassificationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_instance_segmentation import PredictionSingletonInstanceSegmentation -from lightly.openapi_generated.swagger_client.models.prediction_singleton_instance_segmentation_all_of import PredictionSingletonInstanceSegmentationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_keypoint_detection import PredictionSingletonKeypointDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_keypoint_detection_all_of import PredictionSingletonKeypointDetectionAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_object_detection import PredictionSingletonObjectDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_object_detection_all_of import PredictionSingletonObjectDetectionAllOf -from lightly.openapi_generated.swagger_client.models.prediction_singleton_semantic_segmentation import PredictionSingletonSemanticSegmentation -from lightly.openapi_generated.swagger_client.models.prediction_singleton_semantic_segmentation_all_of import PredictionSingletonSemanticSegmentationAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema import PredictionTaskSchema -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_base import PredictionTaskSchemaBase -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category import PredictionTaskSchemaCategory -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints import PredictionTaskSchemaCategoryKeypoints -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints_all_of import PredictionTaskSchemaCategoryKeypointsAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_keypoint import PredictionTaskSchemaKeypoint -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_keypoint_all_of import PredictionTaskSchemaKeypointAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_simple import PredictionTaskSchemaSimple -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_simple_all_of import PredictionTaskSchemaSimpleAllOf -from lightly.openapi_generated.swagger_client.models.prediction_task_schemas import PredictionTaskSchemas -from lightly.openapi_generated.swagger_client.models.questionnaire_data import QuestionnaireData -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region -from lightly.openapi_generated.swagger_client.models.sama_task import SamaTask -from lightly.openapi_generated.swagger_client.models.sama_task_data import SamaTaskData -from lightly.openapi_generated.swagger_client.models.sample_create_request import SampleCreateRequest -from lightly.openapi_generated.swagger_client.models.sample_data import SampleData -from lightly.openapi_generated.swagger_client.models.sample_data_modes import SampleDataModes -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData -from lightly.openapi_generated.swagger_client.models.sample_partial_mode import SamplePartialMode -from lightly.openapi_generated.swagger_client.models.sample_sort_by import SampleSortBy -from lightly.openapi_generated.swagger_client.models.sample_type import SampleType -from lightly.openapi_generated.swagger_client.models.sample_update_request import SampleUpdateRequest -from lightly.openapi_generated.swagger_client.models.sample_write_urls import SampleWriteUrls -from lightly.openapi_generated.swagger_client.models.sampling_config import SamplingConfig -from lightly.openapi_generated.swagger_client.models.sampling_config_stopping_condition import SamplingConfigStoppingCondition -from lightly.openapi_generated.swagger_client.models.sampling_create_request import SamplingCreateRequest -from lightly.openapi_generated.swagger_client.models.sampling_method import SamplingMethod -from lightly.openapi_generated.swagger_client.models.sector import Sector -from lightly.openapi_generated.swagger_client.models.selection_config import SelectionConfig -from lightly.openapi_generated.swagger_client.models.selection_config_all_of import SelectionConfigAllOf -from lightly.openapi_generated.swagger_client.models.selection_config_base import SelectionConfigBase -from lightly.openapi_generated.swagger_client.models.selection_config_entry import SelectionConfigEntry -from lightly.openapi_generated.swagger_client.models.selection_config_entry_input import SelectionConfigEntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_entry_strategy import SelectionConfigEntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_config_v3 import SelectionConfigV3 -from lightly.openapi_generated.swagger_client.models.selection_config_v3_all_of import SelectionConfigV3AllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry import SelectionConfigV3Entry -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_input import SelectionConfigV3EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy import SelectionConfigV3EntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of import SelectionConfigV3EntryStrategyAllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of_target_range import SelectionConfigV3EntryStrategyAllOfTargetRange -from lightly.openapi_generated.swagger_client.models.selection_config_v4 import SelectionConfigV4 -from lightly.openapi_generated.swagger_client.models.selection_config_v4_all_of import SelectionConfigV4AllOf -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry import SelectionConfigV4Entry -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_input import SelectionConfigV4EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_strategy import SelectionConfigV4EntryStrategy -from lightly.openapi_generated.swagger_client.models.selection_input_predictions_name import SelectionInputPredictionsName -from lightly.openapi_generated.swagger_client.models.selection_input_type import SelectionInputType -from lightly.openapi_generated.swagger_client.models.selection_strategy_threshold_operation import SelectionStrategyThresholdOperation -from lightly.openapi_generated.swagger_client.models.selection_strategy_type import SelectionStrategyType -from lightly.openapi_generated.swagger_client.models.selection_strategy_type_v3 import SelectionStrategyTypeV3 -from lightly.openapi_generated.swagger_client.models.service_account_basic_data import ServiceAccountBasicData -from lightly.openapi_generated.swagger_client.models.set_embeddings_is_processed_flag_by_id_body_request import SetEmbeddingsIsProcessedFlagByIdBodyRequest -from lightly.openapi_generated.swagger_client.models.shared_access_config_create_request import SharedAccessConfigCreateRequest -from lightly.openapi_generated.swagger_client.models.shared_access_config_data import SharedAccessConfigData -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType -from lightly.openapi_generated.swagger_client.models.tag_active_learning_scores_data import TagActiveLearningScoresData -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_operation import TagArithmeticsOperation -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_request import TagArithmeticsRequest -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_response import TagArithmeticsResponse -from lightly.openapi_generated.swagger_client.models.tag_bit_mask_response import TagBitMaskResponse -from lightly.openapi_generated.swagger_client.models.tag_change_data import TagChangeData -from lightly.openapi_generated.swagger_client.models.tag_change_data_arithmetics import TagChangeDataArithmetics -from lightly.openapi_generated.swagger_client.models.tag_change_data_initial import TagChangeDataInitial -from lightly.openapi_generated.swagger_client.models.tag_change_data_metadata import TagChangeDataMetadata -from lightly.openapi_generated.swagger_client.models.tag_change_data_operation_method import TagChangeDataOperationMethod -from lightly.openapi_generated.swagger_client.models.tag_change_data_rename import TagChangeDataRename -from lightly.openapi_generated.swagger_client.models.tag_change_data_sampler import TagChangeDataSampler -from lightly.openapi_generated.swagger_client.models.tag_change_data_samples import TagChangeDataSamples -from lightly.openapi_generated.swagger_client.models.tag_change_data_scatterplot import TagChangeDataScatterplot -from lightly.openapi_generated.swagger_client.models.tag_change_data_upsize import TagChangeDataUpsize -from lightly.openapi_generated.swagger_client.models.tag_change_entry import TagChangeEntry -from lightly.openapi_generated.swagger_client.models.tag_create_request import TagCreateRequest -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator -from lightly.openapi_generated.swagger_client.models.tag_data import TagData -from lightly.openapi_generated.swagger_client.models.tag_update_request import TagUpdateRequest -from lightly.openapi_generated.swagger_client.models.tag_upsize_request import TagUpsizeRequest -from lightly.openapi_generated.swagger_client.models.task_type import TaskType -from lightly.openapi_generated.swagger_client.models.team_basic_data import TeamBasicData -from lightly.openapi_generated.swagger_client.models.team_data import TeamData -from lightly.openapi_generated.swagger_client.models.team_role import TeamRole -from lightly.openapi_generated.swagger_client.models.trigger2d_embedding_job_request import Trigger2dEmbeddingJobRequest -from lightly.openapi_generated.swagger_client.models.update_docker_worker_registry_entry_request import UpdateDockerWorkerRegistryEntryRequest -from lightly.openapi_generated.swagger_client.models.update_team_membership_request import UpdateTeamMembershipRequest -from lightly.openapi_generated.swagger_client.models.user_type import UserType -from lightly.openapi_generated.swagger_client.models.video_frame_data import VideoFrameData -from lightly.openapi_generated.swagger_client.models.write_csv_url_data import WriteCSVUrlData diff --git a/lightly/openapi_generated/swagger_client/models/active_learning_score_create_request.py b/lightly/openapi_generated/swagger_client/models/active_learning_score_create_request.py deleted file mode 100644 index 639cc1601..000000000 --- a/lightly/openapi_generated/swagger_client/models/active_learning_score_create_request.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, conlist, constr, validator - -class ActiveLearningScoreCreateRequest(BaseModel): - """ - ActiveLearningScoreCreateRequest - """ - score_type: constr(strict=True, min_length=1) = Field(..., alias="scoreType", description="Type of active learning score") - scores: conlist(Union[StrictFloat, StrictInt], min_items=1) = Field(..., description="Array of active learning scores") - __properties = ["scoreType", "scores"] - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ActiveLearningScoreCreateRequest: - """Create an instance of ActiveLearningScoreCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ActiveLearningScoreCreateRequest: - """Create an instance of ActiveLearningScoreCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ActiveLearningScoreCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ActiveLearningScoreCreateRequest) in the input: " + str(obj)) - - _obj = ActiveLearningScoreCreateRequest.parse_obj({ - "score_type": obj.get("scoreType"), - "scores": obj.get("scores") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/active_learning_score_data.py b/lightly/openapi_generated/swagger_client/models/active_learning_score_data.py deleted file mode 100644 index 843dd8eeb..000000000 --- a/lightly/openapi_generated/swagger_client/models/active_learning_score_data.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, conint, conlist, constr, validator - -class ActiveLearningScoreData(BaseModel): - """ - ActiveLearningScoreData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - tag_id: constr(strict=True) = Field(..., alias="tagId", description="MongoDB ObjectId") - score_type: constr(strict=True, min_length=1) = Field(..., alias="scoreType", description="Type of active learning score") - scores: conlist(Union[StrictFloat, StrictInt], min_items=1) = Field(..., description="Array of active learning scores") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "tagId", "scoreType", "scores", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_id') - def tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ActiveLearningScoreData: - """Create an instance of ActiveLearningScoreData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ActiveLearningScoreData: - """Create an instance of ActiveLearningScoreData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ActiveLearningScoreData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ActiveLearningScoreData) in the input: " + str(obj)) - - _obj = ActiveLearningScoreData.parse_obj({ - "id": obj.get("id"), - "tag_id": obj.get("tagId"), - "score_type": obj.get("scoreType"), - "scores": obj.get("scores"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/active_learning_score_types_v2_data.py b/lightly/openapi_generated/swagger_client/models/active_learning_score_types_v2_data.py deleted file mode 100644 index 5455a44d3..000000000 --- a/lightly/openapi_generated/swagger_client/models/active_learning_score_types_v2_data.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint, constr, validator - -class ActiveLearningScoreTypesV2Data(BaseModel): - """ - ActiveLearningScoreTypesV2Data - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: constr(strict=True) = Field(..., alias="datasetId", description="MongoDB ObjectId") - prediction_uuid_timestamp: conint(strict=True, ge=0) = Field(..., alias="predictionUUIDTimestamp", description="unix timestamp in milliseconds") - task_name: constr(strict=True, min_length=1) = Field(..., alias="taskName", description="A name which is safe to have as a file/folder name in a file system") - score_type: constr(strict=True, min_length=1) = Field(..., alias="scoreType", description="Type of active learning score") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "datasetId", "predictionUUIDTimestamp", "taskName", "scoreType", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('task_name') - def task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$/") - return value - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ActiveLearningScoreTypesV2Data: - """Create an instance of ActiveLearningScoreTypesV2Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ActiveLearningScoreTypesV2Data: - """Create an instance of ActiveLearningScoreTypesV2Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ActiveLearningScoreTypesV2Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ActiveLearningScoreTypesV2Data) in the input: " + str(obj)) - - _obj = ActiveLearningScoreTypesV2Data.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "prediction_uuid_timestamp": obj.get("predictionUUIDTimestamp"), - "task_name": obj.get("taskName"), - "score_type": obj.get("scoreType"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/active_learning_score_v2_data.py b/lightly/openapi_generated/swagger_client/models/active_learning_score_v2_data.py deleted file mode 100644 index 1970b7c58..000000000 --- a/lightly/openapi_generated/swagger_client/models/active_learning_score_v2_data.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, conint, conlist, constr, validator - -class ActiveLearningScoreV2Data(BaseModel): - """ - ActiveLearningScoreV2Data - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: constr(strict=True) = Field(..., alias="datasetId", description="MongoDB ObjectId") - prediction_uuid_timestamp: conint(strict=True, ge=0) = Field(..., alias="predictionUUIDTimestamp", description="unix timestamp in milliseconds") - task_name: constr(strict=True, min_length=1) = Field(..., alias="taskName", description="A name which is safe to have as a file/folder name in a file system") - score_type: constr(strict=True, min_length=1) = Field(..., alias="scoreType", description="Type of active learning score") - scores: conlist(Union[StrictFloat, StrictInt], min_items=1) = Field(..., description="Array of active learning scores") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "datasetId", "predictionUUIDTimestamp", "taskName", "scoreType", "scores", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('task_name') - def task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$/") - return value - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ActiveLearningScoreV2Data: - """Create an instance of ActiveLearningScoreV2Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ActiveLearningScoreV2Data: - """Create an instance of ActiveLearningScoreV2Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ActiveLearningScoreV2Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ActiveLearningScoreV2Data) in the input: " + str(obj)) - - _obj = ActiveLearningScoreV2Data.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "prediction_uuid_timestamp": obj.get("predictionUUIDTimestamp"), - "task_name": obj.get("taskName"), - "score_type": obj.get("scoreType"), - "scores": obj.get("scores"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/api_error_code.py b/lightly/openapi_generated/swagger_client/models/api_error_code.py deleted file mode 100644 index 6e2b5dd56..000000000 --- a/lightly/openapi_generated/swagger_client/models/api_error_code.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class ApiErrorCode(str, Enum): - """ - ApiErrorCode - """ - - """ - allowed enum values - """ - BAD_REQUEST = 'BAD_REQUEST' - NOT_IMPLEMENTED = 'NOT_IMPLEMENTED' - FORBIDDEN = 'FORBIDDEN' - UNAUTHORIZED = 'UNAUTHORIZED' - NOT_FOUND = 'NOT_FOUND' - NOT_MODIFIED = 'NOT_MODIFIED' - CONFLICT = 'CONFLICT' - MALFORMED_REQUEST = 'MALFORMED_REQUEST' - MALFORMED_RESPONSE = 'MALFORMED_RESPONSE' - PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE' - JWT_INVALID = 'JWT_INVALID' - JWT_MALFORMED = 'JWT_MALFORMED' - CREATION_FAILED = 'CREATION_FAILED' - JOB_CREATION_FAILED = 'JOB_CREATION_FAILED' - JOB_UNKNOWN = 'JOB_UNKNOWN' - USER_NOT_KNOWN = 'USER_NOT_KNOWN' - USER_ACCOUNT_DEACTIVATED = 'USER_ACCOUNT_DEACTIVATED' - USER_ACCOUNT_BLOCKED = 'USER_ACCOUNT_BLOCKED' - TEAM_ACCOUNT_PLAN_INSUFFICIENT = 'TEAM_ACCOUNT_PLAN_INSUFFICIENT' - ILLEGAL_ACTION_RESOURCE_IN_USE = 'ILLEGAL_ACTION_RESOURCE_IN_USE' - DATASET_UNKNOWN = 'DATASET_UNKNOWN' - DATASET_NOT_SUPPORTED = 'DATASET_NOT_SUPPORTED' - DATASET_TAG_INVALID = 'DATASET_TAG_INVALID' - DATASET_NAME_EXISTS = 'DATASET_NAME_EXISTS' - DATASET_AT_MAX_CAPACITY = 'DATASET_AT_MAX_CAPACITY' - DATASET_DATASOURCE_UNKNOWN = 'DATASET_DATASOURCE_UNKNOWN' - DATASET_DATASOURCE_CREDENTIALS_ERROR = 'DATASET_DATASOURCE_CREDENTIALS_ERROR' - DATASET_DATASOURCE_INVALID = 'DATASET_DATASOURCE_INVALID' - DATASET_DATASOURCE_ACTION_NOT_IMPLEMENTED = 'DATASET_DATASOURCE_ACTION_NOT_IMPLEMENTED' - DATASET_DATASOURCE_ILLEGAL_ACTION = 'DATASET_DATASOURCE_ILLEGAL_ACTION' - DATASET_DATASOURCE_FILE_TOO_LARGE = 'DATASET_DATASOURCE_FILE_TOO_LARGE' - DATASET_DATASOURCE_RELEVANT_FILENAMES_INVALID = 'DATASET_DATASOURCE_RELEVANT_FILENAMES_INVALID' - ACCESS_CONTROL_UNKNOWN = 'ACCESS_CONTROL_UNKNOWN' - EMBEDDING_UNKNOWN = 'EMBEDDING_UNKNOWN' - EMBEDDING_NAME_EXISTS = 'EMBEDDING_NAME_EXISTS' - EMBEDDING_INVALID = 'EMBEDDING_INVALID' - EMBEDDING_NOT_READY = 'EMBEDDING_NOT_READY' - EMBEDDING_ROW_COUNT_UNKNOWN = 'EMBEDDING_ROW_COUNT_UNKNOWN' - EMBEDDING_ROW_COUNT_INVALID = 'EMBEDDING_ROW_COUNT_INVALID' - EMBEDDING_2_D_UNKNOWN = 'EMBEDDING_2D_UNKNOWN' - TAG_UNKNOWN = 'TAG_UNKNOWN' - TAG_NAME_EXISTS = 'TAG_NAME_EXISTS' - TAG_INITIAL_EXISTS = 'TAG_INITIAL_EXISTS' - TAG_UNDELETABLE_NOT_A_LEAF = 'TAG_UNDELETABLE_NOT_A_LEAF' - TAG_UNDELETABLE_IS_INITIAL = 'TAG_UNDELETABLE_IS_INITIAL' - TAG_NO_TAG_IN_DATASET = 'TAG_NO_TAG_IN_DATASET' - TAG_PREVTAG_NOT_IN_DATASET = 'TAG_PREVTAG_NOT_IN_DATASET' - TAG_QUERYTAG_NOT_IN_DATASET = 'TAG_QUERYTAG_NOT_IN_DATASET' - TAG_PRESELECTEDTAG_NOT_IN_DATASET = 'TAG_PRESELECTEDTAG_NOT_IN_DATASET' - TAG_NO_SCORES_AVAILABLE = 'TAG_NO_SCORES_AVAILABLE' - SAMPLE_UNKNOWN = 'SAMPLE_UNKNOWN' - SAMPLE_THUMBNAME_UNKNOWN = 'SAMPLE_THUMBNAME_UNKNOWN' - SAMPLE_CREATE_REQUEST_INVALID_FORMAT = 'SAMPLE_CREATE_REQUEST_INVALID_FORMAT' - SAMPLE_CREATE_REQUEST_INVALID_CROP_DATA = 'SAMPLE_CREATE_REQUEST_INVALID_CROP_DATA' - PREDICTION_TASK_SCHEMA_UNKNOWN = 'PREDICTION_TASK_SCHEMA_UNKNOWN' - PREDICTION_TASK_SCHEMA_CATEGORIES_NOT_UNIQUE = 'PREDICTION_TASK_SCHEMA_CATEGORIES_NOT_UNIQUE' - SCORE_UNKNOWN = 'SCORE_UNKNOWN' - SCORES_CANNOT_BE_SET = 'SCORES_CANNOT_BE_SET' - DOCKER_RUN_UNKNOWN = 'DOCKER_RUN_UNKNOWN' - DOCKER_RUN_DATASET_UNAVAILABLE = 'DOCKER_RUN_DATASET_UNAVAILABLE' - DOCKER_RUN_REPORT_UNAVAILABLE = 'DOCKER_RUN_REPORT_UNAVAILABLE' - DOCKER_RUN_ARTIFACT_UNKNOWN = 'DOCKER_RUN_ARTIFACT_UNKNOWN' - DOCKER_RUN_ARTIFACT_EXISTS = 'DOCKER_RUN_ARTIFACT_EXISTS' - DOCKER_RUN_ARTIFACT_UNAVAILABLE = 'DOCKER_RUN_ARTIFACT_UNAVAILABLE' - DOCKER_WORKER_UNKNOWN = 'DOCKER_WORKER_UNKNOWN' - DOCKER_WORKER_CONFIG_UNKNOWN = 'DOCKER_WORKER_CONFIG_UNKNOWN' - DOCKER_WORKER_CONFIG_NOT_COMPATIBLE_WITH_DATASOURCE = 'DOCKER_WORKER_CONFIG_NOT_COMPATIBLE_WITH_DATASOURCE' - DOCKER_WORKER_CONFIG_REFERENCES_INVALID_FILES = 'DOCKER_WORKER_CONFIG_REFERENCES_INVALID_FILES' - DOCKER_WORKER_CONFIG_IN_USE = 'DOCKER_WORKER_CONFIG_IN_USE' - DOCKER_WORKER_CONFIG_INVALID = 'DOCKER_WORKER_CONFIG_INVALID' - DOCKER_WORKER_SCHEDULE_UNKNOWN = 'DOCKER_WORKER_SCHEDULE_UNKNOWN' - DOCKER_WORKER_SCHEDULE_UPDATE_FAILED = 'DOCKER_WORKER_SCHEDULE_UPDATE_FAILED' - METADATA_CONFIGURATION_UNKNOWN = 'METADATA_CONFIGURATION_UNKNOWN' - CUSTOM_METADATA_AT_MAX_SIZE = 'CUSTOM_METADATA_AT_MAX_SIZE' - ONPREM_SUBSCRIPTION_INSUFFICIENT = 'ONPREM_SUBSCRIPTION_INSUFFICIENT' - ACCOUNT_SUBSCRIPTION_INSUFFICIENT = 'ACCOUNT_SUBSCRIPTION_INSUFFICIENT' - TEAM_UNKNOWN = 'TEAM_UNKNOWN' - - @classmethod - def from_json(cls, json_str: str) -> 'ApiErrorCode': - """Create an instance of ApiErrorCode from a JSON string""" - return ApiErrorCode(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/api_error_response.py b/lightly/openapi_generated/swagger_client/models/api_error_response.py deleted file mode 100644 index d845e2814..000000000 --- a/lightly/openapi_generated/swagger_client/models/api_error_response.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.api_error_code import ApiErrorCode - -class ApiErrorResponse(BaseModel): - """ - ApiErrorResponse - """ - code: ApiErrorCode = Field(...) - error: StrictStr = Field(..., description="The detailed error message or code of the error") - request_id: Optional[StrictStr] = Field(None, alias="requestId", description="The identifier of a request. Helpful for debugging") - error_labels: Optional[conlist(StrictStr)] = Field(None, alias="errorLabels", description="Can occur on database errors") - __properties = ["code", "error", "requestId", "errorLabels"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ApiErrorResponse: - """Create an instance of ApiErrorResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ApiErrorResponse: - """Create an instance of ApiErrorResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ApiErrorResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ApiErrorResponse) in the input: " + str(obj)) - - _obj = ApiErrorResponse.parse_obj({ - "code": obj.get("code"), - "error": obj.get("error"), - "request_id": obj.get("requestId"), - "error_labels": obj.get("errorLabels") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/async_task_data.py b/lightly/openapi_generated/swagger_client/models/async_task_data.py deleted file mode 100644 index 8ee4799a0..000000000 --- a/lightly/openapi_generated/swagger_client/models/async_task_data.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class AsyncTaskData(BaseModel): - """ - AsyncTaskData - """ - job_id: StrictStr = Field(..., alias="jobId") - __properties = ["jobId"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> AsyncTaskData: - """Create an instance of AsyncTaskData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> AsyncTaskData: - """Create an instance of AsyncTaskData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return AsyncTaskData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in AsyncTaskData) in the input: " + str(obj)) - - _obj = AsyncTaskData.parse_obj({ - "job_id": obj.get("jobId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request.py b/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request.py deleted file mode 100644 index cc652c35e..000000000 --- a/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.auth0_on_sign_up_request_user import Auth0OnSignUpRequestUser - -class Auth0OnSignUpRequest(BaseModel): - """ - Auth0OnSignUpRequest - """ - user: Auth0OnSignUpRequestUser = Field(...) - __properties = ["user"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Auth0OnSignUpRequest: - """Create an instance of Auth0OnSignUpRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of user - if self.user: - _dict['user' if by_alias else 'user'] = self.user.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Auth0OnSignUpRequest: - """Create an instance of Auth0OnSignUpRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Auth0OnSignUpRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Auth0OnSignUpRequest) in the input: " + str(obj)) - - _obj = Auth0OnSignUpRequest.parse_obj({ - "user": Auth0OnSignUpRequestUser.from_dict(obj.get("user")) if obj.get("user") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request_user.py b/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request_user.py deleted file mode 100644 index d375b9dee..000000000 --- a/lightly/openapi_generated/swagger_client/models/auth0_on_sign_up_request_user.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr - -class Auth0OnSignUpRequestUser(BaseModel): - """ - Auth0OnSignUpRequestUser - """ - user_id: StrictStr = Field(..., alias="userId") - email: Optional[StrictStr] = None - locale: Optional[StrictStr] = None - nickname: Optional[StrictStr] = None - name: Optional[StrictStr] = None - given_name: Optional[StrictStr] = Field(None, alias="givenName") - family_name: Optional[StrictStr] = Field(None, alias="familyName") - __properties = ["userId", "email", "locale", "nickname", "name", "givenName", "familyName"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Auth0OnSignUpRequestUser: - """Create an instance of Auth0OnSignUpRequestUser from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Auth0OnSignUpRequestUser: - """Create an instance of Auth0OnSignUpRequestUser from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Auth0OnSignUpRequestUser.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Auth0OnSignUpRequestUser) in the input: " + str(obj)) - - _obj = Auth0OnSignUpRequestUser.parse_obj({ - "user_id": obj.get("userId"), - "email": obj.get("email"), - "locale": obj.get("locale"), - "nickname": obj.get("nickname"), - "name": obj.get("name"), - "given_name": obj.get("givenName"), - "family_name": obj.get("familyName") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/configuration_data.py b/lightly/openapi_generated/swagger_client/models/configuration_data.py deleted file mode 100644 index 76ea89bd3..000000000 --- a/lightly/openapi_generated/swagger_client/models/configuration_data.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.configuration_entry import ConfigurationEntry - -class ConfigurationData(BaseModel): - """ - ConfigurationData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: StrictStr = Field(...) - configs: conlist(ConfigurationEntry) = Field(...) - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - __properties = ["id", "name", "configs", "createdAt", "lastModifiedAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ConfigurationData: - """Create an instance of ConfigurationData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in configs (list) - _items = [] - if self.configs: - for _item in self.configs: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['configs' if by_alias else 'configs'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ConfigurationData: - """Create an instance of ConfigurationData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ConfigurationData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ConfigurationData) in the input: " + str(obj)) - - _obj = ConfigurationData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "configs": [ConfigurationEntry.from_dict(_item) for _item in obj.get("configs")] if obj.get("configs") is not None else None, - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/configuration_entry.py b/lightly/openapi_generated/swagger_client/models/configuration_entry.py deleted file mode 100644 index da3a64795..000000000 --- a/lightly/openapi_generated/swagger_client/models/configuration_entry.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Optional -from pydantic import Extra, BaseModel, Field, constr -from lightly.openapi_generated.swagger_client.models.configuration_value_data_type import ConfigurationValueDataType - -class ConfigurationEntry(BaseModel): - """ - ConfigurationEntry - """ - name: constr(strict=True, min_length=1) = Field(..., description="the name of this entry which is displayed in the UI") - path: constr(strict=True, min_length=1) = Field(..., description="the path is the dotnotation which is used to easily access the customMetadata JSON structure of a sample e.g myArray[0].myObject.field") - default_value: Optional[Any] = Field(..., alias="defaultValue", description="the default value used if its not possible to extract the value using the path or if the value extracted is nullish") - value_data_type: ConfigurationValueDataType = Field(..., alias="valueDataType") - __properties = ["name", "path", "defaultValue", "valueDataType"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ConfigurationEntry: - """Create an instance of ConfigurationEntry from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # set to None if default_value (nullable) is None - # and __fields_set__ contains the field - if self.default_value is None and "default_value" in self.__fields_set__: - _dict['defaultValue' if by_alias else 'default_value'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ConfigurationEntry: - """Create an instance of ConfigurationEntry from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ConfigurationEntry.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ConfigurationEntry) in the input: " + str(obj)) - - _obj = ConfigurationEntry.parse_obj({ - "name": obj.get("name"), - "path": obj.get("path"), - "default_value": obj.get("defaultValue"), - "value_data_type": obj.get("valueDataType") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/configuration_set_request.py b/lightly/openapi_generated/swagger_client/models/configuration_set_request.py deleted file mode 100644 index 07650c154..000000000 --- a/lightly/openapi_generated/swagger_client/models/configuration_set_request.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.configuration_entry import ConfigurationEntry - -class ConfigurationSetRequest(BaseModel): - """ - ConfigurationSetRequest - """ - name: StrictStr = Field(...) - configs: conlist(ConfigurationEntry) = Field(...) - __properties = ["name", "configs"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ConfigurationSetRequest: - """Create an instance of ConfigurationSetRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in configs (list) - _items = [] - if self.configs: - for _item in self.configs: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['configs' if by_alias else 'configs'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ConfigurationSetRequest: - """Create an instance of ConfigurationSetRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ConfigurationSetRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ConfigurationSetRequest) in the input: " + str(obj)) - - _obj = ConfigurationSetRequest.parse_obj({ - "name": obj.get("name"), - "configs": [ConfigurationEntry.from_dict(_item) for _item in obj.get("configs")] if obj.get("configs") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/configuration_value_data_type.py b/lightly/openapi_generated/swagger_client/models/configuration_value_data_type.py deleted file mode 100644 index 8f7b4a991..000000000 --- a/lightly/openapi_generated/swagger_client/models/configuration_value_data_type.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class ConfigurationValueDataType(str, Enum): - """ - We support different data types for the extracted value. This tells Lightly how to interpret the value and also allows you to do different things. - Numeric means the extracted values are in a range and have a lower and upper bound. E.g used for color ranges - Categorical means the extracted values are distinct and can be grouped. This allows us to e.g plot distributions of each unique value within your dataset and to map each unique value to a color - string: most often used for class/category e.g for city, animal or weather condition - int: e.g for ratings of a meal - boolean: for true/false distinctions as e.g isVerified or flashOn - datetime: e.g for grouping by time - timestamp: e.g for grouping by time - Other means that the extracted value is important to you but does not fit another category. It is displayed alongside other information in the sample detail. E.g the license - """ - - """ - allowed enum values - """ - NUMERIC_INT = 'NUMERIC_INT' - NUMERIC_FLOAT = 'NUMERIC_FLOAT' - CATEGORICAL_STRING = 'CATEGORICAL_STRING' - CATEGORICAL_INT = 'CATEGORICAL_INT' - CATEGORICAL_BOOLEAN = 'CATEGORICAL_BOOLEAN' - CATEGORICAL_DATETIME = 'CATEGORICAL_DATETIME' - CATEGORICAL_TIMESTAMP = 'CATEGORICAL_TIMESTAMP' - OTHER_STRING = 'OTHER_STRING' - - @classmethod - def from_json(cls, json_str: str) -> 'ConfigurationValueDataType': - """Create an instance of ConfigurationValueDataType from a JSON string""" - return ConfigurationValueDataType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/create_cf_bucket_activity_request.py b/lightly/openapi_generated/swagger_client/models/create_cf_bucket_activity_request.py deleted file mode 100644 index e397cf8d8..000000000 --- a/lightly/openapi_generated/swagger_client/models/create_cf_bucket_activity_request.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class CreateCFBucketActivityRequest(BaseModel): - """ - CreateCFBucketActivityRequest - """ - name: StrictStr = Field(...) - bucket: StrictStr = Field(...) - __properties = ["name", "bucket"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CreateCFBucketActivityRequest: - """Create an instance of CreateCFBucketActivityRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateCFBucketActivityRequest: - """Create an instance of CreateCFBucketActivityRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateCFBucketActivityRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CreateCFBucketActivityRequest) in the input: " + str(obj)) - - _obj = CreateCFBucketActivityRequest.parse_obj({ - "name": obj.get("name"), - "bucket": obj.get("bucket") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/create_docker_worker_registry_entry_request.py b/lightly/openapi_generated/swagger_client/models/create_docker_worker_registry_entry_request.py deleted file mode 100644 index f383b057b..000000000 --- a/lightly/openapi_generated/swagger_client/models/create_docker_worker_registry_entry_request.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType - -class CreateDockerWorkerRegistryEntryRequest(BaseModel): - """ - CreateDockerWorkerRegistryEntryRequest - """ - name: constr(strict=True, min_length=3) = Field(...) - worker_type: DockerWorkerType = Field(..., alias="workerType") - labels: Optional[conlist(StrictStr)] = Field(None, description="The labels used for specifying the run-worker-relationship") - creator: Optional[Creator] = None - docker_version: Optional[StrictStr] = Field(None, alias="dockerVersion") - __properties = ["name", "workerType", "labels", "creator", "dockerVersion"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CreateDockerWorkerRegistryEntryRequest: - """Create an instance of CreateDockerWorkerRegistryEntryRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateDockerWorkerRegistryEntryRequest: - """Create an instance of CreateDockerWorkerRegistryEntryRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateDockerWorkerRegistryEntryRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CreateDockerWorkerRegistryEntryRequest) in the input: " + str(obj)) - - _obj = CreateDockerWorkerRegistryEntryRequest.parse_obj({ - "name": obj.get("name"), - "worker_type": obj.get("workerType"), - "labels": obj.get("labels"), - "creator": obj.get("creator"), - "docker_version": obj.get("dockerVersion") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/create_entity_response.py b/lightly/openapi_generated/swagger_client/models/create_entity_response.py deleted file mode 100644 index d8d4a3da8..000000000 --- a/lightly/openapi_generated/swagger_client/models/create_entity_response.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr, validator - -class CreateEntityResponse(BaseModel): - """ - CreateEntityResponse - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - __properties = ["id"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CreateEntityResponse: - """Create an instance of CreateEntityResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateEntityResponse: - """Create an instance of CreateEntityResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateEntityResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CreateEntityResponse) in the input: " + str(obj)) - - _obj = CreateEntityResponse.parse_obj({ - "id": obj.get("id") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/create_sample_with_write_urls_response.py b/lightly/openapi_generated/swagger_client/models/create_sample_with_write_urls_response.py deleted file mode 100644 index 049d39819..000000000 --- a/lightly/openapi_generated/swagger_client/models/create_sample_with_write_urls_response.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.sample_write_urls import SampleWriteUrls - -class CreateSampleWithWriteUrlsResponse(BaseModel): - """ - CreateSampleWithWriteUrlsResponse - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - sample_write_urls: SampleWriteUrls = Field(..., alias="sampleWriteUrls") - __properties = ["id", "sampleWriteUrls"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CreateSampleWithWriteUrlsResponse: - """Create an instance of CreateSampleWithWriteUrlsResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sample_write_urls - if self.sample_write_urls: - _dict['sampleWriteUrls' if by_alias else 'sample_write_urls'] = self.sample_write_urls.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateSampleWithWriteUrlsResponse: - """Create an instance of CreateSampleWithWriteUrlsResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateSampleWithWriteUrlsResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CreateSampleWithWriteUrlsResponse) in the input: " + str(obj)) - - _obj = CreateSampleWithWriteUrlsResponse.parse_obj({ - "id": obj.get("id"), - "sample_write_urls": SampleWriteUrls.from_dict(obj.get("sampleWriteUrls")) if obj.get("sampleWriteUrls") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/create_team_membership_request.py b/lightly/openapi_generated/swagger_client/models/create_team_membership_request.py deleted file mode 100644 index 034cbb707..000000000 --- a/lightly/openapi_generated/swagger_client/models/create_team_membership_request.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.team_role import TeamRole - -class CreateTeamMembershipRequest(BaseModel): - """ - CreateTeamMembershipRequest - """ - email: StrictStr = Field(..., description="email of the user") - role: TeamRole = Field(...) - __properties = ["email", "role"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CreateTeamMembershipRequest: - """Create an instance of CreateTeamMembershipRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateTeamMembershipRequest: - """Create an instance of CreateTeamMembershipRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateTeamMembershipRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CreateTeamMembershipRequest) in the input: " + str(obj)) - - _obj = CreateTeamMembershipRequest.parse_obj({ - "email": obj.get("email"), - "role": obj.get("role") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/creator.py b/lightly/openapi_generated/swagger_client/models/creator.py deleted file mode 100644 index a4177303c..000000000 --- a/lightly/openapi_generated/swagger_client/models/creator.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class Creator(str, Enum): - """ - Creator - """ - - """ - allowed enum values - """ - UNKNOWN = 'UNKNOWN' - USER_WEBAPP = 'USER_WEBAPP' - USER_PIP = 'USER_PIP' - USER_PIP_LIGHTLY_MAGIC = 'USER_PIP_LIGHTLY_MAGIC' - USER_WORKER = 'USER_WORKER' - - @classmethod - def from_json(cls, json_str: str) -> 'Creator': - """Create an instance of Creator from a JSON string""" - return Creator(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/crop_data.py b/lightly/openapi_generated/swagger_client/models/crop_data.py deleted file mode 100644 index 3626d9303..000000000 --- a/lightly/openapi_generated/swagger_client/models/crop_data.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Union -from pydantic import Extra, BaseModel, Field, confloat, conint, constr, validator - -class CropData(BaseModel): - """ - CropData - """ - parent_id: constr(strict=True) = Field(..., alias="parentId", description="MongoDB ObjectId") - prediction_uuid_timestamp: conint(strict=True, ge=0) = Field(..., alias="predictionUUIDTimestamp", description="unix timestamp in milliseconds") - prediction_index: conint(strict=True, ge=0) = Field(..., alias="predictionIndex", description="the index of this crop within all found prediction singletons of a sampleId (the parentId)") - prediction_task_name: constr(strict=True, min_length=1) = Field(..., alias="predictionTaskName", description="A name which is safe to have as a file/folder name in a file system") - prediction_task_category_id: conint(strict=True, ge=0) = Field(..., alias="predictionTaskCategoryId", description="The id of the category. Needs to be a positive integer but can be any integer (gaps are allowed, does not need to be sequential)") - prediction_task_score: Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)] = Field(..., alias="predictionTaskScore", description="the score for the prediction task which yielded this crop") - __properties = ["parentId", "predictionUUIDTimestamp", "predictionIndex", "predictionTaskName", "predictionTaskCategoryId", "predictionTaskScore"] - - @validator('parent_id') - def parent_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('prediction_task_name') - def prediction_task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> CropData: - """Create an instance of CropData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CropData: - """Create an instance of CropData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CropData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in CropData) in the input: " + str(obj)) - - _obj = CropData.parse_obj({ - "parent_id": obj.get("parentId"), - "prediction_uuid_timestamp": obj.get("predictionUUIDTimestamp"), - "prediction_index": obj.get("predictionIndex"), - "prediction_task_name": obj.get("predictionTaskName"), - "prediction_task_category_id": obj.get("predictionTaskCategoryId"), - "prediction_task_score": obj.get("predictionTaskScore") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_create_request.py b/lightly/openapi_generated/swagger_client/models/dataset_create_request.py deleted file mode 100644 index 80e858a77..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_create_request.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.dataset_creator import DatasetCreator -from lightly.openapi_generated.swagger_client.models.dataset_type import DatasetType -from lightly.openapi_generated.swagger_client.models.image_type import ImageType - -class DatasetCreateRequest(BaseModel): - """ - DatasetCreateRequest - """ - name: constr(strict=True, min_length=3) = Field(...) - type: Optional[DatasetType] = None - img_type: Optional[ImageType] = Field(None, alias="imgType") - creator: Optional[DatasetCreator] = None - parent_dataset_id: Optional[constr(strict=True)] = Field(None, alias="parentDatasetId", description="MongoDB ObjectId") - __properties = ["name", "type", "imgType", "creator", "parentDatasetId"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - @validator('parent_dataset_id') - def parent_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasetCreateRequest: - """Create an instance of DatasetCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasetCreateRequest: - """Create an instance of DatasetCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasetCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasetCreateRequest) in the input: " + str(obj)) - - _obj = DatasetCreateRequest.parse_obj({ - "name": obj.get("name"), - "type": obj.get("type"), - "img_type": obj.get("imgType"), - "creator": obj.get("creator"), - "parent_dataset_id": obj.get("parentDatasetId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_creator.py b/lightly/openapi_generated/swagger_client/models/dataset_creator.py deleted file mode 100644 index 396c9f8e4..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_creator.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DatasetCreator(str, Enum): - """ - DatasetCreator - """ - - """ - allowed enum values - """ - UNKNOWN = 'UNKNOWN' - USER_WEBAPP = 'USER_WEBAPP' - USER_PIP = 'USER_PIP' - USER_PIP_LIGHTLY_MAGIC = 'USER_PIP_LIGHTLY_MAGIC' - USER_WORKER = 'USER_WORKER' - - @classmethod - def from_json(cls, json_str: str) -> 'DatasetCreator': - """Create an instance of DatasetCreator from a JSON string""" - return DatasetCreator(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_data.py b/lightly/openapi_generated/swagger_client/models/dataset_data.py deleted file mode 100644 index 75063c96a..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_data.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.dataset_type import DatasetType -from lightly.openapi_generated.swagger_client.models.image_type import ImageType -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType - -class DatasetData(BaseModel): - """ - DatasetData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: constr(strict=True, min_length=3) = Field(...) - user_id: StrictStr = Field(..., alias="userId", description="The owner of the dataset") - access_type: Optional[SharedAccessType] = Field(None, alias="accessType") - type: DatasetType = Field(...) - img_type: Optional[ImageType] = Field(None, alias="imgType") - n_samples: StrictInt = Field(..., alias="nSamples") - size_in_bytes: StrictInt = Field(..., alias="sizeInBytes") - meta_data_configuration_id: Optional[constr(strict=True)] = Field(None, alias="metaDataConfigurationId", description="MongoDB ObjectId") - datasources: Optional[conlist(constr(strict=True))] = None - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - datasource_processed_until_timestamp: Optional[conint(strict=True, ge=0)] = Field(None, alias="datasourceProcessedUntilTimestamp", description="unix timestamp in seconds") - access_role: Optional[constr(strict=True)] = Field(None, alias="accessRole", description="AccessRole bitmask of the one accessing the dataset") - parent_dataset_id: Optional[constr(strict=True)] = Field(None, alias="parentDatasetId", description="MongoDB ObjectId") - original_dataset_id: Optional[constr(strict=True)] = Field(None, alias="originalDatasetId", description="MongoDB ObjectId") - __properties = ["id", "name", "userId", "accessType", "type", "imgType", "nSamples", "sizeInBytes", "metaDataConfigurationId", "datasources", "createdAt", "lastModifiedAt", "datasourceProcessedUntilTimestamp", "accessRole", "parentDatasetId", "originalDatasetId"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - @validator('meta_data_configuration_id') - def meta_data_configuration_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('access_role') - def access_role_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^0b[01]{6}$", value): - raise ValueError(r"must validate the regular expression /^0b[01]{6}$/") - return value - - @validator('parent_dataset_id') - def parent_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('original_dataset_id') - def original_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasetData: - """Create an instance of DatasetData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasetData: - """Create an instance of DatasetData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasetData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasetData) in the input: " + str(obj)) - - _obj = DatasetData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "user_id": obj.get("userId"), - "access_type": obj.get("accessType"), - "type": obj.get("type"), - "img_type": obj.get("imgType"), - "n_samples": obj.get("nSamples"), - "size_in_bytes": obj.get("sizeInBytes"), - "meta_data_configuration_id": obj.get("metaDataConfigurationId"), - "datasources": obj.get("datasources"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "datasource_processed_until_timestamp": obj.get("datasourceProcessedUntilTimestamp"), - "access_role": obj.get("accessRole"), - "parent_dataset_id": obj.get("parentDatasetId"), - "original_dataset_id": obj.get("originalDatasetId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_data_enriched.py b/lightly/openapi_generated/swagger_client/models/dataset_data_enriched.py deleted file mode 100644 index ce6e65671..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_data_enriched.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.dataset_type import DatasetType -from lightly.openapi_generated.swagger_client.models.image_type import ImageType -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType - -class DatasetDataEnriched(BaseModel): - """ - DatasetDataEnriched - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: constr(strict=True, min_length=3) = Field(...) - user_id: StrictStr = Field(..., alias="userId", description="The owner of the dataset") - access_type: Optional[SharedAccessType] = Field(None, alias="accessType") - type: DatasetType = Field(...) - img_type: Optional[ImageType] = Field(None, alias="imgType") - n_samples: StrictInt = Field(..., alias="nSamples") - size_in_bytes: StrictInt = Field(..., alias="sizeInBytes") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - meta_data_configuration_id: Optional[constr(strict=True)] = Field(None, alias="metaDataConfigurationId", description="MongoDB ObjectId") - access_role: Optional[constr(strict=True)] = Field(None, alias="accessRole", description="AccessRole bitmask of the one accessing the dataset") - datasources: Optional[conlist(constr(strict=True))] = None - parent_dataset_id: Optional[constr(strict=True)] = Field(None, alias="parentDatasetId", description="MongoDB ObjectId") - original_dataset_id: Optional[constr(strict=True)] = Field(None, alias="originalDatasetId", description="MongoDB ObjectId") - samples: conlist(constr(strict=True)) = Field(...) - n_tags: StrictInt = Field(..., alias="nTags") - n_embeddings: StrictInt = Field(..., alias="nEmbeddings") - __properties = ["id", "name", "userId", "accessType", "type", "imgType", "nSamples", "sizeInBytes", "createdAt", "lastModifiedAt", "metaDataConfigurationId", "accessRole", "datasources", "parentDatasetId", "originalDatasetId", "samples", "nTags", "nEmbeddings"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - @validator('meta_data_configuration_id') - def meta_data_configuration_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('access_role') - def access_role_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^0b[01]{6}$", value): - raise ValueError(r"must validate the regular expression /^0b[01]{6}$/") - return value - - @validator('parent_dataset_id') - def parent_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('original_dataset_id') - def original_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasetDataEnriched: - """Create an instance of DatasetDataEnriched from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasetDataEnriched: - """Create an instance of DatasetDataEnriched from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasetDataEnriched.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasetDataEnriched) in the input: " + str(obj)) - - _obj = DatasetDataEnriched.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "user_id": obj.get("userId"), - "access_type": obj.get("accessType"), - "type": obj.get("type"), - "img_type": obj.get("imgType"), - "n_samples": obj.get("nSamples"), - "size_in_bytes": obj.get("sizeInBytes"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "meta_data_configuration_id": obj.get("metaDataConfigurationId"), - "access_role": obj.get("accessRole"), - "datasources": obj.get("datasources"), - "parent_dataset_id": obj.get("parentDatasetId"), - "original_dataset_id": obj.get("originalDatasetId"), - "samples": obj.get("samples"), - "n_tags": obj.get("nTags"), - "n_embeddings": obj.get("nEmbeddings") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_embedding_data.py b/lightly/openapi_generated/swagger_client/models/dataset_embedding_data.py deleted file mode 100644 index 8552bfbb3..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_embedding_data.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint, constr, validator - -class DatasetEmbeddingData(BaseModel): - """ - DatasetEmbeddingData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: StrictStr = Field(..., description="name of the embedding chosen by the user calling writeCSVUrl") - is_processed: StrictBool = Field(..., alias="isProcessed", description="indicator whether embeddings have already been processed by a background worker") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - is2d: Optional[StrictBool] = Field(None, description="flag set by the background worker if the embedding is 2d") - __properties = ["id", "name", "isProcessed", "createdAt", "is2d"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasetEmbeddingData: - """Create an instance of DatasetEmbeddingData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasetEmbeddingData: - """Create an instance of DatasetEmbeddingData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasetEmbeddingData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasetEmbeddingData) in the input: " + str(obj)) - - _obj = DatasetEmbeddingData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "is_processed": obj.get("isProcessed"), - "created_at": obj.get("createdAt"), - "is2d": obj.get("is2d") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_type.py b/lightly/openapi_generated/swagger_client/models/dataset_type.py deleted file mode 100644 index 0d4db4d18..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_type.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DatasetType(str, Enum): - """ - DatasetType - """ - - """ - allowed enum values - """ - CROPS = 'Crops' - IMAGES = 'Images' - VIDEOS = 'Videos' - - @classmethod - def from_json(cls, json_str: str) -> 'DatasetType': - """Create an instance of DatasetType from a JSON string""" - return DatasetType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/dataset_update_request.py b/lightly/openapi_generated/swagger_client/models/dataset_update_request.py deleted file mode 100644 index 2df361144..000000000 --- a/lightly/openapi_generated/swagger_client/models/dataset_update_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr, validator - -class DatasetUpdateRequest(BaseModel): - """ - DatasetUpdateRequest - """ - name: constr(strict=True, min_length=3) = Field(...) - __properties = ["name"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasetUpdateRequest: - """Create an instance of DatasetUpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasetUpdateRequest: - """Create an instance of DatasetUpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasetUpdateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasetUpdateRequest) in the input: " + str(obj)) - - _obj = DatasetUpdateRequest.parse_obj({ - "name": obj.get("name") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config.py b/lightly/openapi_generated/swagger_client/models/datasource_config.py deleted file mode 100644 index 4a2469f8f..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config.py +++ /dev/null @@ -1,288 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.datasource_config_azure import DatasourceConfigAzure -from lightly.openapi_generated.swagger_client.models.datasource_config_gcs import DatasourceConfigGCS -from lightly.openapi_generated.swagger_client.models.datasource_config_lightly import DatasourceConfigLIGHTLY -from lightly.openapi_generated.swagger_client.models.datasource_config_local import DatasourceConfigLOCAL -from lightly.openapi_generated.swagger_client.models.datasource_config_obs import DatasourceConfigOBS -from lightly.openapi_generated.swagger_client.models.datasource_config_s3 import DatasourceConfigS3 -from lightly.openapi_generated.swagger_client.models.datasource_config_s3_delegated_access import DatasourceConfigS3DelegatedAccess -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -DATASOURCECONFIG_ONE_OF_SCHEMAS = ["DatasourceConfigAzure", "DatasourceConfigGCS", "DatasourceConfigLIGHTLY", "DatasourceConfigLOCAL", "DatasourceConfigOBS", "DatasourceConfigS3", "DatasourceConfigS3DelegatedAccess"] - -class DatasourceConfig(BaseModel): - """ - DatasourceConfig - """ - # data type: DatasourceConfigLIGHTLY - oneof_schema_1_validator: Optional[DatasourceConfigLIGHTLY] = None - # data type: DatasourceConfigS3 - oneof_schema_2_validator: Optional[DatasourceConfigS3] = None - # data type: DatasourceConfigS3DelegatedAccess - oneof_schema_3_validator: Optional[DatasourceConfigS3DelegatedAccess] = None - # data type: DatasourceConfigGCS - oneof_schema_4_validator: Optional[DatasourceConfigGCS] = None - # data type: DatasourceConfigAzure - oneof_schema_5_validator: Optional[DatasourceConfigAzure] = None - # data type: DatasourceConfigOBS - oneof_schema_6_validator: Optional[DatasourceConfigOBS] = None - # data type: DatasourceConfigLOCAL - oneof_schema_7_validator: Optional[DatasourceConfigLOCAL] = None - actual_instance: Any - one_of_schemas: List[str] = Field(DATASOURCECONFIG_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - discriminator_value_class_map = { - } - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = DatasourceConfig.construct() - error_messages = [] - match = 0 - # validate data type: DatasourceConfigLIGHTLY - if not isinstance(v, DatasourceConfigLIGHTLY): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigLIGHTLY`") - else: - match += 1 - # validate data type: DatasourceConfigS3 - if not isinstance(v, DatasourceConfigS3): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigS3`") - else: - match += 1 - # validate data type: DatasourceConfigS3DelegatedAccess - if not isinstance(v, DatasourceConfigS3DelegatedAccess): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigS3DelegatedAccess`") - else: - match += 1 - # validate data type: DatasourceConfigGCS - if not isinstance(v, DatasourceConfigGCS): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigGCS`") - else: - match += 1 - # validate data type: DatasourceConfigAzure - if not isinstance(v, DatasourceConfigAzure): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigAzure`") - else: - match += 1 - # validate data type: DatasourceConfigOBS - if not isinstance(v, DatasourceConfigOBS): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigOBS`") - else: - match += 1 - # validate data type: DatasourceConfigLOCAL - if not isinstance(v, DatasourceConfigLOCAL): - error_messages.append(f"Error! Input type `{type(v)}` is not `DatasourceConfigLOCAL`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in DatasourceConfig with oneOf schemas: DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in DatasourceConfig with oneOf schemas: DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfig: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfig: - """Returns the object represented by the json string""" - instance = DatasourceConfig.construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("type") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `type` in the input.") - - # check if data type is `DatasourceConfigAzure` - if _data_type == "AZURE": - instance.actual_instance = DatasourceConfigAzure.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigAzure` - if _data_type == "DatasourceConfigAzure": - instance.actual_instance = DatasourceConfigAzure.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigGCS` - if _data_type == "DatasourceConfigGCS": - instance.actual_instance = DatasourceConfigGCS.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigLIGHTLY` - if _data_type == "DatasourceConfigLIGHTLY": - instance.actual_instance = DatasourceConfigLIGHTLY.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigLOCAL` - if _data_type == "DatasourceConfigLOCAL": - instance.actual_instance = DatasourceConfigLOCAL.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigOBS` - if _data_type == "DatasourceConfigOBS": - instance.actual_instance = DatasourceConfigOBS.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigS3` - if _data_type == "DatasourceConfigS3": - instance.actual_instance = DatasourceConfigS3.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigS3DelegatedAccess` - if _data_type == "DatasourceConfigS3DelegatedAccess": - instance.actual_instance = DatasourceConfigS3DelegatedAccess.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigGCS` - if _data_type == "GCS": - instance.actual_instance = DatasourceConfigGCS.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigLIGHTLY` - if _data_type == "LIGHTLY": - instance.actual_instance = DatasourceConfigLIGHTLY.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigLOCAL` - if _data_type == "LOCAL": - instance.actual_instance = DatasourceConfigLOCAL.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigOBS` - if _data_type == "OBS": - instance.actual_instance = DatasourceConfigOBS.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigS3` - if _data_type == "S3": - instance.actual_instance = DatasourceConfigS3.from_json(json_str) - return instance - - # check if data type is `DatasourceConfigS3DelegatedAccess` - if _data_type == "S3DelegatedAccess": - instance.actual_instance = DatasourceConfigS3DelegatedAccess.from_json(json_str) - return instance - - # deserialize data into DatasourceConfigLIGHTLY - try: - instance.actual_instance = DatasourceConfigLIGHTLY.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigS3 - try: - instance.actual_instance = DatasourceConfigS3.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigS3DelegatedAccess - try: - instance.actual_instance = DatasourceConfigS3DelegatedAccess.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigGCS - try: - instance.actual_instance = DatasourceConfigGCS.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigAzure - try: - instance.actual_instance = DatasourceConfigAzure.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigOBS - try: - instance.actual_instance = DatasourceConfigOBS.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DatasourceConfigLOCAL - try: - instance.actual_instance = DatasourceConfigLOCAL.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into DatasourceConfig with oneOf schemas: DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into DatasourceConfig with oneOf schemas: DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_azure.py b/lightly/openapi_generated/swagger_client/models/datasource_config_azure.py deleted file mode 100644 index 6214b0725..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_azure.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase - -class DatasourceConfigAzure(DatasourceConfigBase): - """ - DatasourceConfigAzure - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - account_name: constr(strict=True, min_length=1) = Field(..., alias="accountName", description="name of the Azure Storage Account") - account_key: constr(strict=True, min_length=1) = Field(..., alias="accountKey", description="key of the Azure Storage Account") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "accountName", "accountKey"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigAzure: - """Create an instance of DatasourceConfigAzure from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigAzure: - """Create an instance of DatasourceConfigAzure from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigAzure.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigAzure) in the input: " + str(obj)) - - _obj = DatasourceConfigAzure.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "account_name": obj.get("accountName"), - "account_key": obj.get("accountKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_azure_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_azure_all_of.py deleted file mode 100644 index dc59a9693..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_azure_all_of.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr - -class DatasourceConfigAzureAllOf(BaseModel): - """ - DatasourceConfigAzureAllOf - """ - account_name: constr(strict=True, min_length=1) = Field(..., alias="accountName", description="name of the Azure Storage Account") - account_key: constr(strict=True, min_length=1) = Field(..., alias="accountKey", description="key of the Azure Storage Account") - __properties = ["accountName", "accountKey"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigAzureAllOf: - """Create an instance of DatasourceConfigAzureAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigAzureAllOf: - """Create an instance of DatasourceConfigAzureAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigAzureAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigAzureAllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigAzureAllOf.parse_obj({ - "account_name": obj.get("accountName"), - "account_key": obj.get("accountKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_base.py b/lightly/openapi_generated/swagger_client/models/datasource_config_base.py deleted file mode 100644 index 41c71cce3..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_base.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json -import lightly.openapi_generated.swagger_client.models - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.datasource_purpose import DatasourcePurpose - -class DatasourceConfigBase(BaseModel): - """ - DatasourceConfigBase - """ - id: Optional[constr(strict=True)] = Field(None, description="MongoDB ObjectId") - purpose: DatasourcePurpose = Field(...) - type: StrictStr = Field(...) - thumb_suffix: Optional[StrictStr] = Field(None, alias="thumbSuffix", description="the suffix of where to find the thumbnail image. If none is provided, the full image will be loaded where thumbnails would be loaded otherwise. - [filename]: represents the filename without the extension - [extension]: represents the files extension (e.g jpg, png, webp) ") - __properties = ["id", "purpose", "type", "thumbSuffix"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - # JSON field name that stores the object type - __discriminator_property_name = 'type' - - # discriminator mappings - __discriminator_value_class_map = { - 'DatasourceConfigAzure': 'DatasourceConfigAzure', - 'DatasourceConfigGCS': 'DatasourceConfigGCS', - 'DatasourceConfigLIGHTLY': 'DatasourceConfigLIGHTLY', - 'DatasourceConfigLOCAL': 'DatasourceConfigLOCAL', - 'DatasourceConfigOBS': 'DatasourceConfigOBS', - 'DatasourceConfigS3': 'DatasourceConfigS3', - 'DatasourceConfigS3DelegatedAccess': 'DatasourceConfigS3DelegatedAccess' - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Union(DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess): - """Create an instance of DatasourceConfigBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Union(DatasourceConfigAzure, DatasourceConfigGCS, DatasourceConfigLIGHTLY, DatasourceConfigLOCAL, DatasourceConfigOBS, DatasourceConfigS3, DatasourceConfigS3DelegatedAccess): - """Create an instance of DatasourceConfigBase from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = getattr(lightly.openapi_generated.swagger_client.models, object_type) - return klass.from_dict(obj) - else: - raise ValueError("DatasourceConfigBase failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_base_full_path.py b/lightly/openapi_generated/swagger_client/models/datasource_config_base_full_path.py deleted file mode 100644 index eace63453..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_base_full_path.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DatasourceConfigBaseFullPath(BaseModel): - """ - DatasourceConfigBaseFullPath - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - __properties = ["fullPath"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigBaseFullPath: - """Create an instance of DatasourceConfigBaseFullPath from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigBaseFullPath: - """Create an instance of DatasourceConfigBaseFullPath from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigBaseFullPath.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigBaseFullPath) in the input: " + str(obj)) - - _obj = DatasourceConfigBaseFullPath.parse_obj({ - "full_path": obj.get("fullPath") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_gcs.py b/lightly/openapi_generated/swagger_client/models/datasource_config_gcs.py deleted file mode 100644 index d9b150eb6..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_gcs.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase - -class DatasourceConfigGCS(DatasourceConfigBase): - """ - DatasourceConfigGCS - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - gcs_project_id: constr(strict=True, min_length=1) = Field(..., alias="gcsProjectId", description="The projectId where you have your bucket configured") - gcs_credentials: StrictStr = Field(..., alias="gcsCredentials", description="this is the content of the credentials JSON file stringified which you downloaded from Google Cloud Platform") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "gcsProjectId", "gcsCredentials"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigGCS: - """Create an instance of DatasourceConfigGCS from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigGCS: - """Create an instance of DatasourceConfigGCS from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigGCS.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigGCS) in the input: " + str(obj)) - - _obj = DatasourceConfigGCS.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "gcs_project_id": obj.get("gcsProjectId"), - "gcs_credentials": obj.get("gcsCredentials") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_gcs_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_gcs_all_of.py deleted file mode 100644 index 580e33f04..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_gcs_all_of.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr - -class DatasourceConfigGCSAllOf(BaseModel): - """ - DatasourceConfigGCSAllOf - """ - gcs_project_id: constr(strict=True, min_length=1) = Field(..., alias="gcsProjectId", description="The projectId where you have your bucket configured") - gcs_credentials: StrictStr = Field(..., alias="gcsCredentials", description="this is the content of the credentials JSON file stringified which you downloaded from Google Cloud Platform") - __properties = ["gcsProjectId", "gcsCredentials"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigGCSAllOf: - """Create an instance of DatasourceConfigGCSAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigGCSAllOf: - """Create an instance of DatasourceConfigGCSAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigGCSAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigGCSAllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigGCSAllOf.parse_obj({ - "gcs_project_id": obj.get("gcsProjectId"), - "gcs_credentials": obj.get("gcsCredentials") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_lightly.py b/lightly/openapi_generated/swagger_client/models/datasource_config_lightly.py deleted file mode 100644 index 2617eae53..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_lightly.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase - -class DatasourceConfigLIGHTLY(DatasourceConfigBase): - """ - DatasourceConfigLIGHTLY - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigLIGHTLY: - """Create an instance of DatasourceConfigLIGHTLY from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigLIGHTLY: - """Create an instance of DatasourceConfigLIGHTLY from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigLIGHTLY.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigLIGHTLY) in the input: " + str(obj)) - - _obj = DatasourceConfigLIGHTLY.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_local.py b/lightly/openapi_generated/swagger_client/models/datasource_config_local.py deleted file mode 100644 index e2f819723..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_local.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase - -class DatasourceConfigLOCAL(DatasourceConfigBase): - """ - DatasourceConfigLOCAL - """ - full_path: StrictStr = Field(..., alias="fullPath", description="Relative path from the mount point. Not allowed to start with \"/\", contain \"://\" or contain \".\" or \"..\" directory parts.") - web_server_location: Optional[constr(strict=True)] = Field(None, alias="webServerLocation", description="The webserver location where your local webserver is running to use for viewing images in the webapp when using the local datasource workflow. Defaults to http://localhost:3456 ") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "webServerLocation"] - - @validator('web_server_location') - def web_server_location_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^https?:\/\/.+$", value): - raise ValueError(r"must validate the regular expression /^https?:\/\/.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigLOCAL: - """Create an instance of DatasourceConfigLOCAL from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigLOCAL: - """Create an instance of DatasourceConfigLOCAL from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigLOCAL.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigLOCAL) in the input: " + str(obj)) - - _obj = DatasourceConfigLOCAL.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "web_server_location": obj.get("webServerLocation") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_local_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_local_all_of.py deleted file mode 100644 index 247074c37..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_local_all_of.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator - -class DatasourceConfigLOCALAllOf(BaseModel): - """ - DatasourceConfigLOCALAllOf - """ - full_path: StrictStr = Field(..., alias="fullPath", description="Relative path from the mount point. Not allowed to start with \"/\", contain \"://\" or contain \".\" or \"..\" directory parts.") - web_server_location: Optional[constr(strict=True)] = Field(None, alias="webServerLocation", description="The webserver location where your local webserver is running to use for viewing images in the webapp when using the local datasource workflow. Defaults to http://localhost:3456 ") - __properties = ["fullPath", "webServerLocation"] - - @validator('web_server_location') - def web_server_location_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^https?:\/\/.+$", value): - raise ValueError(r"must validate the regular expression /^https?:\/\/.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigLOCALAllOf: - """Create an instance of DatasourceConfigLOCALAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigLOCALAllOf: - """Create an instance of DatasourceConfigLOCALAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigLOCALAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigLOCALAllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigLOCALAllOf.parse_obj({ - "full_path": obj.get("fullPath"), - "web_server_location": obj.get("webServerLocation") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_obs.py b/lightly/openapi_generated/swagger_client/models/datasource_config_obs.py deleted file mode 100644 index f50bab55b..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_obs.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase - -class DatasourceConfigOBS(DatasourceConfigBase): - """ - DatasourceConfigOBS - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - obs_endpoint: constr(strict=True, min_length=1) = Field(..., alias="obsEndpoint", description="The Object Storage Service (OBS) endpoint to use of your S3 compatible cloud storage provider") - obs_access_key_id: constr(strict=True, min_length=1) = Field(..., alias="obsAccessKeyId", description="The Access Key Id of the credential you are providing Lightly to use") - obs_secret_access_key: constr(strict=True, min_length=1) = Field(..., alias="obsSecretAccessKey", description="The Secret Access Key of the credential you are providing Lightly to use") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "obsEndpoint", "obsAccessKeyId", "obsSecretAccessKey"] - - @validator('obs_endpoint') - def obs_endpoint_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^https?:\/\/.+$", value): - raise ValueError(r"must validate the regular expression /^https?:\/\/.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigOBS: - """Create an instance of DatasourceConfigOBS from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigOBS: - """Create an instance of DatasourceConfigOBS from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigOBS.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigOBS) in the input: " + str(obj)) - - _obj = DatasourceConfigOBS.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "obs_endpoint": obj.get("obsEndpoint"), - "obs_access_key_id": obj.get("obsAccessKeyId"), - "obs_secret_access_key": obj.get("obsSecretAccessKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_obs_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_obs_all_of.py deleted file mode 100644 index 9209302d8..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_obs_all_of.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr, validator - -class DatasourceConfigOBSAllOf(BaseModel): - """ - Object Storage Service (OBS) is a S3 (AWS) compatible cloud storage like openstack - """ - obs_endpoint: constr(strict=True, min_length=1) = Field(..., alias="obsEndpoint", description="The Object Storage Service (OBS) endpoint to use of your S3 compatible cloud storage provider") - obs_access_key_id: constr(strict=True, min_length=1) = Field(..., alias="obsAccessKeyId", description="The Access Key Id of the credential you are providing Lightly to use") - obs_secret_access_key: constr(strict=True, min_length=1) = Field(..., alias="obsSecretAccessKey", description="The Secret Access Key of the credential you are providing Lightly to use") - __properties = ["obsEndpoint", "obsAccessKeyId", "obsSecretAccessKey"] - - @validator('obs_endpoint') - def obs_endpoint_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^https?:\/\/.+$", value): - raise ValueError(r"must validate the regular expression /^https?:\/\/.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigOBSAllOf: - """Create an instance of DatasourceConfigOBSAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigOBSAllOf: - """Create an instance of DatasourceConfigOBSAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigOBSAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigOBSAllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigOBSAllOf.parse_obj({ - "obs_endpoint": obj.get("obsEndpoint"), - "obs_access_key_id": obj.get("obsAccessKeyId"), - "obs_secret_access_key": obj.get("obsSecretAccessKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_s3.py b/lightly/openapi_generated/swagger_client/models/datasource_config_s3.py deleted file mode 100644 index 638018727..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_s3.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region - -class DatasourceConfigS3(DatasourceConfigBase): - """ - DatasourceConfigS3 - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - s3_region: S3Region = Field(..., alias="s3Region") - s3_access_key_id: constr(strict=True, min_length=1) = Field(..., alias="s3AccessKeyId", description="The accessKeyId of the credential you are providing Lightly to use") - s3_secret_access_key: constr(strict=True, min_length=1) = Field(..., alias="s3SecretAccessKey", description="The secretAccessKey of the credential you are providing Lightly to use") - s3_server_side_encryption_kms_key: Optional[constr(strict=True, min_length=1)] = Field(None, alias="s3ServerSideEncryptionKMSKey", description="If set, Lightly Worker will automatically set the headers to use server side encryption https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html with this value as the appropriate KMS key arn. This will encrypt the files created by Lightly (crops, frames, thumbnails) in the S3 bucket. ") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "s3Region", "s3AccessKeyId", "s3SecretAccessKey", "s3ServerSideEncryptionKMSKey"] - - @validator('s3_server_side_encryption_kms_key') - def s3_server_side_encryption_kms_key_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigS3: - """Create an instance of DatasourceConfigS3 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigS3: - """Create an instance of DatasourceConfigS3 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigS3.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigS3) in the input: " + str(obj)) - - _obj = DatasourceConfigS3.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "s3_region": obj.get("s3Region"), - "s3_access_key_id": obj.get("s3AccessKeyId"), - "s3_secret_access_key": obj.get("s3SecretAccessKey"), - "s3_server_side_encryption_kms_key": obj.get("s3ServerSideEncryptionKMSKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_s3_all_of.py deleted file mode 100644 index 3e5dbd40f..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_all_of.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region - -class DatasourceConfigS3AllOf(BaseModel): - """ - DatasourceConfigS3AllOf - """ - s3_region: S3Region = Field(..., alias="s3Region") - s3_access_key_id: constr(strict=True, min_length=1) = Field(..., alias="s3AccessKeyId", description="The accessKeyId of the credential you are providing Lightly to use") - s3_secret_access_key: constr(strict=True, min_length=1) = Field(..., alias="s3SecretAccessKey", description="The secretAccessKey of the credential you are providing Lightly to use") - s3_server_side_encryption_kms_key: Optional[constr(strict=True, min_length=1)] = Field(None, alias="s3ServerSideEncryptionKMSKey", description="If set, Lightly Worker will automatically set the headers to use server side encryption https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html with this value as the appropriate KMS key arn. This will encrypt the files created by Lightly (crops, frames, thumbnails) in the S3 bucket. ") - __properties = ["s3Region", "s3AccessKeyId", "s3SecretAccessKey", "s3ServerSideEncryptionKMSKey"] - - @validator('s3_server_side_encryption_kms_key') - def s3_server_side_encryption_kms_key_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigS3AllOf: - """Create an instance of DatasourceConfigS3AllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigS3AllOf: - """Create an instance of DatasourceConfigS3AllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigS3AllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigS3AllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigS3AllOf.parse_obj({ - "s3_region": obj.get("s3Region"), - "s3_access_key_id": obj.get("s3AccessKeyId"), - "s3_secret_access_key": obj.get("s3SecretAccessKey"), - "s3_server_side_encryption_kms_key": obj.get("s3ServerSideEncryptionKMSKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access.py b/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access.py deleted file mode 100644 index 3ea071e56..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.datasource_config_base import DatasourceConfigBase -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region - -class DatasourceConfigS3DelegatedAccess(DatasourceConfigBase): - """ - DatasourceConfigS3DelegatedAccess - """ - full_path: StrictStr = Field(..., alias="fullPath", description="path includes the bucket name and the path within the bucket where you have stored your information") - s3_region: S3Region = Field(..., alias="s3Region") - s3_external_id: constr(strict=True, min_length=10) = Field(..., alias="s3ExternalId", description="The external ID specified when creating the role.") - s3_arn: constr(strict=True, min_length=12) = Field(..., alias="s3ARN", description="The ARN of the role you created") - s3_server_side_encryption_kms_key: Optional[constr(strict=True, min_length=1)] = Field(None, alias="s3ServerSideEncryptionKMSKey", description="If set, Lightly Worker will automatically set the headers to use server side encryption https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html with this value as the appropriate KMS key arn. This will encrypt the files created by Lightly (crops, frames, thumbnails) in the S3 bucket. ") - __properties = ["id", "purpose", "type", "thumbSuffix", "fullPath", "s3Region", "s3ExternalId", "s3ARN", "s3ServerSideEncryptionKMSKey"] - - @validator('s3_external_id') - def s3_external_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]+$/") - return value - - @validator('s3_arn') - def s3_arn_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^arn:aws:iam::[0-9]{12}:role.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:iam::[0-9]{12}:role.+$/") - return value - - @validator('s3_server_side_encryption_kms_key') - def s3_server_side_encryption_kms_key_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigS3DelegatedAccess: - """Create an instance of DatasourceConfigS3DelegatedAccess from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigS3DelegatedAccess: - """Create an instance of DatasourceConfigS3DelegatedAccess from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigS3DelegatedAccess.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigS3DelegatedAccess) in the input: " + str(obj)) - - _obj = DatasourceConfigS3DelegatedAccess.parse_obj({ - "id": obj.get("id"), - "purpose": obj.get("purpose"), - "type": obj.get("type"), - "thumb_suffix": obj.get("thumbSuffix"), - "full_path": obj.get("fullPath"), - "s3_region": obj.get("s3Region"), - "s3_external_id": obj.get("s3ExternalId"), - "s3_arn": obj.get("s3ARN"), - "s3_server_side_encryption_kms_key": obj.get("s3ServerSideEncryptionKMSKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access_all_of.py b/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access_all_of.py deleted file mode 100644 index 2b2109af8..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_s3_delegated_access_all_of.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.s3_region import S3Region - -class DatasourceConfigS3DelegatedAccessAllOf(BaseModel): - """ - DatasourceConfigS3DelegatedAccessAllOf - """ - s3_region: S3Region = Field(..., alias="s3Region") - s3_external_id: constr(strict=True, min_length=10) = Field(..., alias="s3ExternalId", description="The external ID specified when creating the role.") - s3_arn: constr(strict=True, min_length=12) = Field(..., alias="s3ARN", description="The ARN of the role you created") - s3_server_side_encryption_kms_key: Optional[constr(strict=True, min_length=1)] = Field(None, alias="s3ServerSideEncryptionKMSKey", description="If set, Lightly Worker will automatically set the headers to use server side encryption https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html with this value as the appropriate KMS key arn. This will encrypt the files created by Lightly (crops, frames, thumbnails) in the S3 bucket. ") - __properties = ["s3Region", "s3ExternalId", "s3ARN", "s3ServerSideEncryptionKMSKey"] - - @validator('s3_external_id') - def s3_external_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]+$/") - return value - - @validator('s3_arn') - def s3_arn_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^arn:aws:iam::[0-9]{12}:role.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:iam::[0-9]{12}:role.+$/") - return value - - @validator('s3_server_side_encryption_kms_key') - def s3_server_side_encryption_kms_key_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$", value): - raise ValueError(r"must validate the regular expression /^arn:aws:kms:[a-zA-Z0-9-]*:[0-9]{12}:key.+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigS3DelegatedAccessAllOf: - """Create an instance of DatasourceConfigS3DelegatedAccessAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigS3DelegatedAccessAllOf: - """Create an instance of DatasourceConfigS3DelegatedAccessAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigS3DelegatedAccessAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigS3DelegatedAccessAllOf) in the input: " + str(obj)) - - _obj = DatasourceConfigS3DelegatedAccessAllOf.parse_obj({ - "s3_region": obj.get("s3Region"), - "s3_external_id": obj.get("s3ExternalId"), - "s3_arn": obj.get("s3ARN"), - "s3_server_side_encryption_kms_key": obj.get("s3ServerSideEncryptionKMSKey") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data.py b/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data.py deleted file mode 100644 index ae8e14b80..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data_errors import DatasourceConfigVerifyDataErrors - -class DatasourceConfigVerifyData(BaseModel): - """ - DatasourceConfigVerifyData - """ - can_read: StrictBool = Field(..., alias="canRead") - can_write: StrictBool = Field(..., alias="canWrite") - can_list: StrictBool = Field(..., alias="canList") - can_overwrite: StrictBool = Field(..., alias="canOverwrite") - errors: Optional[DatasourceConfigVerifyDataErrors] = None - __properties = ["canRead", "canWrite", "canList", "canOverwrite", "errors"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigVerifyData: - """Create an instance of DatasourceConfigVerifyData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of errors - if self.errors: - _dict['errors' if by_alias else 'errors'] = self.errors.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigVerifyData: - """Create an instance of DatasourceConfigVerifyData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigVerifyData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigVerifyData) in the input: " + str(obj)) - - _obj = DatasourceConfigVerifyData.parse_obj({ - "can_read": obj.get("canRead"), - "can_write": obj.get("canWrite"), - "can_list": obj.get("canList"), - "can_overwrite": obj.get("canOverwrite"), - "errors": DatasourceConfigVerifyDataErrors.from_dict(obj.get("errors")) if obj.get("errors") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data_errors.py b/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data_errors.py deleted file mode 100644 index 03737f6f3..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_config_verify_data_errors.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr - -class DatasourceConfigVerifyDataErrors(BaseModel): - """ - DatasourceConfigVerifyDataErrors - """ - can_read: Optional[StrictStr] = Field(None, alias="canRead") - can_write: Optional[StrictStr] = Field(None, alias="canWrite") - can_list: Optional[StrictStr] = Field(None, alias="canList") - can_overwrite: Optional[StrictStr] = Field(None, alias="canOverwrite") - __properties = ["canRead", "canWrite", "canList", "canOverwrite"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceConfigVerifyDataErrors: - """Create an instance of DatasourceConfigVerifyDataErrors from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceConfigVerifyDataErrors: - """Create an instance of DatasourceConfigVerifyDataErrors from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceConfigVerifyDataErrors.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceConfigVerifyDataErrors) in the input: " + str(obj)) - - _obj = DatasourceConfigVerifyDataErrors.parse_obj({ - "can_read": obj.get("canRead"), - "can_write": obj.get("canWrite"), - "can_list": obj.get("canList"), - "can_overwrite": obj.get("canOverwrite") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_request.py b/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_request.py deleted file mode 100644 index b7cb2f090..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_request.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint - -class DatasourceProcessedUntilTimestampRequest(BaseModel): - """ - DatasourceProcessedUntilTimestampRequest - """ - processed_until_timestamp: conint(strict=True, ge=0) = Field(..., alias="processedUntilTimestamp", description="unix timestamp in milliseconds") - __properties = ["processedUntilTimestamp"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceProcessedUntilTimestampRequest: - """Create an instance of DatasourceProcessedUntilTimestampRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceProcessedUntilTimestampRequest: - """Create an instance of DatasourceProcessedUntilTimestampRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceProcessedUntilTimestampRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceProcessedUntilTimestampRequest) in the input: " + str(obj)) - - _obj = DatasourceProcessedUntilTimestampRequest.parse_obj({ - "processed_until_timestamp": obj.get("processedUntilTimestamp") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_response.py b/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_response.py deleted file mode 100644 index d228893a2..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_processed_until_timestamp_response.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint - -class DatasourceProcessedUntilTimestampResponse(BaseModel): - """ - DatasourceProcessedUntilTimestampResponse - """ - processed_until_timestamp: conint(strict=True, ge=0) = Field(..., alias="processedUntilTimestamp", description="unix timestamp in milliseconds") - __properties = ["processedUntilTimestamp"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceProcessedUntilTimestampResponse: - """Create an instance of DatasourceProcessedUntilTimestampResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceProcessedUntilTimestampResponse: - """Create an instance of DatasourceProcessedUntilTimestampResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceProcessedUntilTimestampResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceProcessedUntilTimestampResponse) in the input: " + str(obj)) - - _obj = DatasourceProcessedUntilTimestampResponse.parse_obj({ - "processed_until_timestamp": obj.get("processedUntilTimestamp") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_purpose.py b/lightly/openapi_generated/swagger_client/models/datasource_purpose.py deleted file mode 100644 index 3b609a096..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_purpose.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DatasourcePurpose(str, Enum): - """ - The datasource purpose and for which use-cases it is needed. - INPUT_OUTPUT: Is used as source of raw data and predictions/metadata within .lightly as well as destination for writing thumbnails, crops or video frame within .lightly - INPUT: Is only used as source of raw data - LIGHTLY: Is used as source of predictions/metadata within .lightly as well as destination for writing thumbnails, crops or video frames within .lightly - """ - - """ - allowed enum values - """ - INPUT_OUTPUT = 'INPUT_OUTPUT' - INPUT = 'INPUT' - LIGHTLY = 'LIGHTLY' - - @classmethod - def from_json(cls, json_str: str) -> 'DatasourcePurpose': - """Create an instance of DatasourcePurpose from a JSON string""" - return DatasourcePurpose(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data.py deleted file mode 100644 index a5642f0af..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data_row import DatasourceRawSamplesDataRow - -class DatasourceRawSamplesData(BaseModel): - """ - DatasourceRawSamplesData - """ - has_more: StrictBool = Field(..., alias="hasMore", description="Set to `false` if end of list is reached. Otherwise `true`.") - cursor: StrictStr = Field(..., description="A cursor that indicates the current position in the list. Must be passed to future requests to continue reading from the same list. ") - data: conlist(DatasourceRawSamplesDataRow) = Field(..., description="Array containing the sample objects") - __properties = ["hasMore", "cursor", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesData: - """Create an instance of DatasourceRawSamplesData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in data (list) - _items = [] - if self.data: - for _item in self.data: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['data' if by_alias else 'data'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesData: - """Create an instance of DatasourceRawSamplesData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesData) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesData.parse_obj({ - "has_more": obj.get("hasMore"), - "cursor": obj.get("cursor"), - "data": [DatasourceRawSamplesDataRow.from_dict(_item) for _item in obj.get("data")] if obj.get("data") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data_row.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data_row.py deleted file mode 100644 index 13edc4f5d..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_data_row.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DatasourceRawSamplesDataRow(BaseModel): - """ - Filename and corresponding read url for a sample in the datasource - """ - file_name: StrictStr = Field(..., alias="fileName") - read_url: StrictStr = Field(..., alias="readUrl", description="A URL which allows anyone in possession of said URL to access the resource") - __properties = ["fileName", "readUrl"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesDataRow: - """Create an instance of DatasourceRawSamplesDataRow from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesDataRow: - """Create an instance of DatasourceRawSamplesDataRow from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesDataRow.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesDataRow) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesDataRow.parse_obj({ - "file_name": obj.get("fileName"), - "read_url": obj.get("readUrl") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data.py deleted file mode 100644 index 628adf561..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_metadata_data_row import DatasourceRawSamplesMetadataDataRow - -class DatasourceRawSamplesMetadataData(BaseModel): - """ - DatasourceRawSamplesMetadataData - """ - has_more: StrictBool = Field(..., alias="hasMore", description="Set to `false` if end of list is reached. Otherwise `true`.") - cursor: StrictStr = Field(..., description="A cursor that indicates the current position in the list. Must be passed to future requests to continue reading from the same list. ") - data: conlist(DatasourceRawSamplesMetadataDataRow) = Field(..., description="Array containing the raw samples metadata objects") - __properties = ["hasMore", "cursor", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesMetadataData: - """Create an instance of DatasourceRawSamplesMetadataData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in data (list) - _items = [] - if self.data: - for _item in self.data: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['data' if by_alias else 'data'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesMetadataData: - """Create an instance of DatasourceRawSamplesMetadataData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesMetadataData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesMetadataData) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesMetadataData.parse_obj({ - "has_more": obj.get("hasMore"), - "cursor": obj.get("cursor"), - "data": [DatasourceRawSamplesMetadataDataRow.from_dict(_item) for _item in obj.get("data")] if obj.get("data") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data_row.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data_row.py deleted file mode 100644 index dd885748e..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_metadata_data_row.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DatasourceRawSamplesMetadataDataRow(BaseModel): - """ - Filename and corresponding read url for the metadata of a sample in the datasource - """ - file_name: StrictStr = Field(..., alias="fileName") - read_url: StrictStr = Field(..., alias="readUrl", description="A URL which allows anyone in possession of said URL to access the resource") - __properties = ["fileName", "readUrl"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesMetadataDataRow: - """Create an instance of DatasourceRawSamplesMetadataDataRow from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesMetadataDataRow: - """Create an instance of DatasourceRawSamplesMetadataDataRow from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesMetadataDataRow.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesMetadataDataRow) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesMetadataDataRow.parse_obj({ - "file_name": obj.get("fileName"), - "read_url": obj.get("readUrl") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data.py deleted file mode 100644 index bdad551ed..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_predictions_data_row import DatasourceRawSamplesPredictionsDataRow - -class DatasourceRawSamplesPredictionsData(BaseModel): - """ - DatasourceRawSamplesPredictionsData - """ - has_more: StrictBool = Field(..., alias="hasMore", description="Set to `false` if end of list is reached. Otherwise `true`.") - cursor: StrictStr = Field(..., description="A cursor that indicates the current position in the list. Must be passed to future requests to continue reading from the same list. ") - data: conlist(DatasourceRawSamplesPredictionsDataRow) = Field(..., description="Array containing the raw samples prediction objects") - __properties = ["hasMore", "cursor", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesPredictionsData: - """Create an instance of DatasourceRawSamplesPredictionsData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in data (list) - _items = [] - if self.data: - for _item in self.data: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['data' if by_alias else 'data'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesPredictionsData: - """Create an instance of DatasourceRawSamplesPredictionsData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesPredictionsData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesPredictionsData) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesPredictionsData.parse_obj({ - "has_more": obj.get("hasMore"), - "cursor": obj.get("cursor"), - "data": [DatasourceRawSamplesPredictionsDataRow.from_dict(_item) for _item in obj.get("data")] if obj.get("data") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data_row.py b/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data_row.py deleted file mode 100644 index 8e2abb75b..000000000 --- a/lightly/openapi_generated/swagger_client/models/datasource_raw_samples_predictions_data_row.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DatasourceRawSamplesPredictionsDataRow(BaseModel): - """ - Filename and corresponding read url for a samples prediction in the datasource - """ - file_name: StrictStr = Field(..., alias="fileName") - read_url: StrictStr = Field(..., alias="readUrl", description="A URL which allows anyone in possession of said URL to access the resource") - __properties = ["fileName", "readUrl"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DatasourceRawSamplesPredictionsDataRow: - """Create an instance of DatasourceRawSamplesPredictionsDataRow from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DatasourceRawSamplesPredictionsDataRow: - """Create an instance of DatasourceRawSamplesPredictionsDataRow from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DatasourceRawSamplesPredictionsDataRow.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DatasourceRawSamplesPredictionsDataRow) in the input: " + str(obj)) - - _obj = DatasourceRawSamplesPredictionsDataRow.parse_obj({ - "file_name": obj.get("fileName"), - "read_url": obj.get("readUrl") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/delegated_access_external_ids_inner.py b/lightly/openapi_generated/swagger_client/models/delegated_access_external_ids_inner.py deleted file mode 100644 index c6ea4066f..000000000 --- a/lightly/openapi_generated/swagger_client/models/delegated_access_external_ids_inner.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator - -class DelegatedAccessExternalIdsInner(BaseModel): - """ - DelegatedAccessExternalIdsInner - """ - external_id: constr(strict=True, min_length=10) = Field(..., alias="externalId", description="The external ID specified when creating the role.") - user_id: Optional[StrictStr] = Field(None, alias="userId") - team_id: Optional[StrictStr] = Field(None, alias="teamId") - __properties = ["externalId", "userId", "teamId"] - - @validator('external_id') - def external_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DelegatedAccessExternalIdsInner: - """Create an instance of DelegatedAccessExternalIdsInner from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DelegatedAccessExternalIdsInner: - """Create an instance of DelegatedAccessExternalIdsInner from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DelegatedAccessExternalIdsInner.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DelegatedAccessExternalIdsInner) in the input: " + str(obj)) - - _obj = DelegatedAccessExternalIdsInner.parse_obj({ - "external_id": obj.get("externalId"), - "user_id": obj.get("userId"), - "team_id": obj.get("teamId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/dimensionality_reduction_method.py b/lightly/openapi_generated/swagger_client/models/dimensionality_reduction_method.py deleted file mode 100644 index 64947045f..000000000 --- a/lightly/openapi_generated/swagger_client/models/dimensionality_reduction_method.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DimensionalityReductionMethod(str, Enum): - """ - Method which was used to create the 2d embeddings - """ - - """ - allowed enum values - """ - PCA = 'PCA' - TSNE = 'TSNE' - UMAP = 'UMAP' - - @classmethod - def from_json(cls, json_str: str) -> 'DimensionalityReductionMethod': - """Create an instance of DimensionalityReductionMethod from a JSON string""" - return DimensionalityReductionMethod(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_authorization_request.py b/lightly/openapi_generated/swagger_client/models/docker_authorization_request.py deleted file mode 100644 index eb6fa33c2..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_authorization_request.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint -from lightly.openapi_generated.swagger_client.models.docker_task_description import DockerTaskDescription - -class DockerAuthorizationRequest(BaseModel): - """ - DockerAuthorizationRequest - """ - timestamp: conint(strict=True, ge=0) = Field(..., description="unix timestamp in milliseconds") - task_description: DockerTaskDescription = Field(..., alias="taskDescription") - __properties = ["timestamp", "taskDescription"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerAuthorizationRequest: - """Create an instance of DockerAuthorizationRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of task_description - if self.task_description: - _dict['taskDescription' if by_alias else 'task_description'] = self.task_description.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerAuthorizationRequest: - """Create an instance of DockerAuthorizationRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerAuthorizationRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerAuthorizationRequest) in the input: " + str(obj)) - - _obj = DockerAuthorizationRequest.parse_obj({ - "timestamp": obj.get("timestamp"), - "task_description": DockerTaskDescription.from_dict(obj.get("taskDescription")) if obj.get("taskDescription") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_authorization_response.py b/lightly/openapi_generated/swagger_client/models/docker_authorization_response.py deleted file mode 100644 index ab552b088..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_authorization_response.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DockerAuthorizationResponse(BaseModel): - """ - DockerAuthorizationResponse - """ - body_string: StrictStr = Field(..., alias="bodyString") - body_hmac: StrictStr = Field(..., alias="bodyHmac") - __properties = ["bodyString", "bodyHmac"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerAuthorizationResponse: - """Create an instance of DockerAuthorizationResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerAuthorizationResponse: - """Create an instance of DockerAuthorizationResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerAuthorizationResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerAuthorizationResponse) in the input: " + str(obj)) - - _obj = DockerAuthorizationResponse.parse_obj({ - "body_string": obj.get("bodyString"), - "body_hmac": obj.get("bodyHmac") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_license_information.py b/lightly/openapi_generated/swagger_client/models/docker_license_information.py deleted file mode 100644 index 6a1ad8419..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_license_information.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint - -class DockerLicenseInformation(BaseModel): - """ - DockerLicenseInformation - """ - license_type: StrictStr = Field(..., alias="licenseType") - license_expiration_date: conint(strict=True, ge=0) = Field(..., alias="licenseExpirationDate", description="unix timestamp in milliseconds") - license_is_valid: StrictBool = Field(..., alias="licenseIsValid") - __properties = ["licenseType", "licenseExpirationDate", "licenseIsValid"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerLicenseInformation: - """Create an instance of DockerLicenseInformation from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerLicenseInformation: - """Create an instance of DockerLicenseInformation from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerLicenseInformation.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerLicenseInformation) in the input: " + str(obj)) - - _obj = DockerLicenseInformation.parse_obj({ - "license_type": obj.get("licenseType"), - "license_expiration_date": obj.get("licenseExpirationDate"), - "license_is_valid": obj.get("licenseIsValid") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_run_artifact_create_request.py deleted file mode 100644 index 42af83ee0..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_create_request.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_storage_location import DockerRunArtifactStorageLocation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_type import DockerRunArtifactType - -class DockerRunArtifactCreateRequest(BaseModel): - """ - DockerRunArtifactCreateRequest - """ - file_name: StrictStr = Field(..., alias="fileName", description="the fileName of the artifact") - type: DockerRunArtifactType = Field(...) - storage_location: Optional[DockerRunArtifactStorageLocation] = Field(None, alias="storageLocation") - __properties = ["fileName", "type", "storageLocation"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunArtifactCreateRequest: - """Create an instance of DockerRunArtifactCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunArtifactCreateRequest: - """Create an instance of DockerRunArtifactCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunArtifactCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunArtifactCreateRequest) in the input: " + str(obj)) - - _obj = DockerRunArtifactCreateRequest.parse_obj({ - "file_name": obj.get("fileName"), - "type": obj.get("type"), - "storage_location": obj.get("storageLocation") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_created_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_artifact_created_data.py deleted file mode 100644 index bde23167a..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_created_data.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DockerRunArtifactCreatedData(BaseModel): - """ - DockerRunArtifactCreatedData - """ - signed_write_url: StrictStr = Field(..., alias="signedWriteUrl") - artifact_id: StrictStr = Field(..., alias="artifactId") - __properties = ["signedWriteUrl", "artifactId"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunArtifactCreatedData: - """Create an instance of DockerRunArtifactCreatedData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunArtifactCreatedData: - """Create an instance of DockerRunArtifactCreatedData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunArtifactCreatedData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunArtifactCreatedData) in the input: " + str(obj)) - - _obj = DockerRunArtifactCreatedData.parse_obj({ - "signed_write_url": obj.get("signedWriteUrl"), - "artifact_id": obj.get("artifactId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_artifact_data.py deleted file mode 100644 index 1a92f6ee6..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_data.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_storage_location import DockerRunArtifactStorageLocation -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_type import DockerRunArtifactType - -class DockerRunArtifactData(BaseModel): - """ - DockerRunArtifactData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - type: DockerRunArtifactType = Field(...) - file_name: StrictStr = Field(..., alias="fileName") - storage_location: Optional[DockerRunArtifactStorageLocation] = Field(None, alias="storageLocation") - created_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "type", "fileName", "storageLocation", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunArtifactData: - """Create an instance of DockerRunArtifactData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunArtifactData: - """Create an instance of DockerRunArtifactData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunArtifactData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunArtifactData) in the input: " + str(obj)) - - _obj = DockerRunArtifactData.parse_obj({ - "id": obj.get("id"), - "type": obj.get("type"), - "file_name": obj.get("fileName"), - "storage_location": obj.get("storageLocation"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_storage_location.py b/lightly/openapi_generated/swagger_client/models/docker_run_artifact_storage_location.py deleted file mode 100644 index 02c2f7cb9..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_storage_location.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunArtifactStorageLocation(str, Enum): - """ - DockerRunArtifactStorageLocation - """ - - """ - allowed enum values - """ - LIGHTLY = 'LIGHTLY' - DATASOURCE = 'DATASOURCE' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunArtifactStorageLocation': - """Create an instance of DockerRunArtifactStorageLocation from a JSON string""" - return DockerRunArtifactStorageLocation(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_type.py b/lightly/openapi_generated/swagger_client/models/docker_run_artifact_type.py deleted file mode 100644 index 02d827c70..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_artifact_type.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunArtifactType(str, Enum): - """ - DockerRunArtifactType - """ - - """ - allowed enum values - """ - LOG = 'LOG' - MEMLOG = 'MEMLOG' - CHECKPOINT = 'CHECKPOINT' - REPORT_PDF = 'REPORT_PDF' - REPORT_JSON = 'REPORT_JSON' - REPORT_V2_JSON = 'REPORT_V2_JSON' - CORRUPTNESS_CHECK_INFORMATION = 'CORRUPTNESS_CHECK_INFORMATION' - SEQUENCE_INFORMATION = 'SEQUENCE_INFORMATION' - RELEVANT_FILENAMES = 'RELEVANT_FILENAMES' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunArtifactType': - """Create an instance of DockerRunArtifactType from a JSON string""" - return DockerRunArtifactType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_run_create_request.py deleted file mode 100644 index 819ac6f3a..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_create_request.py +++ /dev/null @@ -1,119 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.creator import Creator - -class DockerRunCreateRequest(BaseModel): - """ - DockerRunCreateRequest - """ - docker_version: StrictStr = Field(..., alias="dockerVersion") - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - scheduled_id: Optional[constr(strict=True)] = Field(None, alias="scheduledId", description="MongoDB ObjectId") - config_id: Optional[constr(strict=True)] = Field(None, alias="configId", description="MongoDB ObjectId") - message: Optional[StrictStr] = None - creator: Optional[Creator] = None - __properties = ["dockerVersion", "datasetId", "scheduledId", "configId", "message", "creator"] - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('scheduled_id') - def scheduled_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('config_id') - def config_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunCreateRequest: - """Create an instance of DockerRunCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunCreateRequest: - """Create an instance of DockerRunCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunCreateRequest) in the input: " + str(obj)) - - _obj = DockerRunCreateRequest.parse_obj({ - "docker_version": obj.get("dockerVersion"), - "dataset_id": obj.get("datasetId"), - "scheduled_id": obj.get("scheduledId"), - "config_id": obj.get("configId"), - "message": obj.get("message"), - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_data.py deleted file mode 100644 index 5502a6a2c..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_data.py +++ /dev/null @@ -1,146 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_run_artifact_data import DockerRunArtifactData -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState - -class DockerRunData(BaseModel): - """ - DockerRunData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - user_id: StrictStr = Field(..., alias="userId") - docker_version: StrictStr = Field(..., alias="dockerVersion") - state: DockerRunState = Field(...) - archived: Optional[StrictBool] = Field(None, description="if the run is archived") - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - config_id: Optional[constr(strict=True)] = Field(None, alias="configId", description="MongoDB ObjectId") - scheduled_id: Optional[constr(strict=True)] = Field(None, alias="scheduledId", description="MongoDB ObjectId") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - message: Optional[StrictStr] = Field(None, description="last message sent to the docker run") - artifacts: Optional[conlist(DockerRunArtifactData)] = Field(None, description="list of artifacts that were created for a run") - __properties = ["id", "userId", "dockerVersion", "state", "archived", "datasetId", "configId", "scheduledId", "createdAt", "lastModifiedAt", "message", "artifacts"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('config_id') - def config_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('scheduled_id') - def scheduled_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunData: - """Create an instance of DockerRunData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in artifacts (list) - _items = [] - if self.artifacts: - for _item in self.artifacts: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['artifacts' if by_alias else 'artifacts'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunData: - """Create an instance of DockerRunData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunData) in the input: " + str(obj)) - - _obj = DockerRunData.parse_obj({ - "id": obj.get("id"), - "user_id": obj.get("userId"), - "docker_version": obj.get("dockerVersion"), - "state": obj.get("state"), - "archived": obj.get("archived"), - "dataset_id": obj.get("datasetId"), - "config_id": obj.get("configId"), - "scheduled_id": obj.get("scheduledId"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "message": obj.get("message"), - "artifacts": [DockerRunArtifactData.from_dict(_item) for _item in obj.get("artifacts")] if obj.get("artifacts") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_create_entry_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_create_entry_data.py deleted file mode 100644 index dd4fddd09..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_create_entry_data.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint -from lightly.openapi_generated.swagger_client.models.docker_run_log_docker_load import DockerRunLogDockerLoad -from lightly.openapi_generated.swagger_client.models.docker_run_log_level import DockerRunLogLevel -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState - -class DockerRunLogCreateEntryData(BaseModel): - """ - DockerRunLogCreateEntryData - """ - ts: conint(strict=True, ge=0) = Field(..., description="unix timestamp in milliseconds") - level: DockerRunLogLevel = Field(...) - group: StrictStr = Field(..., description="The logger name/group of the log entry.") - origin: Optional[StrictStr] = Field(None, description="The origin/filename+loc from where a log entry was created from.") - msg: StrictStr = Field(..., description="The actual log message.") - state: Optional[DockerRunState] = None - load: Optional[DockerRunLogDockerLoad] = None - __properties = ["ts", "level", "group", "origin", "msg", "state", "load"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunLogCreateEntryData: - """Create an instance of DockerRunLogCreateEntryData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of load - if self.load: - _dict['load' if by_alias else 'load'] = self.load.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunLogCreateEntryData: - """Create an instance of DockerRunLogCreateEntryData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunLogCreateEntryData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunLogCreateEntryData) in the input: " + str(obj)) - - _obj = DockerRunLogCreateEntryData.parse_obj({ - "ts": obj.get("ts"), - "level": obj.get("level"), - "group": obj.get("group"), - "origin": obj.get("origin"), - "msg": obj.get("msg"), - "state": obj.get("state"), - "load": DockerRunLogDockerLoad.from_dict(obj.get("load")) if obj.get("load") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_data.py deleted file mode 100644 index b950012fd..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_data.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, conint, conlist -from lightly.openapi_generated.swagger_client.models.docker_run_log_entry_data import DockerRunLogEntryData - -class DockerRunLogData(BaseModel): - """ - DockerRunLogData - """ - cursor: Optional[conint(strict=True, ge=0)] = Field(0, description="The cursor to use to fetch more logs.") - logs: conlist(DockerRunLogEntryData) = Field(...) - __properties = ["cursor", "logs"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunLogData: - """Create an instance of DockerRunLogData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in logs (list) - _items = [] - if self.logs: - for _item in self.logs: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['logs' if by_alias else 'logs'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunLogData: - """Create an instance of DockerRunLogData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunLogData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunLogData) in the input: " + str(obj)) - - _obj = DockerRunLogData.parse_obj({ - "cursor": obj.get("cursor") if obj.get("cursor") is not None else 0, - "logs": [DockerRunLogEntryData.from_dict(_item) for _item in obj.get("logs")] if obj.get("logs") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_docker_load.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_docker_load.py deleted file mode 100644 index 9610d5994..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_docker_load.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint - -class DockerRunLogDockerLoad(BaseModel): - """ - The load of the docker container when the log entry was created. - """ - cpu: Optional[Union[confloat(le=100, ge=0, strict=True), conint(le=100, ge=0, strict=True)]] = Field(None, description="The cpu usage in percent.") - mem: Optional[Union[confloat(le=100, ge=0, strict=True), conint(le=100, ge=0, strict=True)]] = Field(None, description="The memory usage in percent.") - __properties = ["cpu", "mem"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunLogDockerLoad: - """Create an instance of DockerRunLogDockerLoad from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunLogDockerLoad: - """Create an instance of DockerRunLogDockerLoad from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunLogDockerLoad.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunLogDockerLoad) in the input: " + str(obj)) - - _obj = DockerRunLogDockerLoad.parse_obj({ - "cpu": obj.get("cpu"), - "mem": obj.get("mem") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data.py deleted file mode 100644 index 6d0c025a0..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint -from lightly.openapi_generated.swagger_client.models.docker_run_log_docker_load import DockerRunLogDockerLoad -from lightly.openapi_generated.swagger_client.models.docker_run_log_level import DockerRunLogLevel -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState - -class DockerRunLogEntryData(BaseModel): - """ - DockerRunLogEntryData - """ - ts: conint(strict=True, ge=0) = Field(..., description="unix timestamp in milliseconds") - level: DockerRunLogLevel = Field(...) - group: Optional[StrictStr] = Field(None, description="The logger name/group of the log entry.") - origin: Optional[StrictStr] = Field(None, description="The origin/filename+loc from where a log entry was created from.") - msg: StrictStr = Field(..., description="The actual log message.") - state: DockerRunState = Field(...) - load: Optional[DockerRunLogDockerLoad] = None - __properties = ["ts", "level", "group", "origin", "msg", "state", "load"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunLogEntryData: - """Create an instance of DockerRunLogEntryData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of load - if self.load: - _dict['load' if by_alias else 'load'] = self.load.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunLogEntryData: - """Create an instance of DockerRunLogEntryData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunLogEntryData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunLogEntryData) in the input: " + str(obj)) - - _obj = DockerRunLogEntryData.parse_obj({ - "ts": obj.get("ts"), - "level": obj.get("level"), - "group": obj.get("group"), - "origin": obj.get("origin"), - "msg": obj.get("msg"), - "state": obj.get("state"), - "load": DockerRunLogDockerLoad.from_dict(obj.get("load")) if obj.get("load") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data_base.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data_base.py deleted file mode 100644 index 1f76b4f65..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_entry_data_base.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint -from lightly.openapi_generated.swagger_client.models.docker_run_log_docker_load import DockerRunLogDockerLoad -from lightly.openapi_generated.swagger_client.models.docker_run_log_level import DockerRunLogLevel -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState - -class DockerRunLogEntryDataBase(BaseModel): - """ - DockerRunLogEntryDataBase - """ - ts: Optional[conint(strict=True, ge=0)] = Field(None, description="unix timestamp in milliseconds") - level: Optional[DockerRunLogLevel] = None - group: Optional[StrictStr] = Field(None, description="The logger name/group of the log entry.") - origin: Optional[StrictStr] = Field(None, description="The origin/filename+loc from where a log entry was created from.") - msg: Optional[StrictStr] = Field(None, description="The actual log message.") - state: Optional[DockerRunState] = None - load: Optional[DockerRunLogDockerLoad] = None - __properties = ["ts", "level", "group", "origin", "msg", "state", "load"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunLogEntryDataBase: - """Create an instance of DockerRunLogEntryDataBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of load - if self.load: - _dict['load' if by_alias else 'load'] = self.load.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunLogEntryDataBase: - """Create an instance of DockerRunLogEntryDataBase from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunLogEntryDataBase.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunLogEntryDataBase) in the input: " + str(obj)) - - _obj = DockerRunLogEntryDataBase.parse_obj({ - "ts": obj.get("ts"), - "level": obj.get("level"), - "group": obj.get("group"), - "origin": obj.get("origin"), - "msg": obj.get("msg"), - "state": obj.get("state"), - "load": DockerRunLogDockerLoad.from_dict(obj.get("load")) if obj.get("load") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_log_level.py b/lightly/openapi_generated/swagger_client/models/docker_run_log_level.py deleted file mode 100644 index a4967dab3..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_log_level.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunLogLevel(str, Enum): - """ - DockerRunLogLevel - """ - - """ - allowed enum values - """ - VERBOSE = 'VERBOSE' - DEBUG = 'DEBUG' - INFO = 'INFO' - WARN = 'WARN' - ERROR = 'ERROR' - CRITICAL = 'CRITICAL' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunLogLevel': - """Create an instance of DockerRunLogLevel from a JSON string""" - return DockerRunLogLevel(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_create_request.py deleted file mode 100644 index d7b9bbae8..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_create_request.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_priority import DockerRunScheduledPriority - -class DockerRunScheduledCreateRequest(BaseModel): - """ - DockerRunScheduledCreateRequest - """ - config_id: constr(strict=True) = Field(..., alias="configId", description="MongoDB ObjectId") - priority: DockerRunScheduledPriority = Field(...) - runs_on: Optional[conlist(StrictStr)] = Field(None, alias="runsOn", description="The labels used for specifying the run-worker-relationship") - creator: Optional[Creator] = None - __properties = ["configId", "priority", "runsOn", "creator"] - - @validator('config_id') - def config_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunScheduledCreateRequest: - """Create an instance of DockerRunScheduledCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunScheduledCreateRequest: - """Create an instance of DockerRunScheduledCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunScheduledCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunScheduledCreateRequest) in the input: " + str(obj)) - - _obj = DockerRunScheduledCreateRequest.parse_obj({ - "config_id": obj.get("configId"), - "priority": obj.get("priority"), - "runs_on": obj.get("runsOn"), - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_data.py b/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_data.py deleted file mode 100644 index f6d3fcb91..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_data.py +++ /dev/null @@ -1,129 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_priority import DockerRunScheduledPriority -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_state import DockerRunScheduledState - -class DockerRunScheduledData(BaseModel): - """ - DockerRunScheduledData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: constr(strict=True) = Field(..., alias="datasetId", description="MongoDB ObjectId") - user_id: Optional[StrictStr] = Field(None, alias="userId") - config_id: constr(strict=True) = Field(..., alias="configId", description="MongoDB ObjectId") - priority: DockerRunScheduledPriority = Field(...) - runs_on: conlist(StrictStr) = Field(..., alias="runsOn", description="The labels used for specifying the run-worker-relationship") - state: DockerRunScheduledState = Field(...) - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - owner: Optional[constr(strict=True)] = Field(None, description="MongoDB ObjectId") - __properties = ["id", "datasetId", "userId", "configId", "priority", "runsOn", "state", "createdAt", "lastModifiedAt", "owner"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('config_id') - def config_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('owner') - def owner_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunScheduledData: - """Create an instance of DockerRunScheduledData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunScheduledData: - """Create an instance of DockerRunScheduledData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunScheduledData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunScheduledData) in the input: " + str(obj)) - - _obj = DockerRunScheduledData.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "user_id": obj.get("userId"), - "config_id": obj.get("configId"), - "priority": obj.get("priority"), - "runs_on": obj.get("runsOn"), - "state": obj.get("state"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "owner": obj.get("owner") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_priority.py b/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_priority.py deleted file mode 100644 index 8f59946a2..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_priority.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunScheduledPriority(str, Enum): - """ - DockerRunScheduledPriority - """ - - """ - allowed enum values - """ - LOW = 'LOW' - MID = 'MID' - HIGH = 'HIGH' - CRITICAL = 'CRITICAL' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunScheduledPriority': - """Create an instance of DockerRunScheduledPriority from a JSON string""" - return DockerRunScheduledPriority(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_state.py b/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_state.py deleted file mode 100644 index cd7e2abbf..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_state.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunScheduledState(str, Enum): - """ - DockerRunScheduledState - """ - - """ - allowed enum values - """ - OPEN = 'OPEN' - LOCKED = 'LOCKED' - DONE = 'DONE' - CANCELED = 'CANCELED' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunScheduledState': - """Create an instance of DockerRunScheduledState from a JSON string""" - return DockerRunScheduledState(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_update_request.py b/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_update_request.py deleted file mode 100644 index 020d715f6..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_scheduled_update_request.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_priority import DockerRunScheduledPriority -from lightly.openapi_generated.swagger_client.models.docker_run_scheduled_state import DockerRunScheduledState - -class DockerRunScheduledUpdateRequest(BaseModel): - """ - DockerRunScheduledUpdateRequest - """ - state: DockerRunScheduledState = Field(...) - priority: Optional[DockerRunScheduledPriority] = None - runs_on: Optional[conlist(StrictStr)] = Field(None, alias="runsOn", description="The labels used for specifying the run-worker-relationship") - __properties = ["state", "priority", "runsOn"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunScheduledUpdateRequest: - """Create an instance of DockerRunScheduledUpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunScheduledUpdateRequest: - """Create an instance of DockerRunScheduledUpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunScheduledUpdateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunScheduledUpdateRequest) in the input: " + str(obj)) - - _obj = DockerRunScheduledUpdateRequest.parse_obj({ - "state": obj.get("state"), - "priority": obj.get("priority"), - "runs_on": obj.get("runsOn") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_state.py b/lightly/openapi_generated/swagger_client/models/docker_run_state.py deleted file mode 100644 index cce149e4c..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_state.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerRunState(str, Enum): - """ - DockerRunState - """ - - """ - allowed enum values - """ - STARTED = 'STARTED' - INITIALIZING = 'INITIALIZING' - LOADING_DATASET = 'LOADING_DATASET' - LOADING_PREDICTION = 'LOADING_PREDICTION' - CHECKING_CORRUPTNESS = 'CHECKING_CORRUPTNESS' - INITIALIZING_OBJECT_CROPS = 'INITIALIZING_OBJECT_CROPS' - LOADING_METADATA = 'LOADING_METADATA' - COMPUTING_METADATA = 'COMPUTING_METADATA' - TRAINING = 'TRAINING' - EMBEDDING = 'EMBEDDING' - EMBEDDING_OBJECT_CROPS = 'EMBEDDING_OBJECT_CROPS' - PRETAGGING = 'PRETAGGING' - COMPUTING_ACTIVE_LEARNING_SCORES = 'COMPUTING_ACTIVE_LEARNING_SCORES' - SAMPLING = 'SAMPLING' - EMBEDDING_FULL_IMAGES = 'EMBEDDING_FULL_IMAGES' - SAVING_RESULTS = 'SAVING_RESULTS' - UPLOADING_DATASET = 'UPLOADING_DATASET' - GENERATING_REPORT = 'GENERATING_REPORT' - UPLOADING_REPORT = 'UPLOADING_REPORT' - UPLOADED_REPORT = 'UPLOADED_REPORT' - UPLOADING_ARTIFACTS = 'UPLOADING_ARTIFACTS' - UPLOADED_ARTIFACTS = 'UPLOADED_ARTIFACTS' - COMPLETED = 'COMPLETED' - FAILED = 'FAILED' - CRASHED = 'CRASHED' - ABORTED = 'ABORTED' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerRunState': - """Create an instance of DockerRunState from a JSON string""" - return DockerRunState(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_run_update_request.py b/lightly/openapi_generated/swagger_client/models/docker_run_update_request.py deleted file mode 100644 index 159e52e26..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_run_update_request.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.docker_run_state import DockerRunState - -class DockerRunUpdateRequest(BaseModel): - """ - DockerRunUpdateRequest - """ - state: DockerRunState = Field(...) - message: Optional[StrictStr] = None - __properties = ["state", "message"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerRunUpdateRequest: - """Create an instance of DockerRunUpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerRunUpdateRequest: - """Create an instance of DockerRunUpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerRunUpdateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerRunUpdateRequest) in the input: " + str(obj)) - - _obj = DockerRunUpdateRequest.parse_obj({ - "state": obj.get("state"), - "message": obj.get("message") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_task_description.py b/lightly/openapi_generated/swagger_client/models/docker_task_description.py deleted file mode 100644 index c24b3eaa3..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_task_description.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Union -from pydantic import Extra, BaseModel, Field, StrictStr, confloat, conint -from lightly.openapi_generated.swagger_client.models.sampling_config import SamplingConfig -from lightly.openapi_generated.swagger_client.models.sampling_method import SamplingMethod - -class DockerTaskDescription(BaseModel): - """ - DockerTaskDescription - """ - embeddings_filename: StrictStr = Field(..., alias="embeddingsFilename") - embeddings_hash: StrictStr = Field(..., alias="embeddingsHash") - method: SamplingMethod = Field(...) - existing_selection_column_name: StrictStr = Field(..., alias="existingSelectionColumnName") - active_learning_scores_column_name: StrictStr = Field(..., alias="activeLearningScoresColumnName") - masked_out_column_name: StrictStr = Field(..., alias="maskedOutColumnName") - sampling_config: SamplingConfig = Field(..., alias="samplingConfig") - n_data: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(..., alias="nData", description="the number of samples in the current embeddings file") - __properties = ["embeddingsFilename", "embeddingsHash", "method", "existingSelectionColumnName", "activeLearningScoresColumnName", "maskedOutColumnName", "samplingConfig", "nData"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerTaskDescription: - """Create an instance of DockerTaskDescription from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sampling_config - if self.sampling_config: - _dict['samplingConfig' if by_alias else 'sampling_config'] = self.sampling_config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerTaskDescription: - """Create an instance of DockerTaskDescription from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerTaskDescription.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerTaskDescription) in the input: " + str(obj)) - - _obj = DockerTaskDescription.parse_obj({ - "embeddings_filename": obj.get("embeddingsFilename"), - "embeddings_hash": obj.get("embeddingsHash"), - "method": obj.get("method"), - "existing_selection_column_name": obj.get("existingSelectionColumnName"), - "active_learning_scores_column_name": obj.get("activeLearningScoresColumnName"), - "masked_out_column_name": obj.get("maskedOutColumnName"), - "sampling_config": SamplingConfig.from_dict(obj.get("samplingConfig")) if obj.get("samplingConfig") is not None else None, - "n_data": obj.get("nData") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_user_stats.py b/lightly/openapi_generated/swagger_client/models/docker_user_stats.py deleted file mode 100644 index 424f9b9be..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_user_stats.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict -from pydantic import Extra, BaseModel, Field, StrictStr, conint - -class DockerUserStats(BaseModel): - """ - DockerUserStats - """ - run_id: StrictStr = Field(..., alias="runId") - action: StrictStr = Field(...) - data: Dict[str, Any] = Field(...) - timestamp: conint(strict=True, ge=0) = Field(..., description="unix timestamp in milliseconds") - pip_version: StrictStr = Field(..., alias="pipVersion") - docker_version: StrictStr = Field(..., alias="dockerVersion") - __properties = ["runId", "action", "data", "timestamp", "pipVersion", "dockerVersion"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerUserStats: - """Create an instance of DockerUserStats from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerUserStats: - """Create an instance of DockerUserStats from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerUserStats.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerUserStats) in the input: " + str(obj)) - - _obj = DockerUserStats.parse_obj({ - "run_id": obj.get("runId"), - "action": obj.get("action"), - "data": obj.get("data"), - "timestamp": obj.get("timestamp"), - "pip_version": obj.get("pipVersion"), - "docker_version": obj.get("dockerVersion") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_authorization_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_authorization_request.py deleted file mode 100644 index 35c99fc5b..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_authorization_request.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class DockerWorkerAuthorizationRequest(BaseModel): - """ - DockerWorkerAuthorizationRequest - """ - hashed_task_description: StrictStr = Field(..., alias="hashedTaskDescription") - __properties = ["hashedTaskDescription"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerAuthorizationRequest: - """Create an instance of DockerWorkerAuthorizationRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerAuthorizationRequest: - """Create an instance of DockerWorkerAuthorizationRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerAuthorizationRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerAuthorizationRequest) in the input: " + str(obj)) - - _obj = DockerWorkerAuthorizationRequest.parse_obj({ - "hashed_task_description": obj.get("hashedTaskDescription") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config.py deleted file mode 100644 index ecd36cabe..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.selection_config import SelectionConfig - -class DockerWorkerConfig(BaseModel): - """ - DockerWorkerConfig - """ - worker_type: DockerWorkerType = Field(..., alias="workerType") - docker: Optional[Dict[str, Any]] = Field(None, description="docker run configurations, keys should match the structure of https://github.com/lightly-ai/lightly-core/blob/develop/onprem-docker/lightly_worker/src/lightly_worker/resources/docker/docker.yaml ") - lightly: Optional[Dict[str, Any]] = Field(None, description="lightly configurations which are passed to a docker run, keys should match structure of https://github.com/lightly-ai/lightly/blob/master/lightly/cli/config/config.yaml ") - selection: Optional[SelectionConfig] = None - __properties = ["workerType", "docker", "lightly", "selection"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfig: - """Create an instance of DockerWorkerConfig from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of selection - if self.selection: - _dict['selection' if by_alias else 'selection'] = self.selection.to_dict(by_alias=by_alias) - # set to None if docker (nullable) is None - # and __fields_set__ contains the field - if self.docker is None and "docker" in self.__fields_set__: - _dict['docker' if by_alias else 'docker'] = None - - # set to None if lightly (nullable) is None - # and __fields_set__ contains the field - if self.lightly is None and "lightly" in self.__fields_set__: - _dict['lightly' if by_alias else 'lightly'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfig: - """Create an instance of DockerWorkerConfig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfig.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfig) in the input: " + str(obj)) - - _obj = DockerWorkerConfig.parse_obj({ - "worker_type": obj.get("workerType"), - "docker": obj.get("docker"), - "lightly": obj.get("lightly"), - "selection": SelectionConfig.from_dict(obj.get("selection")) if obj.get("selection") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_create_request.py deleted file mode 100644 index d870fffa4..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.docker_worker_config import DockerWorkerConfig - -class DockerWorkerConfigCreateRequest(BaseModel): - """ - DockerWorkerConfigCreateRequest - """ - config: DockerWorkerConfig = Field(...) - creator: Optional[Creator] = None - __properties = ["config", "creator"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigCreateRequest: - """Create an instance of DockerWorkerConfigCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigCreateRequest: - """Create an instance of DockerWorkerConfigCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigCreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigCreateRequest.parse_obj({ - "config": DockerWorkerConfig.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request.py deleted file mode 100644 index c67a7b5ff..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request_base import DockerWorkerConfigOmniVXCreateRequestBase -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 - -class DockerWorkerConfigOmniV2CreateRequest(DockerWorkerConfigOmniVXCreateRequestBase): - """ - DockerWorkerConfigOmniV2CreateRequest - """ - config: DockerWorkerConfigV2 = Field(...) - __properties = ["version", "creator", "config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV2CreateRequest: - """Create an instance of DockerWorkerConfigOmniV2CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV2CreateRequest: - """Create an instance of DockerWorkerConfigOmniV2CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV2CreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV2CreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV2CreateRequest.parse_obj({ - "version": obj.get("version"), - "creator": obj.get("creator"), - "config": DockerWorkerConfigV2.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request_all_of.py deleted file mode 100644 index 444754607..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v2_create_request_all_of.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 - -class DockerWorkerConfigOmniV2CreateRequestAllOf(BaseModel): - """ - DockerWorkerConfigOmniV2CreateRequestAllOf - """ - config: DockerWorkerConfigV2 = Field(...) - __properties = ["config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV2CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV2CreateRequestAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV2CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV2CreateRequestAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV2CreateRequestAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV2CreateRequestAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV2CreateRequestAllOf.parse_obj({ - "config": DockerWorkerConfigV2.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request.py deleted file mode 100644 index dcda1ca4e..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request_base import DockerWorkerConfigOmniVXCreateRequestBase -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 - -class DockerWorkerConfigOmniV3CreateRequest(DockerWorkerConfigOmniVXCreateRequestBase): - """ - DockerWorkerConfigOmniV3CreateRequest - """ - config: DockerWorkerConfigV3 = Field(...) - __properties = ["version", "creator", "config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV3CreateRequest: - """Create an instance of DockerWorkerConfigOmniV3CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV3CreateRequest: - """Create an instance of DockerWorkerConfigOmniV3CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV3CreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV3CreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV3CreateRequest.parse_obj({ - "version": obj.get("version"), - "creator": obj.get("creator"), - "config": DockerWorkerConfigV3.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request_all_of.py deleted file mode 100644 index 8d6f62f53..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v3_create_request_all_of.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 - -class DockerWorkerConfigOmniV3CreateRequestAllOf(BaseModel): - """ - DockerWorkerConfigOmniV3CreateRequestAllOf - """ - config: DockerWorkerConfigV3 = Field(...) - __properties = ["config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV3CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV3CreateRequestAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV3CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV3CreateRequestAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV3CreateRequestAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV3CreateRequestAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV3CreateRequestAllOf.parse_obj({ - "config": DockerWorkerConfigV3.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request.py deleted file mode 100644 index c8ca135f6..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_vx_create_request_base import DockerWorkerConfigOmniVXCreateRequestBase -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 - -class DockerWorkerConfigOmniV4CreateRequest(DockerWorkerConfigOmniVXCreateRequestBase): - """ - DockerWorkerConfigOmniV4CreateRequest - """ - config: DockerWorkerConfigV4 = Field(...) - __properties = ["version", "creator", "config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV4CreateRequest: - """Create an instance of DockerWorkerConfigOmniV4CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV4CreateRequest: - """Create an instance of DockerWorkerConfigOmniV4CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV4CreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV4CreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV4CreateRequest.parse_obj({ - "version": obj.get("version"), - "creator": obj.get("creator"), - "config": DockerWorkerConfigV4.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request_all_of.py deleted file mode 100644 index 950fef7cd..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_v4_create_request_all_of.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 - -class DockerWorkerConfigOmniV4CreateRequestAllOf(BaseModel): - """ - DockerWorkerConfigOmniV4CreateRequestAllOf - """ - config: DockerWorkerConfigV4 = Field(...) - __properties = ["config"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniV4CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV4CreateRequestAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniV4CreateRequestAllOf: - """Create an instance of DockerWorkerConfigOmniV4CreateRequestAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigOmniV4CreateRequestAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigOmniV4CreateRequestAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigOmniV4CreateRequestAllOf.parse_obj({ - "config": DockerWorkerConfigV4.from_dict(obj.get("config")) if obj.get("config") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request.py deleted file mode 100644 index 01303511b..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v2_create_request import DockerWorkerConfigOmniV2CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v3_create_request import DockerWorkerConfigOmniV3CreateRequest -from lightly.openapi_generated.swagger_client.models.docker_worker_config_omni_v4_create_request import DockerWorkerConfigOmniV4CreateRequest -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -DOCKERWORKERCONFIGOMNIVXCREATEREQUEST_ONE_OF_SCHEMAS = ["DockerWorkerConfigOmniV2CreateRequest", "DockerWorkerConfigOmniV3CreateRequest", "DockerWorkerConfigOmniV4CreateRequest"] - -class DockerWorkerConfigOmniVXCreateRequest(BaseModel): - """ - DockerWorkerConfigOmniVXCreateRequest - """ - # data type: DockerWorkerConfigOmniV2CreateRequest - oneof_schema_1_validator: Optional[DockerWorkerConfigOmniV2CreateRequest] = None - # data type: DockerWorkerConfigOmniV3CreateRequest - oneof_schema_2_validator: Optional[DockerWorkerConfigOmniV3CreateRequest] = None - # data type: DockerWorkerConfigOmniV4CreateRequest - oneof_schema_3_validator: Optional[DockerWorkerConfigOmniV4CreateRequest] = None - actual_instance: Any - one_of_schemas: List[str] = Field(DOCKERWORKERCONFIGOMNIVXCREATEREQUEST_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - discriminator_value_class_map = { - } - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = DockerWorkerConfigOmniVXCreateRequest.construct() - error_messages = [] - match = 0 - # validate data type: DockerWorkerConfigOmniV2CreateRequest - if not isinstance(v, DockerWorkerConfigOmniV2CreateRequest): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigOmniV2CreateRequest`") - else: - match += 1 - # validate data type: DockerWorkerConfigOmniV3CreateRequest - if not isinstance(v, DockerWorkerConfigOmniV3CreateRequest): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigOmniV3CreateRequest`") - else: - match += 1 - # validate data type: DockerWorkerConfigOmniV4CreateRequest - if not isinstance(v, DockerWorkerConfigOmniV4CreateRequest): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigOmniV4CreateRequest`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in DockerWorkerConfigOmniVXCreateRequest with oneOf schemas: DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in DockerWorkerConfigOmniVXCreateRequest with oneOf schemas: DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigOmniVXCreateRequest: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigOmniVXCreateRequest: - """Returns the object represented by the json string""" - instance = DockerWorkerConfigOmniVXCreateRequest.construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("version") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `version` in the input.") - - # check if data type is `DockerWorkerConfigOmniV2CreateRequest` - if _data_type == "DockerWorkerConfigOmniV2CreateRequest": - instance.actual_instance = DockerWorkerConfigOmniV2CreateRequest.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigOmniV3CreateRequest` - if _data_type == "DockerWorkerConfigOmniV3CreateRequest": - instance.actual_instance = DockerWorkerConfigOmniV3CreateRequest.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigOmniV4CreateRequest` - if _data_type == "DockerWorkerConfigOmniV4CreateRequest": - instance.actual_instance = DockerWorkerConfigOmniV4CreateRequest.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigOmniV2CreateRequest` - if _data_type == "V2": - instance.actual_instance = DockerWorkerConfigOmniV2CreateRequest.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigOmniV3CreateRequest` - if _data_type == "V3": - instance.actual_instance = DockerWorkerConfigOmniV3CreateRequest.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigOmniV4CreateRequest` - if _data_type == "V4": - instance.actual_instance = DockerWorkerConfigOmniV4CreateRequest.from_json(json_str) - return instance - - # deserialize data into DockerWorkerConfigOmniV2CreateRequest - try: - instance.actual_instance = DockerWorkerConfigOmniV2CreateRequest.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DockerWorkerConfigOmniV3CreateRequest - try: - instance.actual_instance = DockerWorkerConfigOmniV3CreateRequest.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DockerWorkerConfigOmniV4CreateRequest - try: - instance.actual_instance = DockerWorkerConfigOmniV4CreateRequest.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into DockerWorkerConfigOmniVXCreateRequest with oneOf schemas: DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into DockerWorkerConfigOmniVXCreateRequest with oneOf schemas: DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request_base.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request_base.py deleted file mode 100644 index 1b415353e..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_omni_vx_create_request_base.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json -import lightly.openapi_generated.swagger_client.models - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.creator import Creator - -class DockerWorkerConfigOmniVXCreateRequestBase(BaseModel): - """ - DockerWorkerConfigOmniVXCreateRequestBase - """ - version: StrictStr = Field(..., description="The version of the config. Either V3, V4, etc.etc.") - creator: Optional[Creator] = None - __properties = ["version", "creator"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - # JSON field name that stores the object type - __discriminator_property_name = 'version' - - # discriminator mappings - __discriminator_value_class_map = { - 'DockerWorkerConfigOmniV2CreateRequest': 'DockerWorkerConfigOmniV2CreateRequest', - 'DockerWorkerConfigOmniV3CreateRequest': 'DockerWorkerConfigOmniV3CreateRequest', - 'DockerWorkerConfigOmniV4CreateRequest': 'DockerWorkerConfigOmniV4CreateRequest' - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Union(DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest): - """Create an instance of DockerWorkerConfigOmniVXCreateRequestBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Union(DockerWorkerConfigOmniV2CreateRequest, DockerWorkerConfigOmniV3CreateRequest, DockerWorkerConfigOmniV4CreateRequest): - """Create an instance of DockerWorkerConfigOmniVXCreateRequestBase from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = getattr(lightly.openapi_generated.swagger_client.models, object_type) - return klass.from_dict(obj) - else: - raise ValueError("DockerWorkerConfigOmniVXCreateRequestBase failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data.py deleted file mode 100644 index 25d9dfcd2..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config import DockerWorkerConfig -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase - -class DockerWorkerConfigV0Data(DockerWorkerConfigVXDataBase): - """ - DockerWorkerConfigV0Data - """ - config: DockerWorkerConfig = Field(...) - config_orig: Optional[DockerWorkerConfig] = Field(None, alias="configOrig") - __properties = ["id", "version", "createdAt", "config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV0Data: - """Create an instance of DockerWorkerConfigV0Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV0Data: - """Create an instance of DockerWorkerConfigV0Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV0Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV0Data) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV0Data.parse_obj({ - "id": obj.get("id"), - "version": obj.get("version"), - "created_at": obj.get("createdAt"), - "config": DockerWorkerConfig.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfig.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data_all_of.py deleted file mode 100644 index d81a7e7fa..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v0_data_all_of.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config import DockerWorkerConfig - -class DockerWorkerConfigV0DataAllOf(BaseModel): - """ - DockerWorkerConfigV0DataAllOf - """ - config: DockerWorkerConfig = Field(...) - config_orig: Optional[DockerWorkerConfig] = Field(None, alias="configOrig") - __properties = ["config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV0DataAllOf: - """Create an instance of DockerWorkerConfigV0DataAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV0DataAllOf: - """Create an instance of DockerWorkerConfigV0DataAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV0DataAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV0DataAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV0DataAllOf.parse_obj({ - "config": DockerWorkerConfig.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfig.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2.py deleted file mode 100644 index fae09fe66..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker import DockerWorkerConfigV2Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly import DockerWorkerConfigV2Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.selection_config import SelectionConfig - -class DockerWorkerConfigV2(BaseModel): - """ - DockerWorkerConfigV2 - """ - worker_type: DockerWorkerType = Field(..., alias="workerType") - docker: Optional[DockerWorkerConfigV2Docker] = None - lightly: Optional[DockerWorkerConfigV2Lightly] = None - selection: Optional[SelectionConfig] = None - __properties = ["workerType", "docker", "lightly", "selection"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2: - """Create an instance of DockerWorkerConfigV2 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of docker - if self.docker: - _dict['docker' if by_alias else 'docker'] = self.docker.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of lightly - if self.lightly: - _dict['lightly' if by_alias else 'lightly'] = self.lightly.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of selection - if self.selection: - _dict['selection' if by_alias else 'selection'] = self.selection.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2: - """Create an instance of DockerWorkerConfigV2 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2.parse_obj({ - "worker_type": obj.get("workerType"), - "docker": DockerWorkerConfigV2Docker.from_dict(obj.get("docker")) if obj.get("docker") is not None else None, - "lightly": DockerWorkerConfigV2Lightly.from_dict(obj.get("lightly")) if obj.get("lightly") is not None else None, - "selection": SelectionConfig.from_dict(obj.get("selection")) if obj.get("selection") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_create_request.py deleted file mode 100644 index ad2036832..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 - -class DockerWorkerConfigV2CreateRequest(BaseModel): - """ - DockerWorkerConfigV2CreateRequest - """ - config: DockerWorkerConfigV2 = Field(...) - creator: Optional[Creator] = None - __properties = ["config", "creator"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2CreateRequest: - """Create an instance of DockerWorkerConfigV2CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2CreateRequest: - """Create an instance of DockerWorkerConfigV2CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2CreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2CreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2CreateRequest.parse_obj({ - "config": DockerWorkerConfigV2.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data.py deleted file mode 100644 index 577246f58..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase - -class DockerWorkerConfigV2Data(DockerWorkerConfigVXDataBase): - """ - DockerWorkerConfigV2Data - """ - config: DockerWorkerConfigV2 = Field(...) - config_orig: Optional[DockerWorkerConfigV2] = Field(None, alias="configOrig") - __properties = ["id", "version", "createdAt", "config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2Data: - """Create an instance of DockerWorkerConfigV2Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2Data: - """Create an instance of DockerWorkerConfigV2Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2Data) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2Data.parse_obj({ - "id": obj.get("id"), - "version": obj.get("version"), - "created_at": obj.get("createdAt"), - "config": DockerWorkerConfigV2.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV2.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data_all_of.py deleted file mode 100644 index 310fe125c..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_data_all_of.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2 import DockerWorkerConfigV2 - -class DockerWorkerConfigV2DataAllOf(BaseModel): - """ - DockerWorkerConfigV2DataAllOf - """ - config: DockerWorkerConfigV2 = Field(...) - config_orig: Optional[DockerWorkerConfigV2] = Field(None, alias="configOrig") - __properties = ["config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2DataAllOf: - """Create an instance of DockerWorkerConfigV2DataAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2DataAllOf: - """Create an instance of DockerWorkerConfigV2DataAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2DataAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2DataAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2DataAllOf.parse_obj({ - "config": DockerWorkerConfigV2.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV2.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker.py deleted file mode 100644 index a51d7b892..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_datasource import DockerWorkerConfigV2DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_object_level import DockerWorkerConfigV2DockerObjectLevel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_docker_stopping_condition import DockerWorkerConfigV2DockerStoppingCondition -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_corruptness_check import DockerWorkerConfigV3DockerCorruptnessCheck -from lightly.openapi_generated.swagger_client.models.lightly_docker_selection_method import LightlyDockerSelectionMethod - -class DockerWorkerConfigV2Docker(BaseModel): - """ - docker run configurations, keys should match the structure of https://github.com/lightly-ai/lightly-core/blob/develop/onprem-docker/lightly_worker/src/lightly_worker/resources/docker/docker.yaml - """ - checkpoint: Optional[StrictStr] = None - corruptness_check: Optional[DockerWorkerConfigV3DockerCorruptnessCheck] = Field(None, alias="corruptnessCheck") - datasource: Optional[DockerWorkerConfigV2DockerDatasource] = None - embeddings: Optional[StrictStr] = None - enable_training: Optional[StrictBool] = Field(None, alias="enableTraining") - method: Optional[LightlyDockerSelectionMethod] = None - normalize_embeddings: Optional[StrictBool] = Field(None, alias="normalizeEmbeddings") - output_image_format: Optional[StrictStr] = Field(None, alias="outputImageFormat") - object_level: Optional[DockerWorkerConfigV2DockerObjectLevel] = Field(None, alias="objectLevel") - pretagging: Optional[StrictBool] = None - pretagging_upload: Optional[StrictBool] = Field(None, alias="pretaggingUpload") - relevant_filenames_file: Optional[StrictStr] = Field(None, alias="relevantFilenamesFile") - selected_sequence_length: Optional[conint(strict=True, ge=1)] = Field(None, alias="selectedSequenceLength") - stopping_condition: Optional[DockerWorkerConfigV2DockerStoppingCondition] = Field(None, alias="stoppingCondition") - upload_report: Optional[StrictBool] = Field(None, alias="uploadReport") - __properties = ["checkpoint", "corruptnessCheck", "datasource", "embeddings", "enableTraining", "method", "normalizeEmbeddings", "outputImageFormat", "objectLevel", "pretagging", "pretaggingUpload", "relevantFilenamesFile", "selectedSequenceLength", "stoppingCondition", "uploadReport"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2Docker: - """Create an instance of DockerWorkerConfigV2Docker from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of corruptness_check - if self.corruptness_check: - _dict['corruptnessCheck' if by_alias else 'corruptness_check'] = self.corruptness_check.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of datasource - if self.datasource: - _dict['datasource' if by_alias else 'datasource'] = self.datasource.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of object_level - if self.object_level: - _dict['objectLevel' if by_alias else 'object_level'] = self.object_level.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of stopping_condition - if self.stopping_condition: - _dict['stoppingCondition' if by_alias else 'stopping_condition'] = self.stopping_condition.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2Docker: - """Create an instance of DockerWorkerConfigV2Docker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2Docker.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2Docker) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2Docker.parse_obj({ - "checkpoint": obj.get("checkpoint"), - "corruptness_check": DockerWorkerConfigV3DockerCorruptnessCheck.from_dict(obj.get("corruptnessCheck")) if obj.get("corruptnessCheck") is not None else None, - "datasource": DockerWorkerConfigV2DockerDatasource.from_dict(obj.get("datasource")) if obj.get("datasource") is not None else None, - "embeddings": obj.get("embeddings"), - "enable_training": obj.get("enableTraining"), - "method": obj.get("method"), - "normalize_embeddings": obj.get("normalizeEmbeddings"), - "output_image_format": obj.get("outputImageFormat"), - "object_level": DockerWorkerConfigV2DockerObjectLevel.from_dict(obj.get("objectLevel")) if obj.get("objectLevel") is not None else None, - "pretagging": obj.get("pretagging"), - "pretagging_upload": obj.get("pretaggingUpload"), - "relevant_filenames_file": obj.get("relevantFilenamesFile"), - "selected_sequence_length": obj.get("selectedSequenceLength"), - "stopping_condition": DockerWorkerConfigV2DockerStoppingCondition.from_dict(obj.get("stoppingCondition")) if obj.get("stoppingCondition") is not None else None, - "upload_report": obj.get("uploadReport") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_datasource.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_datasource.py deleted file mode 100644 index df8f8fb14..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_datasource.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool - -class DockerWorkerConfigV2DockerDatasource(BaseModel): - """ - DockerWorkerConfigV2DockerDatasource - """ - bypass_verify: Optional[StrictBool] = Field(None, alias="bypassVerify") - enable_datapool_update: Optional[StrictBool] = Field(None, alias="enableDatapoolUpdate") - process_all: Optional[StrictBool] = Field(None, alias="processAll") - __properties = ["bypassVerify", "enableDatapoolUpdate", "processAll"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2DockerDatasource: - """Create an instance of DockerWorkerConfigV2DockerDatasource from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2DockerDatasource: - """Create an instance of DockerWorkerConfigV2DockerDatasource from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2DockerDatasource.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2DockerDatasource) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2DockerDatasource.parse_obj({ - "bypass_verify": obj.get("bypassVerify"), - "enable_datapool_update": obj.get("enableDatapoolUpdate"), - "process_all": obj.get("processAll") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_object_level.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_object_level.py deleted file mode 100644 index 9122bcb62..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_object_level.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, constr, validator - -class DockerWorkerConfigV2DockerObjectLevel(BaseModel): - """ - DockerWorkerConfigV2DockerObjectLevel - """ - crop_dataset_name: Optional[constr(strict=True)] = Field(None, alias="cropDatasetName", description="Identical limitations than DatasetName however it can be empty") - padding: Optional[Union[StrictFloat, StrictInt]] = None - task_name: Optional[constr(strict=True)] = Field(None, alias="taskName", description="Since we sometimes stitch together SelectionInputTask+ActiveLearningScoreType, they need to follow the same specs of ActiveLearningScoreType. However, this can be an empty string due to internal logic. ") - __properties = ["cropDatasetName", "padding", "taskName"] - - @validator('crop_dataset_name') - def crop_dataset_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9 _-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9 _-]*$/") - return value - - @validator('task_name') - def task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2DockerObjectLevel: - """Create an instance of DockerWorkerConfigV2DockerObjectLevel from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2DockerObjectLevel: - """Create an instance of DockerWorkerConfigV2DockerObjectLevel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2DockerObjectLevel.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2DockerObjectLevel) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2DockerObjectLevel.parse_obj({ - "crop_dataset_name": obj.get("cropDatasetName"), - "padding": obj.get("padding"), - "task_name": obj.get("taskName") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_stopping_condition.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_stopping_condition.py deleted file mode 100644 index c79cc5ed2..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_docker_stopping_condition.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt - -class DockerWorkerConfigV2DockerStoppingCondition(BaseModel): - """ - DockerWorkerConfigV2DockerStoppingCondition - """ - min_distance: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="minDistance") - n_samples: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="nSamples") - __properties = ["minDistance", "nSamples"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2DockerStoppingCondition: - """Create an instance of DockerWorkerConfigV2DockerStoppingCondition from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2DockerStoppingCondition: - """Create an instance of DockerWorkerConfigV2DockerStoppingCondition from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2DockerStoppingCondition.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2DockerStoppingCondition) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2DockerStoppingCondition.parse_obj({ - "min_distance": obj.get("minDistance"), - "n_samples": obj.get("nSamples") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly.py deleted file mode 100644 index a37201475..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_collate import DockerWorkerConfigV2LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_model import DockerWorkerConfigV2LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_lightly_trainer import DockerWorkerConfigV2LightlyTrainer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_criterion import DockerWorkerConfigV3LightlyCriterion -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_loader import DockerWorkerConfigV3LightlyLoader -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_optimizer import DockerWorkerConfigV3LightlyOptimizer - -class DockerWorkerConfigV2Lightly(BaseModel): - """ - Lightly configurations which are passed to a Lightly Worker run. For information about the options see https://docs.lightly.ai/docs/all-configuration-options#run-configuration. - """ - loader: Optional[DockerWorkerConfigV3LightlyLoader] = None - model: Optional[DockerWorkerConfigV2LightlyModel] = None - trainer: Optional[DockerWorkerConfigV2LightlyTrainer] = None - criterion: Optional[DockerWorkerConfigV3LightlyCriterion] = None - optimizer: Optional[DockerWorkerConfigV3LightlyOptimizer] = None - collate: Optional[DockerWorkerConfigV2LightlyCollate] = None - __properties = ["loader", "model", "trainer", "criterion", "optimizer", "collate"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2Lightly: - """Create an instance of DockerWorkerConfigV2Lightly from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of loader - if self.loader: - _dict['loader' if by_alias else 'loader'] = self.loader.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of model - if self.model: - _dict['model' if by_alias else 'model'] = self.model.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of trainer - if self.trainer: - _dict['trainer' if by_alias else 'trainer'] = self.trainer.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of criterion - if self.criterion: - _dict['criterion' if by_alias else 'criterion'] = self.criterion.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of optimizer - if self.optimizer: - _dict['optimizer' if by_alias else 'optimizer'] = self.optimizer.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of collate - if self.collate: - _dict['collate' if by_alias else 'collate'] = self.collate.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2Lightly: - """Create an instance of DockerWorkerConfigV2Lightly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2Lightly.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2Lightly) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2Lightly.parse_obj({ - "loader": DockerWorkerConfigV3LightlyLoader.from_dict(obj.get("loader")) if obj.get("loader") is not None else None, - "model": DockerWorkerConfigV2LightlyModel.from_dict(obj.get("model")) if obj.get("model") is not None else None, - "trainer": DockerWorkerConfigV2LightlyTrainer.from_dict(obj.get("trainer")) if obj.get("trainer") is not None else None, - "criterion": DockerWorkerConfigV3LightlyCriterion.from_dict(obj.get("criterion")) if obj.get("criterion") is not None else None, - "optimizer": DockerWorkerConfigV3LightlyOptimizer.from_dict(obj.get("optimizer")) if obj.get("optimizer") is not None else None, - "collate": DockerWorkerConfigV2LightlyCollate.from_dict(obj.get("collate")) if obj.get("collate") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_collate.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_collate.py deleted file mode 100644 index 0a3b20140..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_collate.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class DockerWorkerConfigV2LightlyCollate(BaseModel): - """ - DockerWorkerConfigV2LightlyCollate - """ - input_size: Optional[conint(strict=True, ge=1)] = Field(None, alias="inputSize") - cj_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjProb") - cj_bright: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjBright") - cj_contrast: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjContrast") - cj_sat: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjSat") - cj_hue: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjHue") - min_scale: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="minScale") - random_gray_scale: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="randomGrayScale") - gaussian_blur: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="gaussianBlur") - kernel_size: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="kernelSize") - sigmas: Optional[conlist(Union[confloat(gt=0, strict=True), conint(gt=0, strict=True)], max_items=2, min_items=2)] = None - vf_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="vfProb") - hf_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="hfProb") - rr_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="rrProb") - __properties = ["inputSize", "cjProb", "cjBright", "cjContrast", "cjSat", "cjHue", "minScale", "randomGrayScale", "gaussianBlur", "kernelSize", "sigmas", "vfProb", "hfProb", "rrProb"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2LightlyCollate: - """Create an instance of DockerWorkerConfigV2LightlyCollate from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2LightlyCollate: - """Create an instance of DockerWorkerConfigV2LightlyCollate from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2LightlyCollate.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2LightlyCollate) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2LightlyCollate.parse_obj({ - "input_size": obj.get("inputSize"), - "cj_prob": obj.get("cjProb"), - "cj_bright": obj.get("cjBright"), - "cj_contrast": obj.get("cjContrast"), - "cj_sat": obj.get("cjSat"), - "cj_hue": obj.get("cjHue"), - "min_scale": obj.get("minScale"), - "random_gray_scale": obj.get("randomGrayScale"), - "gaussian_blur": obj.get("gaussianBlur"), - "kernel_size": obj.get("kernelSize"), - "sigmas": obj.get("sigmas"), - "vf_prob": obj.get("vfProb"), - "hf_prob": obj.get("hfProb"), - "rr_prob": obj.get("rrProb") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_model.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_model.py deleted file mode 100644 index eec232631..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_model.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, conint -from lightly.openapi_generated.swagger_client.models.lightly_model_v2 import LightlyModelV2 - -class DockerWorkerConfigV2LightlyModel(BaseModel): - """ - DockerWorkerConfigV2LightlyModel - """ - name: Optional[LightlyModelV2] = None - out_dim: Optional[conint(strict=True, ge=1)] = Field(None, alias="outDim") - num_ftrs: Optional[conint(strict=True, ge=1)] = Field(None, alias="numFtrs") - width: Optional[conint(strict=True, ge=1)] = None - __properties = ["name", "outDim", "numFtrs", "width"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2LightlyModel: - """Create an instance of DockerWorkerConfigV2LightlyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2LightlyModel: - """Create an instance of DockerWorkerConfigV2LightlyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2LightlyModel.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2LightlyModel) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2LightlyModel.parse_obj({ - "name": obj.get("name"), - "out_dim": obj.get("outDim"), - "num_ftrs": obj.get("numFtrs"), - "width": obj.get("width") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_trainer.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_trainer.py deleted file mode 100644 index 7ae82b634..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v2_lightly_trainer.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, conint -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v2 import LightlyTrainerPrecisionV2 - -class DockerWorkerConfigV2LightlyTrainer(BaseModel): - """ - DockerWorkerConfigV2LightlyTrainer - """ - gpus: Optional[conint(strict=True, ge=0)] = None - max_epochs: Optional[conint(strict=True, ge=0)] = Field(None, alias="maxEpochs") - precision: Optional[LightlyTrainerPrecisionV2] = None - __properties = ["gpus", "maxEpochs", "precision"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV2LightlyTrainer: - """Create an instance of DockerWorkerConfigV2LightlyTrainer from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV2LightlyTrainer: - """Create an instance of DockerWorkerConfigV2LightlyTrainer from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV2LightlyTrainer.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV2LightlyTrainer) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV2LightlyTrainer.parse_obj({ - "gpus": obj.get("gpus"), - "max_epochs": obj.get("maxEpochs"), - "precision": obj.get("precision") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3.py deleted file mode 100644 index 4e5d1d8db..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker import DockerWorkerConfigV3Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly import DockerWorkerConfigV3Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.selection_config_v3 import SelectionConfigV3 - -class DockerWorkerConfigV3(BaseModel): - """ - DockerWorkerConfigV3 - """ - worker_type: DockerWorkerType = Field(..., alias="workerType") - docker: Optional[DockerWorkerConfigV3Docker] = None - lightly: Optional[DockerWorkerConfigV3Lightly] = None - selection: Optional[SelectionConfigV3] = None - __properties = ["workerType", "docker", "lightly", "selection"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3: - """Create an instance of DockerWorkerConfigV3 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of docker - if self.docker: - _dict['docker' if by_alias else 'docker'] = self.docker.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of lightly - if self.lightly: - _dict['lightly' if by_alias else 'lightly'] = self.lightly.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of selection - if self.selection: - _dict['selection' if by_alias else 'selection'] = self.selection.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3: - """Create an instance of DockerWorkerConfigV3 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3.parse_obj({ - "worker_type": obj.get("workerType"), - "docker": DockerWorkerConfigV3Docker.from_dict(obj.get("docker")) if obj.get("docker") is not None else None, - "lightly": DockerWorkerConfigV3Lightly.from_dict(obj.get("lightly")) if obj.get("lightly") is not None else None, - "selection": SelectionConfigV3.from_dict(obj.get("selection")) if obj.get("selection") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_create_request.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_create_request.py deleted file mode 100644 index 4891c3fca..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 - -class DockerWorkerConfigV3CreateRequest(BaseModel): - """ - DockerWorkerConfigV3CreateRequest - """ - config: DockerWorkerConfigV3 = Field(...) - creator: Optional[Creator] = None - __properties = ["config", "creator"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3CreateRequest: - """Create an instance of DockerWorkerConfigV3CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3CreateRequest: - """Create an instance of DockerWorkerConfigV3CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3CreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3CreateRequest) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3CreateRequest.parse_obj({ - "config": DockerWorkerConfigV3.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data.py deleted file mode 100644 index ea8bc7e57..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase - -class DockerWorkerConfigV3Data(DockerWorkerConfigVXDataBase): - """ - DockerWorkerConfigV3Data - """ - config: DockerWorkerConfigV3 = Field(...) - config_orig: Optional[DockerWorkerConfigV3] = Field(None, alias="configOrig") - __properties = ["id", "version", "createdAt", "config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3Data: - """Create an instance of DockerWorkerConfigV3Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3Data: - """Create an instance of DockerWorkerConfigV3Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3Data) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3Data.parse_obj({ - "id": obj.get("id"), - "version": obj.get("version"), - "created_at": obj.get("createdAt"), - "config": DockerWorkerConfigV3.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV3.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data_all_of.py deleted file mode 100644 index e75f69be3..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_data_all_of.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3 import DockerWorkerConfigV3 - -class DockerWorkerConfigV3DataAllOf(BaseModel): - """ - DockerWorkerConfigV3DataAllOf - """ - config: DockerWorkerConfigV3 = Field(...) - config_orig: Optional[DockerWorkerConfigV3] = Field(None, alias="configOrig") - __properties = ["config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3DataAllOf: - """Create an instance of DockerWorkerConfigV3DataAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3DataAllOf: - """Create an instance of DockerWorkerConfigV3DataAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3DataAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3DataAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3DataAllOf.parse_obj({ - "config": DockerWorkerConfigV3.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV3.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_datasource_input_expiration.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_datasource_input_expiration.py deleted file mode 100644 index 3cb45c3dd..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_datasource_input_expiration.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Union -from pydantic import Extra, BaseModel, Field, confloat, conint -from lightly.openapi_generated.swagger_client.models.expiry_handling_strategy_v3 import ExpiryHandlingStrategyV3 - -class DockerWorkerConfigV3DatasourceInputExpiration(BaseModel): - """ - Images that expire in less than the specified number of days are handled specially. Given the handling strategy, these images are either skipped or the worker breaks if encountering any of them. - """ - min_days_to_expiration: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(..., alias="minDaysToExpiration") - handling_strategy: ExpiryHandlingStrategyV3 = Field(..., alias="handlingStrategy") - __properties = ["minDaysToExpiration", "handlingStrategy"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3DatasourceInputExpiration: - """Create an instance of DockerWorkerConfigV3DatasourceInputExpiration from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3DatasourceInputExpiration: - """Create an instance of DockerWorkerConfigV3DatasourceInputExpiration from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3DatasourceInputExpiration.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3DatasourceInputExpiration) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3DatasourceInputExpiration.parse_obj({ - "min_days_to_expiration": obj.get("minDaysToExpiration"), - "handling_strategy": obj.get("handlingStrategy") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker.py deleted file mode 100644 index 7a66eab2e..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_corruptness_check import DockerWorkerConfigV3DockerCorruptnessCheck -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_datasource import DockerWorkerConfigV3DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_training import DockerWorkerConfigV3DockerTraining - -class DockerWorkerConfigV3Docker(BaseModel): - """ - docker run configurations, keys should match the structure of https://github.com/lightly-ai/lightly-core/blob/develop/onprem-docker/lightly_worker/src/lightly_worker/resources/docker/docker.yaml - """ - checkpoint: Optional[StrictStr] = None - checkpoint_run_id: Optional[constr(strict=True)] = Field(None, alias="checkpointRunId", description="MongoDB ObjectId") - corruptness_check: Optional[DockerWorkerConfigV3DockerCorruptnessCheck] = Field(None, alias="corruptnessCheck") - datasource: Optional[DockerWorkerConfigV3DockerDatasource] = None - embeddings: Optional[StrictStr] = None - enable_training: Optional[StrictBool] = Field(None, alias="enableTraining") - training: Optional[DockerWorkerConfigV3DockerTraining] = None - normalize_embeddings: Optional[StrictBool] = Field(None, alias="normalizeEmbeddings") - num_processes: Optional[conint(strict=True, ge=-1)] = Field(None, alias="numProcesses") - num_threads: Optional[conint(strict=True, ge=-1)] = Field(None, alias="numThreads") - output_image_format: Optional[StrictStr] = Field(None, alias="outputImageFormat") - pretagging: Optional[StrictBool] = None - pretagging_upload: Optional[StrictBool] = Field(None, alias="pretaggingUpload") - relevant_filenames_file: Optional[StrictStr] = Field(None, alias="relevantFilenamesFile") - selected_sequence_length: Optional[conint(strict=True, ge=1)] = Field(None, alias="selectedSequenceLength") - upload_report: Optional[StrictBool] = Field(None, alias="uploadReport") - shutdown_when_job_finished: Optional[StrictBool] = Field(None, alias="shutdownWhenJobFinished") - __properties = ["checkpoint", "checkpointRunId", "corruptnessCheck", "datasource", "embeddings", "enableTraining", "training", "normalizeEmbeddings", "numProcesses", "numThreads", "outputImageFormat", "pretagging", "pretaggingUpload", "relevantFilenamesFile", "selectedSequenceLength", "uploadReport", "shutdownWhenJobFinished"] - - @validator('checkpoint_run_id') - def checkpoint_run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3Docker: - """Create an instance of DockerWorkerConfigV3Docker from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of corruptness_check - if self.corruptness_check: - _dict['corruptnessCheck' if by_alias else 'corruptness_check'] = self.corruptness_check.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of datasource - if self.datasource: - _dict['datasource' if by_alias else 'datasource'] = self.datasource.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of training - if self.training: - _dict['training' if by_alias else 'training'] = self.training.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3Docker: - """Create an instance of DockerWorkerConfigV3Docker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3Docker.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3Docker) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3Docker.parse_obj({ - "checkpoint": obj.get("checkpoint"), - "checkpoint_run_id": obj.get("checkpointRunId"), - "corruptness_check": DockerWorkerConfigV3DockerCorruptnessCheck.from_dict(obj.get("corruptnessCheck")) if obj.get("corruptnessCheck") is not None else None, - "datasource": DockerWorkerConfigV3DockerDatasource.from_dict(obj.get("datasource")) if obj.get("datasource") is not None else None, - "embeddings": obj.get("embeddings"), - "enable_training": obj.get("enableTraining"), - "training": DockerWorkerConfigV3DockerTraining.from_dict(obj.get("training")) if obj.get("training") is not None else None, - "normalize_embeddings": obj.get("normalizeEmbeddings"), - "num_processes": obj.get("numProcesses"), - "num_threads": obj.get("numThreads"), - "output_image_format": obj.get("outputImageFormat"), - "pretagging": obj.get("pretagging"), - "pretagging_upload": obj.get("pretaggingUpload"), - "relevant_filenames_file": obj.get("relevantFilenamesFile"), - "selected_sequence_length": obj.get("selectedSequenceLength"), - "upload_report": obj.get("uploadReport"), - "shutdown_when_job_finished": obj.get("shutdownWhenJobFinished") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_corruptness_check.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_corruptness_check.py deleted file mode 100644 index 5aeac4eb9..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_corruptness_check.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint - -class DockerWorkerConfigV3DockerCorruptnessCheck(BaseModel): - """ - DockerWorkerConfigV3DockerCorruptnessCheck - """ - corruption_threshold: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="corruptionThreshold") - __properties = ["corruptionThreshold"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3DockerCorruptnessCheck: - """Create an instance of DockerWorkerConfigV3DockerCorruptnessCheck from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3DockerCorruptnessCheck: - """Create an instance of DockerWorkerConfigV3DockerCorruptnessCheck from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3DockerCorruptnessCheck.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3DockerCorruptnessCheck) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3DockerCorruptnessCheck.parse_obj({ - "corruption_threshold": obj.get("corruptionThreshold") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_datasource.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_datasource.py deleted file mode 100644 index 28b425e3b..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_datasource.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_datasource_input_expiration import DockerWorkerConfigV3DatasourceInputExpiration - -class DockerWorkerConfigV3DockerDatasource(BaseModel): - """ - DockerWorkerConfigV3DockerDatasource - """ - bypass_verify: Optional[StrictBool] = Field(None, alias="bypassVerify") - enable_datapool_update: Optional[StrictBool] = Field(None, alias="enableDatapoolUpdate") - process_all: Optional[StrictBool] = Field(None, alias="processAll") - input_expiration: Optional[DockerWorkerConfigV3DatasourceInputExpiration] = Field(None, alias="inputExpiration") - __properties = ["bypassVerify", "enableDatapoolUpdate", "processAll", "inputExpiration"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3DockerDatasource: - """Create an instance of DockerWorkerConfigV3DockerDatasource from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of input_expiration - if self.input_expiration: - _dict['inputExpiration' if by_alias else 'input_expiration'] = self.input_expiration.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3DockerDatasource: - """Create an instance of DockerWorkerConfigV3DockerDatasource from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3DockerDatasource.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3DockerDatasource) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3DockerDatasource.parse_obj({ - "bypass_verify": obj.get("bypassVerify"), - "enable_datapool_update": obj.get("enableDatapoolUpdate"), - "process_all": obj.get("processAll"), - "input_expiration": DockerWorkerConfigV3DatasourceInputExpiration.from_dict(obj.get("inputExpiration")) if obj.get("inputExpiration") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_training.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_training.py deleted file mode 100644 index 2fba227c8..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_docker_training.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator - -class DockerWorkerConfigV3DockerTraining(BaseModel): - """ - DockerWorkerConfigV3DockerTraining - """ - task_name: Optional[constr(strict=True)] = Field(None, alias="taskName", description="Since we sometimes stitch together SelectionInputTask+ActiveLearningScoreType, they need to follow the same specs of ActiveLearningScoreType. However, this can be an empty string due to internal logic. ") - __properties = ["taskName"] - - @validator('task_name') - def task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3DockerTraining: - """Create an instance of DockerWorkerConfigV3DockerTraining from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3DockerTraining: - """Create an instance of DockerWorkerConfigV3DockerTraining from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3DockerTraining.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3DockerTraining) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3DockerTraining.parse_obj({ - "task_name": obj.get("taskName") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly.py deleted file mode 100644 index d6859f466..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly.py +++ /dev/null @@ -1,120 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictInt -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_checkpoint_callback import DockerWorkerConfigV3LightlyCheckpointCallback -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_collate import DockerWorkerConfigV3LightlyCollate -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_criterion import DockerWorkerConfigV3LightlyCriterion -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_loader import DockerWorkerConfigV3LightlyLoader -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_model import DockerWorkerConfigV3LightlyModel -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_optimizer import DockerWorkerConfigV3LightlyOptimizer -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly_trainer import DockerWorkerConfigV3LightlyTrainer - -class DockerWorkerConfigV3Lightly(BaseModel): - """ - Lightly configurations which are passed to a Lightly Worker run. For information about the options see https://docs.lightly.ai/docs/all-configuration-options#run-configuration. - """ - seed: Optional[StrictInt] = Field(None, description="Random seed.") - checkpoint_callback: Optional[DockerWorkerConfigV3LightlyCheckpointCallback] = Field(None, alias="checkpointCallback") - loader: Optional[DockerWorkerConfigV3LightlyLoader] = None - model: Optional[DockerWorkerConfigV3LightlyModel] = None - trainer: Optional[DockerWorkerConfigV3LightlyTrainer] = None - criterion: Optional[DockerWorkerConfigV3LightlyCriterion] = None - optimizer: Optional[DockerWorkerConfigV3LightlyOptimizer] = None - collate: Optional[DockerWorkerConfigV3LightlyCollate] = None - __properties = ["seed", "checkpointCallback", "loader", "model", "trainer", "criterion", "optimizer", "collate"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3Lightly: - """Create an instance of DockerWorkerConfigV3Lightly from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of checkpoint_callback - if self.checkpoint_callback: - _dict['checkpointCallback' if by_alias else 'checkpoint_callback'] = self.checkpoint_callback.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of loader - if self.loader: - _dict['loader' if by_alias else 'loader'] = self.loader.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of model - if self.model: - _dict['model' if by_alias else 'model'] = self.model.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of trainer - if self.trainer: - _dict['trainer' if by_alias else 'trainer'] = self.trainer.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of criterion - if self.criterion: - _dict['criterion' if by_alias else 'criterion'] = self.criterion.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of optimizer - if self.optimizer: - _dict['optimizer' if by_alias else 'optimizer'] = self.optimizer.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of collate - if self.collate: - _dict['collate' if by_alias else 'collate'] = self.collate.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3Lightly: - """Create an instance of DockerWorkerConfigV3Lightly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3Lightly.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3Lightly) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3Lightly.parse_obj({ - "seed": obj.get("seed"), - "checkpoint_callback": DockerWorkerConfigV3LightlyCheckpointCallback.from_dict(obj.get("checkpointCallback")) if obj.get("checkpointCallback") is not None else None, - "loader": DockerWorkerConfigV3LightlyLoader.from_dict(obj.get("loader")) if obj.get("loader") is not None else None, - "model": DockerWorkerConfigV3LightlyModel.from_dict(obj.get("model")) if obj.get("model") is not None else None, - "trainer": DockerWorkerConfigV3LightlyTrainer.from_dict(obj.get("trainer")) if obj.get("trainer") is not None else None, - "criterion": DockerWorkerConfigV3LightlyCriterion.from_dict(obj.get("criterion")) if obj.get("criterion") is not None else None, - "optimizer": DockerWorkerConfigV3LightlyOptimizer.from_dict(obj.get("optimizer")) if obj.get("optimizer") is not None else None, - "collate": DockerWorkerConfigV3LightlyCollate.from_dict(obj.get("collate")) if obj.get("collate") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_checkpoint_callback.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_checkpoint_callback.py deleted file mode 100644 index 1260ae5e6..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_checkpoint_callback.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool - -class DockerWorkerConfigV3LightlyCheckpointCallback(BaseModel): - """ - DockerWorkerConfigV3LightlyCheckpointCallback - """ - save_last: Optional[StrictBool] = Field(None, alias="saveLast", description="If True, the checkpoint from the last epoch is saved.") - __properties = ["saveLast"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyCheckpointCallback: - """Create an instance of DockerWorkerConfigV3LightlyCheckpointCallback from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyCheckpointCallback: - """Create an instance of DockerWorkerConfigV3LightlyCheckpointCallback from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyCheckpointCallback.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyCheckpointCallback) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyCheckpointCallback.parse_obj({ - "save_last": obj.get("saveLast") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_collate.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_collate.py deleted file mode 100644 index e75f4d394..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_collate.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, confloat, conint, conlist - -class DockerWorkerConfigV3LightlyCollate(BaseModel): - """ - DockerWorkerConfigV3LightlyCollate - """ - input_size: Optional[conint(strict=True, ge=1)] = Field(None, alias="inputSize") - cj_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjProb") - cj_bright: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjBright") - cj_contrast: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjContrast") - cj_sat: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjSat") - cj_hue: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="cjHue") - min_scale: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="minScale") - random_gray_scale: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="randomGrayScale") - gaussian_blur: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="gaussianBlur") - kernel_size: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="kernelSize") - sigmas: Optional[conlist(Union[confloat(gt=0, strict=True), conint(gt=0, strict=True)], max_items=2, min_items=2)] = None - vf_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="vfProb") - hf_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="hfProb") - rr_prob: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="rrProb") - rr_degrees: Optional[conlist(Union[StrictFloat, StrictInt], max_items=2, min_items=2)] = Field(None, alias="rrDegrees") - __properties = ["inputSize", "cjProb", "cjBright", "cjContrast", "cjSat", "cjHue", "minScale", "randomGrayScale", "gaussianBlur", "kernelSize", "sigmas", "vfProb", "hfProb", "rrProb", "rrDegrees"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyCollate: - """Create an instance of DockerWorkerConfigV3LightlyCollate from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # set to None if rr_degrees (nullable) is None - # and __fields_set__ contains the field - if self.rr_degrees is None and "rr_degrees" in self.__fields_set__: - _dict['rrDegrees' if by_alias else 'rr_degrees'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyCollate: - """Create an instance of DockerWorkerConfigV3LightlyCollate from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyCollate.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyCollate) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyCollate.parse_obj({ - "input_size": obj.get("inputSize"), - "cj_prob": obj.get("cjProb"), - "cj_bright": obj.get("cjBright"), - "cj_contrast": obj.get("cjContrast"), - "cj_sat": obj.get("cjSat"), - "cj_hue": obj.get("cjHue"), - "min_scale": obj.get("minScale"), - "random_gray_scale": obj.get("randomGrayScale"), - "gaussian_blur": obj.get("gaussianBlur"), - "kernel_size": obj.get("kernelSize"), - "sigmas": obj.get("sigmas"), - "vf_prob": obj.get("vfProb"), - "hf_prob": obj.get("hfProb"), - "rr_prob": obj.get("rrProb"), - "rr_degrees": obj.get("rrDegrees") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_criterion.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_criterion.py deleted file mode 100644 index 99e909834..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_criterion.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, confloat, conint - -class DockerWorkerConfigV3LightlyCriterion(BaseModel): - """ - DockerWorkerConfigV3LightlyCriterion - """ - temperature: Optional[Union[confloat(gt=0.0, strict=True), conint(gt=0, strict=True)]] = None - __properties = ["temperature"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyCriterion: - """Create an instance of DockerWorkerConfigV3LightlyCriterion from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyCriterion: - """Create an instance of DockerWorkerConfigV3LightlyCriterion from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyCriterion.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyCriterion) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyCriterion.parse_obj({ - "temperature": obj.get("temperature") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_loader.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_loader.py deleted file mode 100644 index 99e3fcdb1..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_loader.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, conint - -class DockerWorkerConfigV3LightlyLoader(BaseModel): - """ - DockerWorkerConfigV3LightlyLoader - """ - batch_size: Optional[conint(strict=True, ge=1)] = Field(None, alias="batchSize") - shuffle: Optional[StrictBool] = None - num_workers: Optional[conint(strict=True, ge=-1)] = Field(None, alias="numWorkers") - drop_last: Optional[StrictBool] = Field(None, alias="dropLast") - __properties = ["batchSize", "shuffle", "numWorkers", "dropLast"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyLoader: - """Create an instance of DockerWorkerConfigV3LightlyLoader from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyLoader: - """Create an instance of DockerWorkerConfigV3LightlyLoader from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyLoader.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyLoader) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyLoader.parse_obj({ - "batch_size": obj.get("batchSize"), - "shuffle": obj.get("shuffle"), - "num_workers": obj.get("numWorkers"), - "drop_last": obj.get("dropLast") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_model.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_model.py deleted file mode 100644 index a63807186..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_model.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, conint -from lightly.openapi_generated.swagger_client.models.lightly_model_v3 import LightlyModelV3 - -class DockerWorkerConfigV3LightlyModel(BaseModel): - """ - DockerWorkerConfigV3LightlyModel - """ - name: Optional[LightlyModelV3] = None - out_dim: Optional[conint(strict=True, ge=1)] = Field(None, alias="outDim") - num_ftrs: Optional[conint(strict=True, ge=1)] = Field(None, alias="numFtrs") - width: Optional[conint(strict=True, ge=1)] = None - __properties = ["name", "outDim", "numFtrs", "width"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyModel: - """Create an instance of DockerWorkerConfigV3LightlyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyModel: - """Create an instance of DockerWorkerConfigV3LightlyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyModel.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyModel) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyModel.parse_obj({ - "name": obj.get("name"), - "out_dim": obj.get("outDim"), - "num_ftrs": obj.get("numFtrs"), - "width": obj.get("width") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_optimizer.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_optimizer.py deleted file mode 100644 index e3ead37ff..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_optimizer.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint - -class DockerWorkerConfigV3LightlyOptimizer(BaseModel): - """ - DockerWorkerConfigV3LightlyOptimizer - """ - lr: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = None - weight_decay: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="weightDecay") - __properties = ["lr", "weightDecay"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyOptimizer: - """Create an instance of DockerWorkerConfigV3LightlyOptimizer from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyOptimizer: - """Create an instance of DockerWorkerConfigV3LightlyOptimizer from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyOptimizer.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyOptimizer) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyOptimizer.parse_obj({ - "lr": obj.get("lr"), - "weight_decay": obj.get("weightDecay") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_trainer.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_trainer.py deleted file mode 100644 index 5cf388cef..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v3_lightly_trainer.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, conint -from lightly.openapi_generated.swagger_client.models.lightly_trainer_precision_v3 import LightlyTrainerPrecisionV3 - -class DockerWorkerConfigV3LightlyTrainer(BaseModel): - """ - DockerWorkerConfigV3LightlyTrainer - """ - gpus: Optional[conint(strict=True, ge=0)] = None - max_epochs: Optional[conint(strict=True, ge=0)] = Field(None, alias="maxEpochs") - precision: Optional[LightlyTrainerPrecisionV3] = None - __properties = ["gpus", "maxEpochs", "precision"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV3LightlyTrainer: - """Create an instance of DockerWorkerConfigV3LightlyTrainer from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV3LightlyTrainer: - """Create an instance of DockerWorkerConfigV3LightlyTrainer from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV3LightlyTrainer.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV3LightlyTrainer) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV3LightlyTrainer.parse_obj({ - "gpus": obj.get("gpus"), - "max_epochs": obj.get("maxEpochs"), - "precision": obj.get("precision") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4.py deleted file mode 100644 index 678612140..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_lightly import DockerWorkerConfigV3Lightly -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_docker import DockerWorkerConfigV4Docker -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType -from lightly.openapi_generated.swagger_client.models.selection_config_v4 import SelectionConfigV4 - -class DockerWorkerConfigV4(BaseModel): - """ - DockerWorkerConfigV4 - """ - worker_type: DockerWorkerType = Field(..., alias="workerType") - docker: Optional[DockerWorkerConfigV4Docker] = None - lightly: Optional[DockerWorkerConfigV3Lightly] = None - selection: Optional[SelectionConfigV4] = None - __properties = ["workerType", "docker", "lightly", "selection"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV4: - """Create an instance of DockerWorkerConfigV4 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of docker - if self.docker: - _dict['docker' if by_alias else 'docker'] = self.docker.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of lightly - if self.lightly: - _dict['lightly' if by_alias else 'lightly'] = self.lightly.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of selection - if self.selection: - _dict['selection' if by_alias else 'selection'] = self.selection.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV4: - """Create an instance of DockerWorkerConfigV4 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV4.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV4) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV4.parse_obj({ - "worker_type": obj.get("workerType"), - "docker": DockerWorkerConfigV4Docker.from_dict(obj.get("docker")) if obj.get("docker") is not None else None, - "lightly": DockerWorkerConfigV3Lightly.from_dict(obj.get("lightly")) if obj.get("lightly") is not None else None, - "selection": SelectionConfigV4.from_dict(obj.get("selection")) if obj.get("selection") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data.py deleted file mode 100644 index faa7fe8be..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 -from lightly.openapi_generated.swagger_client.models.docker_worker_config_vx_data_base import DockerWorkerConfigVXDataBase - -class DockerWorkerConfigV4Data(DockerWorkerConfigVXDataBase): - """ - DockerWorkerConfigV4Data - """ - config: DockerWorkerConfigV4 = Field(...) - config_orig: Optional[DockerWorkerConfigV4] = Field(None, alias="configOrig") - __properties = ["id", "version", "createdAt", "config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV4Data: - """Create an instance of DockerWorkerConfigV4Data from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV4Data: - """Create an instance of DockerWorkerConfigV4Data from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV4Data.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV4Data) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV4Data.parse_obj({ - "id": obj.get("id"), - "version": obj.get("version"), - "created_at": obj.get("createdAt"), - "config": DockerWorkerConfigV4.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV4.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data_all_of.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data_all_of.py deleted file mode 100644 index 34a47fb43..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_data_all_of.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4 import DockerWorkerConfigV4 - -class DockerWorkerConfigV4DataAllOf(BaseModel): - """ - DockerWorkerConfigV4DataAllOf - """ - config: DockerWorkerConfigV4 = Field(...) - config_orig: Optional[DockerWorkerConfigV4] = Field(None, alias="configOrig") - __properties = ["config", "configOrig"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV4DataAllOf: - """Create an instance of DockerWorkerConfigV4DataAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of config_orig - if self.config_orig: - _dict['configOrig' if by_alias else 'config_orig'] = self.config_orig.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV4DataAllOf: - """Create an instance of DockerWorkerConfigV4DataAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV4DataAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV4DataAllOf) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV4DataAllOf.parse_obj({ - "config": DockerWorkerConfigV4.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "config_orig": DockerWorkerConfigV4.from_dict(obj.get("configOrig")) if obj.get("configOrig") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_docker.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_docker.py deleted file mode 100644 index b1d5d55ec..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_v4_docker.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_corruptness_check import DockerWorkerConfigV3DockerCorruptnessCheck -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_datasource import DockerWorkerConfigV3DockerDatasource -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_docker_training import DockerWorkerConfigV3DockerTraining - -class DockerWorkerConfigV4Docker(BaseModel): - """ - docker run configurations, keys should match the structure of https://github.com/lightly-ai/lightly-core/blob/develop/onprem-docker/lightly_worker/src/lightly_worker/resources/docker/docker.yaml - """ - checkpoint: Optional[StrictStr] = None - checkpoint_run_id: Optional[constr(strict=True)] = Field(None, alias="checkpointRunId", description="MongoDB ObjectId") - corruptness_check: Optional[DockerWorkerConfigV3DockerCorruptnessCheck] = Field(None, alias="corruptnessCheck") - datasource: Optional[DockerWorkerConfigV3DockerDatasource] = None - embeddings: Optional[StrictStr] = None - enable_training: Optional[StrictBool] = Field(None, alias="enableTraining") - training: Optional[DockerWorkerConfigV3DockerTraining] = None - normalize_embeddings: Optional[StrictBool] = Field(None, alias="normalizeEmbeddings") - num_processes: Optional[conint(strict=True, ge=-1)] = Field(None, alias="numProcesses") - num_threads: Optional[conint(strict=True, ge=-1)] = Field(None, alias="numThreads") - output_image_format: Optional[StrictStr] = Field(None, alias="outputImageFormat") - pretagging: Optional[StrictBool] = None - pretagging_upload: Optional[StrictBool] = Field(None, alias="pretaggingUpload") - relevant_filenames_file: Optional[StrictStr] = Field(None, alias="relevantFilenamesFile") - selected_sequence_length: Optional[conint(strict=True, ge=1)] = Field(None, alias="selectedSequenceLength") - upload_report: Optional[StrictBool] = Field(None, alias="uploadReport") - use_datapool: Optional[StrictBool] = Field(None, alias="useDatapool") - shutdown_when_job_finished: Optional[StrictBool] = Field(None, alias="shutdownWhenJobFinished") - cache_size: Optional[conint(strict=True, ge=-1)] = Field(None, alias="cacheSize", description="Maximum number of bytes stored in the disk cache. Setting it to <=0 disables the cache.") - __properties = ["checkpoint", "checkpointRunId", "corruptnessCheck", "datasource", "embeddings", "enableTraining", "training", "normalizeEmbeddings", "numProcesses", "numThreads", "outputImageFormat", "pretagging", "pretaggingUpload", "relevantFilenamesFile", "selectedSequenceLength", "uploadReport", "useDatapool", "shutdownWhenJobFinished", "cacheSize"] - - @validator('checkpoint_run_id') - def checkpoint_run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigV4Docker: - """Create an instance of DockerWorkerConfigV4Docker from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of corruptness_check - if self.corruptness_check: - _dict['corruptnessCheck' if by_alias else 'corruptness_check'] = self.corruptness_check.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of datasource - if self.datasource: - _dict['datasource' if by_alias else 'datasource'] = self.datasource.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of training - if self.training: - _dict['training' if by_alias else 'training'] = self.training.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigV4Docker: - """Create an instance of DockerWorkerConfigV4Docker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerConfigV4Docker.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerConfigV4Docker) in the input: " + str(obj)) - - _obj = DockerWorkerConfigV4Docker.parse_obj({ - "checkpoint": obj.get("checkpoint"), - "checkpoint_run_id": obj.get("checkpointRunId"), - "corruptness_check": DockerWorkerConfigV3DockerCorruptnessCheck.from_dict(obj.get("corruptnessCheck")) if obj.get("corruptnessCheck") is not None else None, - "datasource": DockerWorkerConfigV3DockerDatasource.from_dict(obj.get("datasource")) if obj.get("datasource") is not None else None, - "embeddings": obj.get("embeddings"), - "enable_training": obj.get("enableTraining"), - "training": DockerWorkerConfigV3DockerTraining.from_dict(obj.get("training")) if obj.get("training") is not None else None, - "normalize_embeddings": obj.get("normalizeEmbeddings"), - "num_processes": obj.get("numProcesses"), - "num_threads": obj.get("numThreads"), - "output_image_format": obj.get("outputImageFormat"), - "pretagging": obj.get("pretagging"), - "pretagging_upload": obj.get("pretaggingUpload"), - "relevant_filenames_file": obj.get("relevantFilenamesFile"), - "selected_sequence_length": obj.get("selectedSequenceLength"), - "upload_report": obj.get("uploadReport"), - "use_datapool": obj.get("useDatapool"), - "shutdown_when_job_finished": obj.get("shutdownWhenJobFinished"), - "cache_size": obj.get("cacheSize") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data.py deleted file mode 100644 index 3ce6fdf9b..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data.py +++ /dev/null @@ -1,216 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v0_data import DockerWorkerConfigV0Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v2_data import DockerWorkerConfigV2Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v3_data import DockerWorkerConfigV3Data -from lightly.openapi_generated.swagger_client.models.docker_worker_config_v4_data import DockerWorkerConfigV4Data -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -DOCKERWORKERCONFIGVXDATA_ONE_OF_SCHEMAS = ["DockerWorkerConfigV0Data", "DockerWorkerConfigV2Data", "DockerWorkerConfigV3Data", "DockerWorkerConfigV4Data"] - -class DockerWorkerConfigVXData(BaseModel): - """ - DockerWorkerConfigVXData - """ - # data type: DockerWorkerConfigV0Data - oneof_schema_1_validator: Optional[DockerWorkerConfigV0Data] = None - # data type: DockerWorkerConfigV2Data - oneof_schema_2_validator: Optional[DockerWorkerConfigV2Data] = None - # data type: DockerWorkerConfigV3Data - oneof_schema_3_validator: Optional[DockerWorkerConfigV3Data] = None - # data type: DockerWorkerConfigV4Data - oneof_schema_4_validator: Optional[DockerWorkerConfigV4Data] = None - actual_instance: Any - one_of_schemas: List[str] = Field(DOCKERWORKERCONFIGVXDATA_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - discriminator_value_class_map = { - } - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = DockerWorkerConfigVXData.construct() - error_messages = [] - match = 0 - # validate data type: DockerWorkerConfigV0Data - if not isinstance(v, DockerWorkerConfigV0Data): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigV0Data`") - else: - match += 1 - # validate data type: DockerWorkerConfigV2Data - if not isinstance(v, DockerWorkerConfigV2Data): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigV2Data`") - else: - match += 1 - # validate data type: DockerWorkerConfigV3Data - if not isinstance(v, DockerWorkerConfigV3Data): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigV3Data`") - else: - match += 1 - # validate data type: DockerWorkerConfigV4Data - if not isinstance(v, DockerWorkerConfigV4Data): - error_messages.append(f"Error! Input type `{type(v)}` is not `DockerWorkerConfigV4Data`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in DockerWorkerConfigVXData with oneOf schemas: DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in DockerWorkerConfigVXData with oneOf schemas: DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerConfigVXData: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerConfigVXData: - """Returns the object represented by the json string""" - instance = DockerWorkerConfigVXData.construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("version") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `version` in the input.") - - # check if data type is `DockerWorkerConfigV0Data` - if _data_type == "DockerWorkerConfigV0Data": - instance.actual_instance = DockerWorkerConfigV0Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV2Data` - if _data_type == "DockerWorkerConfigV2Data": - instance.actual_instance = DockerWorkerConfigV2Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV3Data` - if _data_type == "DockerWorkerConfigV3Data": - instance.actual_instance = DockerWorkerConfigV3Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV4Data` - if _data_type == "DockerWorkerConfigV4Data": - instance.actual_instance = DockerWorkerConfigV4Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV0Data` - if _data_type == "V0": - instance.actual_instance = DockerWorkerConfigV0Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV2Data` - if _data_type == "V2": - instance.actual_instance = DockerWorkerConfigV2Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV3Data` - if _data_type == "V3": - instance.actual_instance = DockerWorkerConfigV3Data.from_json(json_str) - return instance - - # check if data type is `DockerWorkerConfigV4Data` - if _data_type == "V4": - instance.actual_instance = DockerWorkerConfigV4Data.from_json(json_str) - return instance - - # deserialize data into DockerWorkerConfigV0Data - try: - instance.actual_instance = DockerWorkerConfigV0Data.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DockerWorkerConfigV2Data - try: - instance.actual_instance = DockerWorkerConfigV2Data.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DockerWorkerConfigV3Data - try: - instance.actual_instance = DockerWorkerConfigV3Data.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DockerWorkerConfigV4Data - try: - instance.actual_instance = DockerWorkerConfigV4Data.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into DockerWorkerConfigVXData with oneOf schemas: DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into DockerWorkerConfigVXData with oneOf schemas: DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data_base.py b/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data_base.py deleted file mode 100644 index dc6d97396..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_config_vx_data_base.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json -import lightly.openapi_generated.swagger_client.models - - - -from pydantic import Extra, BaseModel, Field, StrictStr, conint, constr, validator - -class DockerWorkerConfigVXDataBase(BaseModel): - """ - DockerWorkerConfigVXDataBase - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - version: StrictStr = Field(..., description="The version of the config. Either V3, V4, etc. Used as the discriminator for") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "version", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - # JSON field name that stores the object type - __discriminator_property_name = 'version' - - # discriminator mappings - __discriminator_value_class_map = { - 'DockerWorkerConfigV0Data': 'DockerWorkerConfigV0Data', - 'DockerWorkerConfigV2Data': 'DockerWorkerConfigV2Data', - 'DockerWorkerConfigV3Data': 'DockerWorkerConfigV3Data', - 'DockerWorkerConfigV4Data': 'DockerWorkerConfigV4Data' - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Union(DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data): - """Create an instance of DockerWorkerConfigVXDataBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Union(DockerWorkerConfigV0Data, DockerWorkerConfigV2Data, DockerWorkerConfigV3Data, DockerWorkerConfigV4Data): - """Create an instance of DockerWorkerConfigVXDataBase from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = getattr(lightly.openapi_generated.swagger_client.models, object_type) - return klass.from_dict(obj) - else: - raise ValueError("DockerWorkerConfigVXDataBase failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_registry_entry_data.py b/lightly/openapi_generated/swagger_client/models/docker_worker_registry_entry_data.py deleted file mode 100644 index 6c4fe75a4..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_registry_entry_data.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.docker_worker_state import DockerWorkerState -from lightly.openapi_generated.swagger_client.models.docker_worker_type import DockerWorkerType - -class DockerWorkerRegistryEntryData(BaseModel): - """ - DockerWorkerRegistryEntryData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - user_id: StrictStr = Field(..., alias="userId") - name: constr(strict=True, min_length=3) = Field(...) - worker_type: DockerWorkerType = Field(..., alias="workerType") - state: DockerWorkerState = Field(...) - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - labels: conlist(StrictStr) = Field(..., description="The labels used for specifying the run-worker-relationship") - docker_version: Optional[StrictStr] = Field(None, alias="dockerVersion") - __properties = ["id", "userId", "name", "workerType", "state", "createdAt", "lastModifiedAt", "labels", "dockerVersion"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 _-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 _-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> DockerWorkerRegistryEntryData: - """Create an instance of DockerWorkerRegistryEntryData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DockerWorkerRegistryEntryData: - """Create an instance of DockerWorkerRegistryEntryData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DockerWorkerRegistryEntryData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DockerWorkerRegistryEntryData) in the input: " + str(obj)) - - _obj = DockerWorkerRegistryEntryData.parse_obj({ - "id": obj.get("id"), - "user_id": obj.get("userId"), - "name": obj.get("name"), - "worker_type": obj.get("workerType"), - "state": obj.get("state"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "labels": obj.get("labels"), - "docker_version": obj.get("dockerVersion") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_state.py b/lightly/openapi_generated/swagger_client/models/docker_worker_state.py deleted file mode 100644 index 9e00e2e21..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_state.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerWorkerState(str, Enum): - """ - DockerWorkerState - """ - - """ - allowed enum values - """ - OFFLINE = 'OFFLINE' - CRASHED = 'CRASHED' - IDLE = 'IDLE' - BUSY = 'BUSY' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerWorkerState': - """Create an instance of DockerWorkerState from a JSON string""" - return DockerWorkerState(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/docker_worker_type.py b/lightly/openapi_generated/swagger_client/models/docker_worker_type.py deleted file mode 100644 index ea6b6464a..000000000 --- a/lightly/openapi_generated/swagger_client/models/docker_worker_type.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class DockerWorkerType(str, Enum): - """ - DockerWorkerType - """ - - """ - allowed enum values - """ - FULL = 'FULL' - - @classmethod - def from_json(cls, json_str: str) -> 'DockerWorkerType': - """Create an instance of DockerWorkerType from a JSON string""" - return DockerWorkerType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/embedding2d_create_request.py b/lightly/openapi_generated/swagger_client/models/embedding2d_create_request.py deleted file mode 100644 index 7b15bd32d..000000000 --- a/lightly/openapi_generated/swagger_client/models/embedding2d_create_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.dimensionality_reduction_method import DimensionalityReductionMethod - -class Embedding2dCreateRequest(BaseModel): - """ - Embedding2dCreateRequest - """ - name: StrictStr = Field(..., description="Name of the 2d embedding (default is embedding name + __2d)") - dimensionality_reduction_method: DimensionalityReductionMethod = Field(..., alias="dimensionalityReductionMethod") - coordinates_dimension1: conlist(Union[StrictFloat, StrictInt], min_items=1) = Field(..., alias="coordinatesDimension1", description="Array of coordinates of a 2d embedding") - coordinates_dimension2: conlist(Union[StrictFloat, StrictInt], min_items=1) = Field(..., alias="coordinatesDimension2", description="Array of coordinates of a 2d embedding") - __properties = ["name", "dimensionalityReductionMethod", "coordinatesDimension1", "coordinatesDimension2"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Embedding2dCreateRequest: - """Create an instance of Embedding2dCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Embedding2dCreateRequest: - """Create an instance of Embedding2dCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Embedding2dCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Embedding2dCreateRequest) in the input: " + str(obj)) - - _obj = Embedding2dCreateRequest.parse_obj({ - "name": obj.get("name"), - "dimensionality_reduction_method": obj.get("dimensionalityReductionMethod"), - "coordinates_dimension1": obj.get("coordinatesDimension1"), - "coordinates_dimension2": obj.get("coordinatesDimension2") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/embedding2d_data.py b/lightly/openapi_generated/swagger_client/models/embedding2d_data.py deleted file mode 100644 index 0b2e490c7..000000000 --- a/lightly/openapi_generated/swagger_client/models/embedding2d_data.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.dimensionality_reduction_method import DimensionalityReductionMethod - -class Embedding2dData(BaseModel): - """ - Embedding2dData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: constr(strict=True) = Field(..., alias="datasetId", description="MongoDB ObjectId") - embedding_id: constr(strict=True) = Field(..., alias="embeddingId", description="MongoDB ObjectId") - name: StrictStr = Field(..., description="Name of the 2d embedding (default is embedding name + __2d)") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - dimensionality_reduction_method: DimensionalityReductionMethod = Field(..., alias="dimensionalityReductionMethod") - coordinates_dimension1: Optional[conlist(Union[StrictFloat, StrictInt], min_items=1)] = Field(None, alias="coordinatesDimension1", description="Array of coordinates of a 2d embedding") - coordinates_dimension2: Optional[conlist(Union[StrictFloat, StrictInt], min_items=1)] = Field(None, alias="coordinatesDimension2", description="Array of coordinates of a 2d embedding") - __properties = ["id", "datasetId", "embeddingId", "name", "createdAt", "dimensionalityReductionMethod", "coordinatesDimension1", "coordinatesDimension2"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('embedding_id') - def embedding_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Embedding2dData: - """Create an instance of Embedding2dData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Embedding2dData: - """Create an instance of Embedding2dData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Embedding2dData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Embedding2dData) in the input: " + str(obj)) - - _obj = Embedding2dData.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "embedding_id": obj.get("embeddingId"), - "name": obj.get("name"), - "created_at": obj.get("createdAt"), - "dimensionality_reduction_method": obj.get("dimensionalityReductionMethod"), - "coordinates_dimension1": obj.get("coordinatesDimension1"), - "coordinates_dimension2": obj.get("coordinatesDimension2") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/embedding_data.py b/lightly/openapi_generated/swagger_client/models/embedding_data.py deleted file mode 100644 index df06a7403..000000000 --- a/lightly/openapi_generated/swagger_client/models/embedding_data.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator - -class EmbeddingData(BaseModel): - """ - EmbeddingData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: StrictStr = Field(...) - __properties = ["id", "dataset", "name"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset') - def dataset_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> EmbeddingData: - """Create an instance of EmbeddingData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> EmbeddingData: - """Create an instance of EmbeddingData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return EmbeddingData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in EmbeddingData) in the input: " + str(obj)) - - _obj = EmbeddingData.parse_obj({ - "id": obj.get("id"), - "dataset": obj.get("dataset"), - "name": obj.get("name") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/expiry_handling_strategy_v3.py b/lightly/openapi_generated/swagger_client/models/expiry_handling_strategy_v3.py deleted file mode 100644 index 6fcb9315f..000000000 --- a/lightly/openapi_generated/swagger_client/models/expiry_handling_strategy_v3.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class ExpiryHandlingStrategyV3(str, Enum): - """ - ExpiryHandlingStrategyV3 - """ - - """ - allowed enum values - """ - SKIP = 'SKIP' - ABORT = 'ABORT' - - @classmethod - def from_json(cls, json_str: str) -> 'ExpiryHandlingStrategyV3': - """Create an instance of ExpiryHandlingStrategyV3 from a JSON string""" - return ExpiryHandlingStrategyV3(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/file_name_format.py b/lightly/openapi_generated/swagger_client/models/file_name_format.py deleted file mode 100644 index 801a325ca..000000000 --- a/lightly/openapi_generated/swagger_client/models/file_name_format.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class FileNameFormat(str, Enum): - """ - When the filename is output, which format shall be used. E.g for a sample called 'frame0.png' that was uploaded from a datasource 's3://my_bucket/datasets/for_lightly/' in the folder 'car/green/' - NAME: car/green/frame0.png - DATASOURCE_FULL: s3://my_bucket/datasets/for_lightly/car/green/frame0.png - REDIRECTED_READ_URL: https://api.lightly.ai/v1/datasets/{datasetId}/samples/{sampleId}/readurlRedirect?publicToken={jsonWebToken} - """ - - """ - allowed enum values - """ - NAME = 'NAME' - DATASOURCE_FULL = 'DATASOURCE_FULL' - REDIRECTED_READ_URL = 'REDIRECTED_READ_URL' - - @classmethod - def from_json(cls, json_str: str) -> 'FileNameFormat': - """Create an instance of FileNameFormat from a JSON string""" - return FileNameFormat(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/file_output_format.py b/lightly/openapi_generated/swagger_client/models/file_output_format.py deleted file mode 100644 index 7d1706f6d..000000000 --- a/lightly/openapi_generated/swagger_client/models/file_output_format.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class FileOutputFormat(str, Enum): - """ - FileOutputFormat - """ - - """ - allowed enum values - """ - JSON = 'JSON' - PLAIN = 'PLAIN' - - @classmethod - def from_json(cls, json_str: str) -> 'FileOutputFormat': - """Create an instance of FileOutputFormat from a JSON string""" - return FileOutputFormat(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/filename_and_read_url.py b/lightly/openapi_generated/swagger_client/models/filename_and_read_url.py deleted file mode 100644 index fc5af48c5..000000000 --- a/lightly/openapi_generated/swagger_client/models/filename_and_read_url.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class FilenameAndReadUrl(BaseModel): - """ - Filename and corresponding read url for a sample in a tag - """ - file_name: StrictStr = Field(..., alias="fileName") - read_url: StrictStr = Field(..., alias="readUrl", description="A URL which allows anyone in possession of said URL to access the resource") - __properties = ["fileName", "readUrl"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> FilenameAndReadUrl: - """Create an instance of FilenameAndReadUrl from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> FilenameAndReadUrl: - """Create an instance of FilenameAndReadUrl from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return FilenameAndReadUrl.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in FilenameAndReadUrl) in the input: " + str(obj)) - - _obj = FilenameAndReadUrl.parse_obj({ - "file_name": obj.get("fileName"), - "read_url": obj.get("readUrl") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/image_type.py b/lightly/openapi_generated/swagger_client/models/image_type.py deleted file mode 100644 index 7d68fe9e5..000000000 --- a/lightly/openapi_generated/swagger_client/models/image_type.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class ImageType(str, Enum): - """ - ImageType - """ - - """ - allowed enum values - """ - FULL = 'full' - THUMBNAIL = 'thumbnail' - META = 'meta' - - @classmethod - def from_json(cls, json_str: str) -> 'ImageType': - """Create an instance of ImageType from a JSON string""" - return ImageType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/initial_tag_create_request.py b/lightly/openapi_generated/swagger_client/models/initial_tag_create_request.py deleted file mode 100644 index f202af5d4..000000000 --- a/lightly/openapi_generated/swagger_client/models/initial_tag_create_request.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.image_type import ImageType -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class InitialTagCreateRequest(BaseModel): - """ - InitialTagCreateRequest - """ - name: Optional[constr(strict=True, min_length=3)] = Field(None, description="The name of the tag") - creator: Optional[TagCreator] = None - img_type: ImageType = Field(..., alias="imgType") - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["name", "creator", "imgType", "runId"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> InitialTagCreateRequest: - """Create an instance of InitialTagCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> InitialTagCreateRequest: - """Create an instance of InitialTagCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return InitialTagCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in InitialTagCreateRequest) in the input: " + str(obj)) - - _obj = InitialTagCreateRequest.parse_obj({ - "name": obj.get("name"), - "creator": obj.get("creator"), - "img_type": obj.get("imgType"), - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/internal_debug_latency.py b/lightly/openapi_generated/swagger_client/models/internal_debug_latency.py deleted file mode 100644 index ef3a4a931..000000000 --- a/lightly/openapi_generated/swagger_client/models/internal_debug_latency.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt -from lightly.openapi_generated.swagger_client.models.internal_debug_latency_mongodb import InternalDebugLatencyMongodb - -class InternalDebugLatency(BaseModel): - """ - InternalDebugLatency - """ - express: Optional[Union[StrictFloat, StrictInt]] = None - mongodb: Optional[InternalDebugLatencyMongodb] = None - redis_cache: Optional[InternalDebugLatencyMongodb] = Field(None, alias="redisCache") - redis_worker: Optional[InternalDebugLatencyMongodb] = Field(None, alias="redisWorker") - __properties = ["express", "mongodb", "redisCache", "redisWorker"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> InternalDebugLatency: - """Create an instance of InternalDebugLatency from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of mongodb - if self.mongodb: - _dict['mongodb' if by_alias else 'mongodb'] = self.mongodb.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of redis_cache - if self.redis_cache: - _dict['redisCache' if by_alias else 'redis_cache'] = self.redis_cache.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of redis_worker - if self.redis_worker: - _dict['redisWorker' if by_alias else 'redis_worker'] = self.redis_worker.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> InternalDebugLatency: - """Create an instance of InternalDebugLatency from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return InternalDebugLatency.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in InternalDebugLatency) in the input: " + str(obj)) - - _obj = InternalDebugLatency.parse_obj({ - "express": obj.get("express"), - "mongodb": InternalDebugLatencyMongodb.from_dict(obj.get("mongodb")) if obj.get("mongodb") is not None else None, - "redis_cache": InternalDebugLatencyMongodb.from_dict(obj.get("redisCache")) if obj.get("redisCache") is not None else None, - "redis_worker": InternalDebugLatencyMongodb.from_dict(obj.get("redisWorker")) if obj.get("redisWorker") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/internal_debug_latency_mongodb.py b/lightly/openapi_generated/swagger_client/models/internal_debug_latency_mongodb.py deleted file mode 100644 index 77a189be7..000000000 --- a/lightly/openapi_generated/swagger_client/models/internal_debug_latency_mongodb.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, StrictFloat, StrictInt - -class InternalDebugLatencyMongodb(BaseModel): - """ - InternalDebugLatencyMongodb - """ - connection: Optional[Union[StrictFloat, StrictInt]] = None - query: Optional[Union[StrictFloat, StrictInt]] = None - __properties = ["connection", "query"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> InternalDebugLatencyMongodb: - """Create an instance of InternalDebugLatencyMongodb from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> InternalDebugLatencyMongodb: - """Create an instance of InternalDebugLatencyMongodb from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return InternalDebugLatencyMongodb.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in InternalDebugLatencyMongodb) in the input: " + str(obj)) - - _obj = InternalDebugLatencyMongodb.parse_obj({ - "connection": obj.get("connection"), - "query": obj.get("query") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/job_result_type.py b/lightly/openapi_generated/swagger_client/models/job_result_type.py deleted file mode 100644 index 94685e4f3..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_result_type.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class JobResultType(str, Enum): - """ - JobResultType - """ - - """ - allowed enum values - """ - DATASET_PROCESSING = 'DATASET_PROCESSING' - IMAGEMETA = 'IMAGEMETA' - EMBEDDING = 'EMBEDDING' - EMBEDDINGS2D = 'EMBEDDINGS2D' - SAMPLING = 'SAMPLING' - - @classmethod - def from_json(cls, json_str: str) -> 'JobResultType': - """Create an instance of JobResultType from a JSON string""" - return JobResultType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/job_state.py b/lightly/openapi_generated/swagger_client/models/job_state.py deleted file mode 100644 index 98fe3198d..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_state.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class JobState(str, Enum): - """ - JobState - """ - - """ - allowed enum values - """ - UNKNOWN = 'UNKNOWN' - WAITING = 'WAITING' - RUNNING = 'RUNNING' - FAILED = 'FAILED' - FINISHED = 'FINISHED' - - @classmethod - def from_json(cls, json_str: str) -> 'JobState': - """Create an instance of JobState from a JSON string""" - return JobState(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/job_status_data.py b/lightly/openapi_generated/swagger_client/models/job_status_data.py deleted file mode 100644 index f24d50c88..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_status_data.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.job_state import JobState -from lightly.openapi_generated.swagger_client.models.job_status_data_result import JobStatusDataResult -from lightly.openapi_generated.swagger_client.models.job_status_meta import JobStatusMeta - -class JobStatusData(BaseModel): - """ - JobStatusData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - status: JobState = Field(...) - meta: Optional[JobStatusMeta] = None - wait_time_till_next_poll: StrictInt = Field(..., alias="waitTimeTillNextPoll", description="The time in seconds the client should wait before doing the next poll.") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="lastModifiedAt", description="unix timestamp in milliseconds") - finished_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="finishedAt", description="unix timestamp in milliseconds") - error: Optional[StrictStr] = None - result: Optional[JobStatusDataResult] = None - __properties = ["id", "datasetId", "status", "meta", "waitTimeTillNextPoll", "createdAt", "lastModifiedAt", "finishedAt", "error", "result"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> JobStatusData: - """Create an instance of JobStatusData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of meta - if self.meta: - _dict['meta' if by_alias else 'meta'] = self.meta.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of result - if self.result: - _dict['result' if by_alias else 'result'] = self.result.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> JobStatusData: - """Create an instance of JobStatusData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return JobStatusData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in JobStatusData) in the input: " + str(obj)) - - _obj = JobStatusData.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "status": obj.get("status"), - "meta": JobStatusMeta.from_dict(obj.get("meta")) if obj.get("meta") is not None else None, - "wait_time_till_next_poll": obj.get("waitTimeTillNextPoll"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "finished_at": obj.get("finishedAt"), - "error": obj.get("error"), - "result": JobStatusDataResult.from_dict(obj.get("result")) if obj.get("result") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/job_status_data_result.py b/lightly/openapi_generated/swagger_client/models/job_status_data_result.py deleted file mode 100644 index cc19fb35c..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_status_data_result.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.job_result_type import JobResultType - -class JobStatusDataResult(BaseModel): - """ - JobStatusDataResult - """ - type: JobResultType = Field(...) - data: Optional[Any] = Field(None, description="Depending on the job type, this can be anything") - __properties = ["type", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> JobStatusDataResult: - """Create an instance of JobStatusDataResult from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # set to None if data (nullable) is None - # and __fields_set__ contains the field - if self.data is None and "data" in self.__fields_set__: - _dict['data' if by_alias else 'data'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> JobStatusDataResult: - """Create an instance of JobStatusDataResult from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return JobStatusDataResult.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in JobStatusDataResult) in the input: " + str(obj)) - - _obj = JobStatusDataResult.parse_obj({ - "type": obj.get("type"), - "data": obj.get("data") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/job_status_meta.py b/lightly/openapi_generated/swagger_client/models/job_status_meta.py deleted file mode 100644 index 4256f0f80..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_status_meta.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictBool, StrictInt -from lightly.openapi_generated.swagger_client.models.job_status_upload_method import JobStatusUploadMethod - -class JobStatusMeta(BaseModel): - """ - JobStatusMeta - """ - total: StrictInt = Field(...) - processed: StrictInt = Field(...) - upload_method: Optional[JobStatusUploadMethod] = Field(None, alias="uploadMethod") - is_registered: Optional[StrictBool] = Field(None, alias="isRegistered", description="Flag which indicates whether the job was registered or not.") - __properties = ["total", "processed", "uploadMethod", "isRegistered"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> JobStatusMeta: - """Create an instance of JobStatusMeta from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> JobStatusMeta: - """Create an instance of JobStatusMeta from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return JobStatusMeta.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in JobStatusMeta) in the input: " + str(obj)) - - _obj = JobStatusMeta.parse_obj({ - "total": obj.get("total"), - "processed": obj.get("processed"), - "upload_method": obj.get("uploadMethod"), - "is_registered": obj.get("isRegistered") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/job_status_upload_method.py b/lightly/openapi_generated/swagger_client/models/job_status_upload_method.py deleted file mode 100644 index 64a42eb50..000000000 --- a/lightly/openapi_generated/swagger_client/models/job_status_upload_method.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class JobStatusUploadMethod(str, Enum): - """ - JobStatusUploadMethod - """ - - """ - allowed enum values - """ - USER_WEBAPP = 'USER_WEBAPP' - USER_PIP = 'USER_PIP' - INTERNAL = 'INTERNAL' - - @classmethod - def from_json(cls, json_str: str) -> 'JobStatusUploadMethod': - """Create an instance of JobStatusUploadMethod from a JSON string""" - return JobStatusUploadMethod(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/jobs_data.py b/lightly/openapi_generated/swagger_client/models/jobs_data.py deleted file mode 100644 index b01a65e4f..000000000 --- a/lightly/openapi_generated/swagger_client/models/jobs_data.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.job_result_type import JobResultType -from lightly.openapi_generated.swagger_client.models.job_state import JobState - -class JobsData(BaseModel): - """ - JobsData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - job_id: StrictStr = Field(..., alias="jobId") - job_type: JobResultType = Field(..., alias="jobType") - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - status: JobState = Field(...) - finished_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="finishedAt", description="unix timestamp in milliseconds") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "jobId", "jobType", "datasetId", "status", "finishedAt", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> JobsData: - """Create an instance of JobsData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> JobsData: - """Create an instance of JobsData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return JobsData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in JobsData) in the input: " + str(obj)) - - _obj = JobsData.parse_obj({ - "id": obj.get("id"), - "job_id": obj.get("jobId"), - "job_type": obj.get("jobType"), - "dataset_id": obj.get("datasetId"), - "status": obj.get("status"), - "finished_at": obj.get("finishedAt"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/label_box_data_row.py b/lightly/openapi_generated/swagger_client/models/label_box_data_row.py deleted file mode 100644 index e483fa829..000000000 --- a/lightly/openapi_generated/swagger_client/models/label_box_data_row.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class LabelBoxDataRow(BaseModel): - """ - LabelBoxDataRow - """ - external_id: StrictStr = Field(..., alias="externalId", description="The task_id for importing into LabelBox.") - image_url: StrictStr = Field(..., alias="imageUrl", description="A URL which allows anyone in possession of said URL for the time specified by the expiresIn query param to access the resource") - __properties = ["externalId", "imageUrl"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> LabelBoxDataRow: - """Create an instance of LabelBoxDataRow from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> LabelBoxDataRow: - """Create an instance of LabelBoxDataRow from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return LabelBoxDataRow.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in LabelBoxDataRow) in the input: " + str(obj)) - - _obj = LabelBoxDataRow.parse_obj({ - "external_id": obj.get("externalId"), - "image_url": obj.get("imageUrl") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/label_box_v4_data_row.py b/lightly/openapi_generated/swagger_client/models/label_box_v4_data_row.py deleted file mode 100644 index 17e401e2c..000000000 --- a/lightly/openapi_generated/swagger_client/models/label_box_v4_data_row.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr - -class LabelBoxV4DataRow(BaseModel): - """ - LabelBoxV4DataRow - """ - row_data: StrictStr = Field(..., description="A URL which allows anyone in possession of said URL for the time specified by the expiresIn query param to access the resource") - global_key: Optional[StrictStr] = Field(None, description="The task_id for importing into LabelBox.") - media_type: Optional[StrictStr] = Field(None, description="LabelBox media type, e.g. IMAGE") - __properties = ["row_data", "global_key", "media_type"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> LabelBoxV4DataRow: - """Create an instance of LabelBoxV4DataRow from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> LabelBoxV4DataRow: - """Create an instance of LabelBoxV4DataRow from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return LabelBoxV4DataRow.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in LabelBoxV4DataRow) in the input: " + str(obj)) - - _obj = LabelBoxV4DataRow.parse_obj({ - "row_data": obj.get("row_data"), - "global_key": obj.get("global_key"), - "media_type": obj.get("media_type") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/label_studio_task.py b/lightly/openapi_generated/swagger_client/models/label_studio_task.py deleted file mode 100644 index cb2718094..000000000 --- a/lightly/openapi_generated/swagger_client/models/label_studio_task.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictInt -from lightly.openapi_generated.swagger_client.models.label_studio_task_data import LabelStudioTaskData - -class LabelStudioTask(BaseModel): - """ - LabelStudioTask - """ - id: StrictInt = Field(..., description="The task_id for importing into LabelStudio.") - data: LabelStudioTaskData = Field(...) - __properties = ["id", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> LabelStudioTask: - """Create an instance of LabelStudioTask from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of data - if self.data: - _dict['data' if by_alias else 'data'] = self.data.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> LabelStudioTask: - """Create an instance of LabelStudioTask from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return LabelStudioTask.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in LabelStudioTask) in the input: " + str(obj)) - - _obj = LabelStudioTask.parse_obj({ - "id": obj.get("id"), - "data": LabelStudioTaskData.from_dict(obj.get("data")) if obj.get("data") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/label_studio_task_data.py b/lightly/openapi_generated/swagger_client/models/label_studio_task_data.py deleted file mode 100644 index f4e2f5d71..000000000 --- a/lightly/openapi_generated/swagger_client/models/label_studio_task_data.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.sample_data import SampleData - -class LabelStudioTaskData(BaseModel): - """ - LabelStudioTaskData - """ - image: StrictStr = Field(..., description="A URL which allows anyone in possession of said URL for the time specified by the expiresIn query param to access the resource") - lightly_file_name: Optional[StrictStr] = Field(None, alias="lightlyFileName", description="The original fileName of the sample. This is unique within a dataset") - lightly_meta_info: Optional[SampleData] = Field(None, alias="lightlyMetaInfo") - __properties = ["image", "lightlyFileName", "lightlyMetaInfo"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> LabelStudioTaskData: - """Create an instance of LabelStudioTaskData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of lightly_meta_info - if self.lightly_meta_info: - _dict['lightlyMetaInfo' if by_alias else 'lightly_meta_info'] = self.lightly_meta_info.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> LabelStudioTaskData: - """Create an instance of LabelStudioTaskData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return LabelStudioTaskData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in LabelStudioTaskData) in the input: " + str(obj)) - - _obj = LabelStudioTaskData.parse_obj({ - "image": obj.get("image"), - "lightly_file_name": obj.get("lightlyFileName"), - "lightly_meta_info": SampleData.from_dict(obj.get("lightlyMetaInfo")) if obj.get("lightlyMetaInfo") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/lightly_docker_selection_method.py b/lightly/openapi_generated/swagger_client/models/lightly_docker_selection_method.py deleted file mode 100644 index 19d319550..000000000 --- a/lightly/openapi_generated/swagger_client/models/lightly_docker_selection_method.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class LightlyDockerSelectionMethod(str, Enum): - """ - LightlyDockerSelectionMethod - """ - - """ - allowed enum values - """ - CORESET = 'coreset' - RANDOM = 'random' - - @classmethod - def from_json(cls, json_str: str) -> 'LightlyDockerSelectionMethod': - """Create an instance of LightlyDockerSelectionMethod from a JSON string""" - return LightlyDockerSelectionMethod(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/lightly_model_v2.py b/lightly/openapi_generated/swagger_client/models/lightly_model_v2.py deleted file mode 100644 index f713c9aea..000000000 --- a/lightly/openapi_generated/swagger_client/models/lightly_model_v2.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class LightlyModelV2(str, Enum): - """ - LightlyModelV2 - """ - - """ - allowed enum values - """ - RESNET_MINUS_18 = 'resnet-18' - RESNET_MINUS_34 = 'resnet-34' - RESNET_MINUS_50 = 'resnet-50' - RESNET_MINUS_101 = 'resnet-101' - RESNET_MINUS_152 = 'resnet-152' - - @classmethod - def from_json(cls, json_str: str) -> 'LightlyModelV2': - """Create an instance of LightlyModelV2 from a JSON string""" - return LightlyModelV2(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/lightly_model_v3.py b/lightly/openapi_generated/swagger_client/models/lightly_model_v3.py deleted file mode 100644 index d557f1b8b..000000000 --- a/lightly/openapi_generated/swagger_client/models/lightly_model_v3.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class LightlyModelV3(str, Enum): - """ - LightlyModelV3 - """ - - """ - allowed enum values - """ - RESNET_MINUS_18 = 'resnet-18' - RESNET_MINUS_34 = 'resnet-34' - RESNET_MINUS_50 = 'resnet-50' - RESNET_MINUS_101 = 'resnet-101' - RESNET_MINUS_152 = 'resnet-152' - - @classmethod - def from_json(cls, json_str: str) -> 'LightlyModelV3': - """Create an instance of LightlyModelV3 from a JSON string""" - return LightlyModelV3(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v2.py b/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v2.py deleted file mode 100644 index 01f965caa..000000000 --- a/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v2.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class LightlyTrainerPrecisionV2(int, Enum): - """ - LightlyTrainerPrecisionV2 - """ - - """ - allowed enum values - """ - NUMBER_16 = 16 - NUMBER_32 = 32 - - @classmethod - def from_json(cls, json_str: str) -> 'LightlyTrainerPrecisionV2': - """Create an instance of LightlyTrainerPrecisionV2 from a JSON string""" - return LightlyTrainerPrecisionV2(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v3.py b/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v3.py deleted file mode 100644 index 65f8a652d..000000000 --- a/lightly/openapi_generated/swagger_client/models/lightly_trainer_precision_v3.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class LightlyTrainerPrecisionV3(int, Enum): - """ - LightlyTrainerPrecisionV3 - """ - - """ - allowed enum values - """ - NUMBER_16 = 16 - NUMBER_32 = 32 - - @classmethod - def from_json(cls, json_str: str) -> 'LightlyTrainerPrecisionV3': - """Create an instance of LightlyTrainerPrecisionV3 from a JSON string""" - return LightlyTrainerPrecisionV3(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton.py deleted file mode 100644 index 078fb4740..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.prediction_singleton_classification import PredictionSingletonClassification -from lightly.openapi_generated.swagger_client.models.prediction_singleton_instance_segmentation import PredictionSingletonInstanceSegmentation -from lightly.openapi_generated.swagger_client.models.prediction_singleton_keypoint_detection import PredictionSingletonKeypointDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_object_detection import PredictionSingletonObjectDetection -from lightly.openapi_generated.swagger_client.models.prediction_singleton_semantic_segmentation import PredictionSingletonSemanticSegmentation -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -PREDICTIONSINGLETON_ONE_OF_SCHEMAS = ["PredictionSingletonClassification", "PredictionSingletonInstanceSegmentation", "PredictionSingletonKeypointDetection", "PredictionSingletonObjectDetection", "PredictionSingletonSemanticSegmentation"] - -class PredictionSingleton(BaseModel): - """ - PredictionSingleton - """ - # data type: PredictionSingletonClassification - oneof_schema_1_validator: Optional[PredictionSingletonClassification] = None - # data type: PredictionSingletonObjectDetection - oneof_schema_2_validator: Optional[PredictionSingletonObjectDetection] = None - # data type: PredictionSingletonSemanticSegmentation - oneof_schema_3_validator: Optional[PredictionSingletonSemanticSegmentation] = None - # data type: PredictionSingletonInstanceSegmentation - oneof_schema_4_validator: Optional[PredictionSingletonInstanceSegmentation] = None - # data type: PredictionSingletonKeypointDetection - oneof_schema_5_validator: Optional[PredictionSingletonKeypointDetection] = None - actual_instance: Any - one_of_schemas: List[str] = Field(PREDICTIONSINGLETON_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - discriminator_value_class_map = { - } - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = PredictionSingleton.construct() - error_messages = [] - match = 0 - # validate data type: PredictionSingletonClassification - if not isinstance(v, PredictionSingletonClassification): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionSingletonClassification`") - else: - match += 1 - # validate data type: PredictionSingletonObjectDetection - if not isinstance(v, PredictionSingletonObjectDetection): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionSingletonObjectDetection`") - else: - match += 1 - # validate data type: PredictionSingletonSemanticSegmentation - if not isinstance(v, PredictionSingletonSemanticSegmentation): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionSingletonSemanticSegmentation`") - else: - match += 1 - # validate data type: PredictionSingletonInstanceSegmentation - if not isinstance(v, PredictionSingletonInstanceSegmentation): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionSingletonInstanceSegmentation`") - else: - match += 1 - # validate data type: PredictionSingletonKeypointDetection - if not isinstance(v, PredictionSingletonKeypointDetection): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionSingletonKeypointDetection`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in PredictionSingleton with oneOf schemas: PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in PredictionSingleton with oneOf schemas: PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingleton: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingleton: - """Returns the object represented by the json string""" - instance = PredictionSingleton.construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("type") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `type` in the input.") - - # check if data type is `PredictionSingletonClassification` - if _data_type == "CLASSIFICATION": - instance.actual_instance = PredictionSingletonClassification.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonInstanceSegmentation` - if _data_type == "INSTANCE_SEGMENTATION": - instance.actual_instance = PredictionSingletonInstanceSegmentation.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonKeypointDetection` - if _data_type == "KEYPOINT_DETECTION": - instance.actual_instance = PredictionSingletonKeypointDetection.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonObjectDetection` - if _data_type == "OBJECT_DETECTION": - instance.actual_instance = PredictionSingletonObjectDetection.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonClassification` - if _data_type == "PredictionSingletonClassification": - instance.actual_instance = PredictionSingletonClassification.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonInstanceSegmentation` - if _data_type == "PredictionSingletonInstanceSegmentation": - instance.actual_instance = PredictionSingletonInstanceSegmentation.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonKeypointDetection` - if _data_type == "PredictionSingletonKeypointDetection": - instance.actual_instance = PredictionSingletonKeypointDetection.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonObjectDetection` - if _data_type == "PredictionSingletonObjectDetection": - instance.actual_instance = PredictionSingletonObjectDetection.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonSemanticSegmentation` - if _data_type == "PredictionSingletonSemanticSegmentation": - instance.actual_instance = PredictionSingletonSemanticSegmentation.from_json(json_str) - return instance - - # check if data type is `PredictionSingletonSemanticSegmentation` - if _data_type == "SEMANTIC_SEGMENTATION": - instance.actual_instance = PredictionSingletonSemanticSegmentation.from_json(json_str) - return instance - - # deserialize data into PredictionSingletonClassification - try: - instance.actual_instance = PredictionSingletonClassification.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into PredictionSingletonObjectDetection - try: - instance.actual_instance = PredictionSingletonObjectDetection.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into PredictionSingletonSemanticSegmentation - try: - instance.actual_instance = PredictionSingletonSemanticSegmentation.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into PredictionSingletonInstanceSegmentation - try: - instance.actual_instance = PredictionSingletonInstanceSegmentation.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into PredictionSingletonKeypointDetection - try: - instance.actual_instance = PredictionSingletonKeypointDetection.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into PredictionSingleton with oneOf schemas: PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into PredictionSingleton with oneOf schemas: PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_base.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_base.py deleted file mode 100644 index caff2751a..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_base.py +++ /dev/null @@ -1,126 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json -import lightly.openapi_generated.swagger_client.models - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictStr, confloat, conint, constr, validator - -class PredictionSingletonBase(BaseModel): - """ - PredictionSingletonBase - """ - type: StrictStr = Field(...) - task_name: constr(strict=True, min_length=1) = Field(..., alias="taskName", description="A name which is safe to have as a file/folder name in a file system") - crop_dataset_id: Optional[constr(strict=True)] = Field(None, alias="cropDatasetId", description="MongoDB ObjectId") - crop_sample_id: Optional[constr(strict=True)] = Field(None, alias="cropSampleId", description="MongoDB ObjectId") - category_id: conint(strict=True, ge=0) = Field(..., alias="categoryId", description="The id of the category. Needs to be a positive integer but can be any integer (gaps are allowed, does not need to be sequential)") - score: Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)] = Field(..., description="the score for the prediction task which yielded this crop") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score"] - - @validator('task_name') - def task_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$/") - return value - - @validator('crop_dataset_id') - def crop_dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('crop_sample_id') - def crop_sample_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - # JSON field name that stores the object type - __discriminator_property_name = 'type' - - # discriminator mappings - __discriminator_value_class_map = { - 'PredictionSingletonClassification': 'PredictionSingletonClassification', - 'PredictionSingletonInstanceSegmentation': 'PredictionSingletonInstanceSegmentation', - 'PredictionSingletonKeypointDetection': 'PredictionSingletonKeypointDetection', - 'PredictionSingletonObjectDetection': 'PredictionSingletonObjectDetection', - 'PredictionSingletonSemanticSegmentation': 'PredictionSingletonSemanticSegmentation' - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Union(PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation): - """Create an instance of PredictionSingletonBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Union(PredictionSingletonClassification, PredictionSingletonInstanceSegmentation, PredictionSingletonKeypointDetection, PredictionSingletonObjectDetection, PredictionSingletonSemanticSegmentation): - """Create an instance of PredictionSingletonBase from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = getattr(lightly.openapi_generated.swagger_client.models, object_type) - return klass.from_dict(obj) - else: - raise ValueError("PredictionSingletonBase failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification.py deleted file mode 100644 index 5b2757c75..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase - -class PredictionSingletonClassification(PredictionSingletonBase): - """ - PredictionSingletonClassification - """ - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonClassification: - """Create an instance of PredictionSingletonClassification from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonClassification: - """Create an instance of PredictionSingletonClassification from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonClassification.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonClassification) in the input: " + str(obj)) - - _obj = PredictionSingletonClassification.parse_obj({ - "type": obj.get("type"), - "task_name": obj.get("taskName"), - "crop_dataset_id": obj.get("cropDatasetId"), - "crop_sample_id": obj.get("cropSampleId"), - "category_id": obj.get("categoryId"), - "score": obj.get("score"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification_all_of.py deleted file mode 100644 index 3e8bbeeaf..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_classification_all_of.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class PredictionSingletonClassificationAllOf(BaseModel): - """ - PredictionSingletonClassificationAllOf - """ - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonClassificationAllOf: - """Create an instance of PredictionSingletonClassificationAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonClassificationAllOf: - """Create an instance of PredictionSingletonClassificationAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonClassificationAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonClassificationAllOf) in the input: " + str(obj)) - - _obj = PredictionSingletonClassificationAllOf.parse_obj({ - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation.py deleted file mode 100644 index 76f93d537..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase - -class PredictionSingletonInstanceSegmentation(PredictionSingletonBase): - """ - PredictionSingletonInstanceSegmentation - """ - segmentation: conlist(conint(strict=True, ge=0)) = Field(..., description="Run Length Encoding (RLE) as outlined by https://docs.lightly.ai/docs/prediction-format#semantic-segmentation ") - bbox: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4) = Field(..., description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score", "segmentation", "bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonInstanceSegmentation: - """Create an instance of PredictionSingletonInstanceSegmentation from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonInstanceSegmentation: - """Create an instance of PredictionSingletonInstanceSegmentation from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonInstanceSegmentation.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonInstanceSegmentation) in the input: " + str(obj)) - - _obj = PredictionSingletonInstanceSegmentation.parse_obj({ - "type": obj.get("type"), - "task_name": obj.get("taskName"), - "crop_dataset_id": obj.get("cropDatasetId"), - "crop_sample_id": obj.get("cropSampleId"), - "category_id": obj.get("categoryId"), - "score": obj.get("score"), - "segmentation": obj.get("segmentation"), - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation_all_of.py deleted file mode 100644 index 9cb8faf4a..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_instance_segmentation_all_of.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class PredictionSingletonInstanceSegmentationAllOf(BaseModel): - """ - PredictionSingletonInstanceSegmentationAllOf - """ - segmentation: conlist(conint(strict=True, ge=0)) = Field(..., description="Run Length Encoding (RLE) as outlined by https://docs.lightly.ai/docs/prediction-format#semantic-segmentation ") - bbox: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4) = Field(..., description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["segmentation", "bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonInstanceSegmentationAllOf: - """Create an instance of PredictionSingletonInstanceSegmentationAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonInstanceSegmentationAllOf: - """Create an instance of PredictionSingletonInstanceSegmentationAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonInstanceSegmentationAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonInstanceSegmentationAllOf) in the input: " + str(obj)) - - _obj = PredictionSingletonInstanceSegmentationAllOf.parse_obj({ - "segmentation": obj.get("segmentation"), - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection.py deleted file mode 100644 index be66eae4a..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase - -class PredictionSingletonKeypointDetection(PredictionSingletonBase): - """ - PredictionSingletonKeypointDetection - """ - keypoints: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], min_items=3) = Field(..., description="[x1, y2, s1, ..., xk, yk, sk] as outlined by https://docs.lightly.ai/docs/prediction-format#keypoint-detection ") - bbox: Optional[conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4)] = Field(None, description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score", "keypoints", "bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonKeypointDetection: - """Create an instance of PredictionSingletonKeypointDetection from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonKeypointDetection: - """Create an instance of PredictionSingletonKeypointDetection from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonKeypointDetection.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonKeypointDetection) in the input: " + str(obj)) - - _obj = PredictionSingletonKeypointDetection.parse_obj({ - "type": obj.get("type"), - "task_name": obj.get("taskName"), - "crop_dataset_id": obj.get("cropDatasetId"), - "crop_sample_id": obj.get("cropSampleId"), - "category_id": obj.get("categoryId"), - "score": obj.get("score"), - "keypoints": obj.get("keypoints"), - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection_all_of.py deleted file mode 100644 index d5cfa8795..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_keypoint_detection_all_of.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class PredictionSingletonKeypointDetectionAllOf(BaseModel): - """ - PredictionSingletonKeypointDetectionAllOf - """ - keypoints: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], min_items=3) = Field(..., description="[x1, y2, s1, ..., xk, yk, sk] as outlined by https://docs.lightly.ai/docs/prediction-format#keypoint-detection ") - bbox: Optional[conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4)] = Field(None, description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["keypoints", "bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonKeypointDetectionAllOf: - """Create an instance of PredictionSingletonKeypointDetectionAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonKeypointDetectionAllOf: - """Create an instance of PredictionSingletonKeypointDetectionAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonKeypointDetectionAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonKeypointDetectionAllOf) in the input: " + str(obj)) - - _obj = PredictionSingletonKeypointDetectionAllOf.parse_obj({ - "keypoints": obj.get("keypoints"), - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection.py deleted file mode 100644 index bff2c8d22..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase - -class PredictionSingletonObjectDetection(PredictionSingletonBase): - """ - PredictionSingletonObjectDetection - """ - bbox: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4) = Field(..., description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score", "bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonObjectDetection: - """Create an instance of PredictionSingletonObjectDetection from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonObjectDetection: - """Create an instance of PredictionSingletonObjectDetection from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonObjectDetection.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonObjectDetection) in the input: " + str(obj)) - - _obj = PredictionSingletonObjectDetection.parse_obj({ - "type": obj.get("type"), - "task_name": obj.get("taskName"), - "crop_dataset_id": obj.get("cropDatasetId"), - "crop_sample_id": obj.get("cropSampleId"), - "category_id": obj.get("categoryId"), - "score": obj.get("score"), - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection_all_of.py deleted file mode 100644 index 24fb056b2..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_object_detection_all_of.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class PredictionSingletonObjectDetectionAllOf(BaseModel): - """ - PredictionSingletonObjectDetectionAllOf - """ - bbox: conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=4, min_items=4) = Field(..., description="The bbox of where a prediction task yielded a finding. [x, y, width, height]") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["bbox", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonObjectDetectionAllOf: - """Create an instance of PredictionSingletonObjectDetectionAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonObjectDetectionAllOf: - """Create an instance of PredictionSingletonObjectDetectionAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonObjectDetectionAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonObjectDetectionAllOf) in the input: " + str(obj)) - - _obj = PredictionSingletonObjectDetectionAllOf.parse_obj({ - "bbox": obj.get("bbox"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation.py deleted file mode 100644 index ef595d400..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_singleton_base import PredictionSingletonBase - -class PredictionSingletonSemanticSegmentation(PredictionSingletonBase): - """ - PredictionSingletonSemanticSegmentation - """ - segmentation: conlist(conint(strict=True, ge=0)) = Field(..., description="Run Length Encoding (RLE) as outlined by https://docs.lightly.ai/docs/prediction-format#semantic-segmentation ") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["type", "taskName", "cropDatasetId", "cropSampleId", "categoryId", "score", "segmentation", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonSemanticSegmentation: - """Create an instance of PredictionSingletonSemanticSegmentation from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonSemanticSegmentation: - """Create an instance of PredictionSingletonSemanticSegmentation from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonSemanticSegmentation.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonSemanticSegmentation) in the input: " + str(obj)) - - _obj = PredictionSingletonSemanticSegmentation.parse_obj({ - "type": obj.get("type"), - "task_name": obj.get("taskName"), - "crop_dataset_id": obj.get("cropDatasetId"), - "crop_sample_id": obj.get("cropSampleId"), - "category_id": obj.get("categoryId"), - "score": obj.get("score"), - "segmentation": obj.get("segmentation"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation_all_of.py deleted file mode 100644 index cdbff3b3c..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_singleton_semantic_segmentation_all_of.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class PredictionSingletonSemanticSegmentationAllOf(BaseModel): - """ - PredictionSingletonSemanticSegmentationAllOf - """ - segmentation: conlist(conint(strict=True, ge=0)) = Field(..., description="Run Length Encoding (RLE) as outlined by https://docs.lightly.ai/docs/prediction-format#semantic-segmentation ") - probabilities: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)])] = Field(None, description="The probabilities of it being a certain category other than the one which was selected. The sum of all probabilities should equal 1.") - __properties = ["segmentation", "probabilities"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionSingletonSemanticSegmentationAllOf: - """Create an instance of PredictionSingletonSemanticSegmentationAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionSingletonSemanticSegmentationAllOf: - """Create an instance of PredictionSingletonSemanticSegmentationAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionSingletonSemanticSegmentationAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionSingletonSemanticSegmentationAllOf) in the input: " + str(obj)) - - _obj = PredictionSingletonSemanticSegmentationAllOf.parse_obj({ - "segmentation": obj.get("segmentation"), - "probabilities": obj.get("probabilities") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema.py deleted file mode 100644 index 469dcd4da..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema.py +++ /dev/null @@ -1,183 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_keypoint import PredictionTaskSchemaKeypoint -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_simple import PredictionTaskSchemaSimple -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -PREDICTIONTASKSCHEMA_ONE_OF_SCHEMAS = ["PredictionTaskSchemaKeypoint", "PredictionTaskSchemaSimple"] - -class PredictionTaskSchema(BaseModel): - """ - PredictionTaskSchema - """ - # data type: PredictionTaskSchemaSimple - oneof_schema_1_validator: Optional[PredictionTaskSchemaSimple] = None - # data type: PredictionTaskSchemaKeypoint - oneof_schema_2_validator: Optional[PredictionTaskSchemaKeypoint] = None - actual_instance: Any - one_of_schemas: List[str] = Field(PREDICTIONTASKSCHEMA_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - discriminator_value_class_map = { - } - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = PredictionTaskSchema.construct() - error_messages = [] - match = 0 - # validate data type: PredictionTaskSchemaSimple - if not isinstance(v, PredictionTaskSchemaSimple): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionTaskSchemaSimple`") - else: - match += 1 - # validate data type: PredictionTaskSchemaKeypoint - if not isinstance(v, PredictionTaskSchemaKeypoint): - error_messages.append(f"Error! Input type `{type(v)}` is not `PredictionTaskSchemaKeypoint`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in PredictionTaskSchema with oneOf schemas: PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in PredictionTaskSchema with oneOf schemas: PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchema: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchema: - """Returns the object represented by the json string""" - instance = PredictionTaskSchema.construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("type") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `type` in the input.") - - # check if data type is `PredictionTaskSchemaSimple` - if _data_type == "CLASSIFICATION": - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaSimple` - if _data_type == "INSTANCE_SEGMENTATION": - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaKeypoint` - if _data_type == "KEYPOINT_DETECTION": - instance.actual_instance = PredictionTaskSchemaKeypoint.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaSimple` - if _data_type == "OBJECT_DETECTION": - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaKeypoint` - if _data_type == "PredictionTaskSchemaKeypoint": - instance.actual_instance = PredictionTaskSchemaKeypoint.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaSimple` - if _data_type == "PredictionTaskSchemaSimple": - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - return instance - - # check if data type is `PredictionTaskSchemaSimple` - if _data_type == "SEMANTIC_SEGMENTATION": - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - return instance - - # deserialize data into PredictionTaskSchemaSimple - try: - instance.actual_instance = PredictionTaskSchemaSimple.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into PredictionTaskSchemaKeypoint - try: - instance.actual_instance = PredictionTaskSchemaKeypoint.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into PredictionTaskSchema with oneOf schemas: PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into PredictionTaskSchema with oneOf schemas: PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_base.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_base.py deleted file mode 100644 index a657ec939..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_base.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json -import lightly.openapi_generated.swagger_client.models - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator - -class PredictionTaskSchemaBase(BaseModel): - """ - The schema for predictions or labels when doing classification, object detection, keypoint detection or instance segmentation - """ - name: constr(strict=True, min_length=1) = Field(..., description="A name which is safe to have as a file/folder name in a file system") - type: StrictStr = Field(..., description="This is the TaskType. Due to openapi.oneOf fuckery with discriminators, this needs to be a string") - __properties = ["name", "type"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 ._-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - # JSON field name that stores the object type - __discriminator_property_name = 'type' - - # discriminator mappings - __discriminator_value_class_map = { - 'PredictionTaskSchemaKeypoint': 'PredictionTaskSchemaKeypoint', - 'PredictionTaskSchemaSimple': 'PredictionTaskSchemaSimple' - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Union(PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple): - """Create an instance of PredictionTaskSchemaBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Union(PredictionTaskSchemaKeypoint, PredictionTaskSchemaSimple): - """Create an instance of PredictionTaskSchemaBase from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = getattr(lightly.openapi_generated.swagger_client.models, object_type) - return klass.from_dict(obj) - else: - raise ValueError("PredictionTaskSchemaBase failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category.py deleted file mode 100644 index 505a8b7e1..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint, constr - -class PredictionTaskSchemaCategory(BaseModel): - """ - The link between the categoryId and the name that should be used - """ - id: conint(strict=True, ge=0) = Field(..., description="The id of the category. Needs to be a positive integer but can be any integer (gaps are allowed, does not need to be sequential)") - name: constr(strict=True, min_length=1) = Field(..., description="The name of the category when it should be visualized") - __properties = ["id", "name"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaCategory: - """Create an instance of PredictionTaskSchemaCategory from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaCategory: - """Create an instance of PredictionTaskSchemaCategory from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaCategory.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaCategory) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaCategory.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints.py deleted file mode 100644 index e0d9a71fa..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, conint, conlist, constr - -class PredictionTaskSchemaCategoryKeypoints(BaseModel): - """ - PredictionTaskSchemaCategoryKeypoints - """ - id: conint(strict=True, ge=0) = Field(..., description="The id of the category. Needs to be a positive integer but can be any integer (gaps are allowed, does not need to be sequential)") - name: constr(strict=True, min_length=1) = Field(..., description="The name of the category when it should be visualized") - keypoint_names: Optional[conlist(constr(strict=True, min_length=1))] = Field(None, alias="keypointNames", description="The names of the individual keypoints. E.g left-shoulder, right-shoulder, nose, etc. Must be of equal length as the number of keypoints of a keypoint detection. ") - keypoint_skeleton: Optional[conlist(conlist(conint(strict=True, ge=0), max_items=2, min_items=2))] = Field(None, alias="keypointSkeleton", description="The keypoint skeleton of a category. It is used to show the overall connectivity between keypoints. Each entry in the array describes a a single connection between two keypoints by their index. e.g [1,3],[2,4],[3,4] ") - __properties = ["id", "name", "keypointNames", "keypointSkeleton"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaCategoryKeypoints: - """Create an instance of PredictionTaskSchemaCategoryKeypoints from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaCategoryKeypoints: - """Create an instance of PredictionTaskSchemaCategoryKeypoints from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaCategoryKeypoints.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaCategoryKeypoints) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaCategoryKeypoints.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "keypoint_names": obj.get("keypointNames"), - "keypoint_skeleton": obj.get("keypointSkeleton") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints_all_of.py deleted file mode 100644 index 4dba76568..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_category_keypoints_all_of.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, conint, conlist, constr - -class PredictionTaskSchemaCategoryKeypointsAllOf(BaseModel): - """ - The link between the categoryId and the name that should be used - """ - keypoint_names: Optional[conlist(constr(strict=True, min_length=1))] = Field(None, alias="keypointNames", description="The names of the individual keypoints. E.g left-shoulder, right-shoulder, nose, etc. Must be of equal length as the number of keypoints of a keypoint detection. ") - keypoint_skeleton: Optional[conlist(conlist(conint(strict=True, ge=0), max_items=2, min_items=2))] = Field(None, alias="keypointSkeleton", description="The keypoint skeleton of a category. It is used to show the overall connectivity between keypoints. Each entry in the array describes a a single connection between two keypoints by their index. e.g [1,3],[2,4],[3,4] ") - __properties = ["keypointNames", "keypointSkeleton"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaCategoryKeypointsAllOf: - """Create an instance of PredictionTaskSchemaCategoryKeypointsAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaCategoryKeypointsAllOf: - """Create an instance of PredictionTaskSchemaCategoryKeypointsAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaCategoryKeypointsAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaCategoryKeypointsAllOf) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaCategoryKeypointsAllOf.parse_obj({ - "keypoint_names": obj.get("keypointNames"), - "keypoint_skeleton": obj.get("keypointSkeleton") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint.py deleted file mode 100644 index 612d9677d..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_base import PredictionTaskSchemaBase -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints import PredictionTaskSchemaCategoryKeypoints - -class PredictionTaskSchemaKeypoint(PredictionTaskSchemaBase): - """ - PredictionTaskSchemaKeypoint - """ - categories: conlist(PredictionTaskSchemaCategoryKeypoints) = Field(..., description="An array of the categories that exist for this prediction task. The id needs to be unique") - __properties = ["name", "type", "categories"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaKeypoint: - """Create an instance of PredictionTaskSchemaKeypoint from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in categories (list) - _items = [] - if self.categories: - for _item in self.categories: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['categories' if by_alias else 'categories'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaKeypoint: - """Create an instance of PredictionTaskSchemaKeypoint from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaKeypoint.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaKeypoint) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaKeypoint.parse_obj({ - "name": obj.get("name"), - "type": obj.get("type"), - "categories": [PredictionTaskSchemaCategoryKeypoints.from_dict(_item) for _item in obj.get("categories")] if obj.get("categories") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint_all_of.py deleted file mode 100644 index 155c79b4e..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_keypoint_all_of.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category_keypoints import PredictionTaskSchemaCategoryKeypoints - -class PredictionTaskSchemaKeypointAllOf(BaseModel): - """ - The schema for predictions or labels when doing keypoint detection - """ - categories: conlist(PredictionTaskSchemaCategoryKeypoints) = Field(..., description="An array of the categories that exist for this prediction task. The id needs to be unique") - __properties = ["categories"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaKeypointAllOf: - """Create an instance of PredictionTaskSchemaKeypointAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in categories (list) - _items = [] - if self.categories: - for _item in self.categories: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['categories' if by_alias else 'categories'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaKeypointAllOf: - """Create an instance of PredictionTaskSchemaKeypointAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaKeypointAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaKeypointAllOf) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaKeypointAllOf.parse_obj({ - "categories": [PredictionTaskSchemaCategoryKeypoints.from_dict(_item) for _item in obj.get("categories")] if obj.get("categories") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple.py deleted file mode 100644 index 45aee273e..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_base import PredictionTaskSchemaBase -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category import PredictionTaskSchemaCategory - -class PredictionTaskSchemaSimple(PredictionTaskSchemaBase): - """ - PredictionTaskSchemaSimple - """ - categories: conlist(PredictionTaskSchemaCategory) = Field(..., description="An array of the categories that exist for this prediction task. The id needs to be unique") - __properties = ["name", "type", "categories"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaSimple: - """Create an instance of PredictionTaskSchemaSimple from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in categories (list) - _items = [] - if self.categories: - for _item in self.categories: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['categories' if by_alias else 'categories'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaSimple: - """Create an instance of PredictionTaskSchemaSimple from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaSimple.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaSimple) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaSimple.parse_obj({ - "name": obj.get("name"), - "type": obj.get("type"), - "categories": [PredictionTaskSchemaCategory.from_dict(_item) for _item in obj.get("categories")] if obj.get("categories") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple_all_of.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple_all_of.py deleted file mode 100644 index 9616f4fff..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schema_simple_all_of.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.prediction_task_schema_category import PredictionTaskSchemaCategory - -class PredictionTaskSchemaSimpleAllOf(BaseModel): - """ - The schema for predictions or labels when doing classification, object detection or instance segmentation - """ - categories: conlist(PredictionTaskSchemaCategory) = Field(..., description="An array of the categories that exist for this prediction task. The id needs to be unique") - __properties = ["categories"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemaSimpleAllOf: - """Create an instance of PredictionTaskSchemaSimpleAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in categories (list) - _items = [] - if self.categories: - for _item in self.categories: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['categories' if by_alias else 'categories'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemaSimpleAllOf: - """Create an instance of PredictionTaskSchemaSimpleAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemaSimpleAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemaSimpleAllOf) in the input: " + str(obj)) - - _obj = PredictionTaskSchemaSimpleAllOf.parse_obj({ - "categories": [PredictionTaskSchemaCategory.from_dict(_item) for _item in obj.get("categories")] if obj.get("categories") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/prediction_task_schemas.py b/lightly/openapi_generated/swagger_client/models/prediction_task_schemas.py deleted file mode 100644 index bbdef7dee..000000000 --- a/lightly/openapi_generated/swagger_client/models/prediction_task_schemas.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conint, conlist -from lightly.openapi_generated.swagger_client.models.prediction_task_schema import PredictionTaskSchema - -class PredictionTaskSchemas(BaseModel): - """ - PredictionTaskSchemas - """ - prediction_uuid_timestamp: conint(strict=True, ge=0) = Field(..., alias="predictionUUIDTimestamp", description="unix timestamp in milliseconds") - schemas: conlist(PredictionTaskSchema) = Field(...) - __properties = ["predictionUUIDTimestamp", "schemas"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> PredictionTaskSchemas: - """Create an instance of PredictionTaskSchemas from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in schemas (list) - _items = [] - if self.schemas: - for _item in self.schemas: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['schemas' if by_alias else 'schemas'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PredictionTaskSchemas: - """Create an instance of PredictionTaskSchemas from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PredictionTaskSchemas.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in PredictionTaskSchemas) in the input: " + str(obj)) - - _obj = PredictionTaskSchemas.parse_obj({ - "prediction_uuid_timestamp": obj.get("predictionUUIDTimestamp"), - "schemas": [PredictionTaskSchema.from_dict(_item) for _item in obj.get("schemas")] if obj.get("schemas") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/profile_basic_data.py b/lightly/openapi_generated/swagger_client/models/profile_basic_data.py deleted file mode 100644 index 295988dd2..000000000 --- a/lightly/openapi_generated/swagger_client/models/profile_basic_data.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conint, conlist -from lightly.openapi_generated.swagger_client.models.team_basic_data import TeamBasicData - -class ProfileBasicData(BaseModel): - """ - ProfileBasicData - """ - id: StrictStr = Field(...) - nickname: Optional[StrictStr] = None - name: Optional[StrictStr] = None - given_name: Optional[StrictStr] = Field(None, alias="givenName") - family_name: Optional[StrictStr] = Field(None, alias="familyName") - email: Optional[StrictStr] = None - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - teams: Optional[conlist(TeamBasicData)] = None - __properties = ["id", "nickname", "name", "givenName", "familyName", "email", "createdAt", "teams"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ProfileBasicData: - """Create an instance of ProfileBasicData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in teams (list) - _items = [] - if self.teams: - for _item in self.teams: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['teams' if by_alias else 'teams'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ProfileBasicData: - """Create an instance of ProfileBasicData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ProfileBasicData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ProfileBasicData) in the input: " + str(obj)) - - _obj = ProfileBasicData.parse_obj({ - "id": obj.get("id"), - "nickname": obj.get("nickname"), - "name": obj.get("name"), - "given_name": obj.get("givenName"), - "family_name": obj.get("familyName"), - "email": obj.get("email"), - "created_at": obj.get("createdAt"), - "teams": [TeamBasicData.from_dict(_item) for _item in obj.get("teams")] if obj.get("teams") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/profile_me_data.py b/lightly/openapi_generated/swagger_client/models/profile_me_data.py deleted file mode 100644 index 60715f113..000000000 --- a/lightly/openapi_generated/swagger_client/models/profile_me_data.py +++ /dev/null @@ -1,113 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, StrictStr, conint, conlist, constr -from lightly.openapi_generated.swagger_client.models.profile_me_data_settings import ProfileMeDataSettings -from lightly.openapi_generated.swagger_client.models.team_basic_data import TeamBasicData -from lightly.openapi_generated.swagger_client.models.user_type import UserType - -class ProfileMeData(BaseModel): - """ - ProfileMeData - """ - id: StrictStr = Field(...) - user_type: UserType = Field(..., alias="userType") - email: StrictStr = Field(..., description="email of the user") - nickname: Optional[StrictStr] = None - name: Optional[StrictStr] = None - given_name: Optional[StrictStr] = Field(None, alias="givenName") - family_name: Optional[StrictStr] = Field(None, alias="familyName") - token: Optional[constr(strict=True, min_length=5)] = Field(None, description="The user's token to be used for authentication via token querystring") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - teams: Optional[conlist(TeamBasicData)] = None - settings: ProfileMeDataSettings = Field(...) - onboarding: Optional[Union[StrictFloat, StrictInt]] = None - __properties = ["id", "userType", "email", "nickname", "name", "givenName", "familyName", "token", "createdAt", "teams", "settings", "onboarding"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ProfileMeData: - """Create an instance of ProfileMeData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in teams (list) - _items = [] - if self.teams: - for _item in self.teams: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['teams' if by_alias else 'teams'] = _items - # override the default output from pydantic by calling `to_dict()` of settings - if self.settings: - _dict['settings' if by_alias else 'settings'] = self.settings.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ProfileMeData: - """Create an instance of ProfileMeData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ProfileMeData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ProfileMeData) in the input: " + str(obj)) - - _obj = ProfileMeData.parse_obj({ - "id": obj.get("id"), - "user_type": obj.get("userType"), - "email": obj.get("email"), - "nickname": obj.get("nickname"), - "name": obj.get("name"), - "given_name": obj.get("givenName"), - "family_name": obj.get("familyName"), - "token": obj.get("token"), - "created_at": obj.get("createdAt"), - "teams": [TeamBasicData.from_dict(_item) for _item in obj.get("teams")] if obj.get("teams") is not None else None, - "settings": ProfileMeDataSettings.from_dict(obj.get("settings")) if obj.get("settings") is not None else None, - "onboarding": obj.get("onboarding") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/profile_me_data_settings.py b/lightly/openapi_generated/swagger_client/models/profile_me_data_settings.py deleted file mode 100644 index 25d1cff0e..000000000 --- a/lightly/openapi_generated/swagger_client/models/profile_me_data_settings.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr - -class ProfileMeDataSettings(BaseModel): - """ - ProfileMeDataSettings - """ - locale: Optional[StrictStr] = Field('en', description="Which locale does the user prefer") - date_format: Optional[StrictStr] = Field(None, alias="dateFormat", description="Which format for dates does the user prefer") - number_format: Optional[StrictStr] = Field(None, alias="numberFormat", description="Which format for numbers does the user prefer") - additional_properties: Dict[str, Any] = {} - __properties = ["locale", "dateFormat", "numberFormat"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ProfileMeDataSettings: - """Create an instance of ProfileMeDataSettings from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - "additional_properties" - }, - exclude_none=True) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ProfileMeDataSettings: - """Create an instance of ProfileMeDataSettings from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ProfileMeDataSettings.parse_obj(obj) - - _obj = ProfileMeDataSettings.parse_obj({ - "locale": obj.get("locale") if obj.get("locale") is not None else 'en', - "date_format": obj.get("dateFormat"), - "number_format": obj.get("numberFormat") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/questionnaire_data.py b/lightly/openapi_generated/swagger_client/models/questionnaire_data.py deleted file mode 100644 index 52182805e..000000000 --- a/lightly/openapi_generated/swagger_client/models/questionnaire_data.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, constr -from lightly.openapi_generated.swagger_client.models.sector import Sector - -class QuestionnaireData(BaseModel): - """ - QuestionnaireData - """ - company: Optional[constr(strict=True, min_length=3)] = None - sector: Optional[Sector] = None - __properties = ["company", "sector"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> QuestionnaireData: - """Create an instance of QuestionnaireData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> QuestionnaireData: - """Create an instance of QuestionnaireData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return QuestionnaireData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in QuestionnaireData) in the input: " + str(obj)) - - _obj = QuestionnaireData.parse_obj({ - "company": obj.get("company"), - "sector": obj.get("sector") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/s3_region.py b/lightly/openapi_generated/swagger_client/models/s3_region.py deleted file mode 100644 index bc056b475..000000000 --- a/lightly/openapi_generated/swagger_client/models/s3_region.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class S3Region(str, Enum): - """ - The region where your bucket is located (see https://docs.aws.amazon.com/general/latest/gr/s3.html for further information) - """ - - """ - allowed enum values - """ - US_MINUS_EAST_MINUS_2 = 'us-east-2' - US_MINUS_EAST_MINUS_1 = 'us-east-1' - US_MINUS_WEST_MINUS_1 = 'us-west-1' - US_MINUS_WEST_MINUS_2 = 'us-west-2' - AF_MINUS_SOUTH_MINUS_1 = 'af-south-1' - AP_MINUS_EAST_MINUS_1 = 'ap-east-1' - AP_MINUS_SOUTH_MINUS_2 = 'ap-south-2' - AP_MINUS_SOUTHEAST_MINUS_3 = 'ap-southeast-3' - AP_MINUS_SOUTHEAST_MINUS_4 = 'ap-southeast-4' - AP_MINUS_SOUTH_MINUS_1 = 'ap-south-1' - AP_MINUS_NORTHEAST_MINUS_3 = 'ap-northeast-3' - AP_MINUS_NORTHEAST_MINUS_2 = 'ap-northeast-2' - AP_MINUS_SOUTHEAST_MINUS_1 = 'ap-southeast-1' - AP_MINUS_SOUTHEAST_MINUS_2 = 'ap-southeast-2' - AP_MINUS_NORTHEAST_MINUS_1 = 'ap-northeast-1' - CA_MINUS_CENTRAL_MINUS_1 = 'ca-central-1' - CN_MINUS_NORTHWEST_MINUS_1 = 'cn-northwest-1' - EU_MINUS_CENTRAL_MINUS_1 = 'eu-central-1' - EU_MINUS_WEST_MINUS_1 = 'eu-west-1' - EU_MINUS_WEST_MINUS_2 = 'eu-west-2' - EU_MINUS_SOUTH_MINUS_1 = 'eu-south-1' - EU_MINUS_WEST_MINUS_3 = 'eu-west-3' - EU_MINUS_NORTH_MINUS_1 = 'eu-north-1' - EU_MINUS_SOUTH_MINUS_2 = 'eu-south-2' - EU_MINUS_CENTRAL_MINUS_2 = 'eu-central-2' - ME_MINUS_SOUTH_MINUS_1 = 'me-south-1' - ME_MINUS_CENTRAL_MINUS_1 = 'me-central-1' - SA_MINUS_EAST_MINUS_1 = 'sa-east-1' - US_MINUS_GOV_MINUS_EAST = 'us-gov-east' - US_MINUS_GOV_MINUS_WEST = 'us-gov-west' - - @classmethod - def from_json(cls, json_str: str) -> 'S3Region': - """Create an instance of S3Region from a JSON string""" - return S3Region(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/sama_task.py b/lightly/openapi_generated/swagger_client/models/sama_task.py deleted file mode 100644 index 2cc767742..000000000 --- a/lightly/openapi_generated/swagger_client/models/sama_task.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictInt -from lightly.openapi_generated.swagger_client.models.sama_task_data import SamaTaskData - -class SamaTask(BaseModel): - """ - SamaTask - """ - priority: Optional[StrictInt] = None - reserve_for: Optional[StrictInt] = None - data: SamaTaskData = Field(...) - __properties = ["priority", "reserve_for", "data"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SamaTask: - """Create an instance of SamaTask from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of data - if self.data: - _dict['data' if by_alias else 'data'] = self.data.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SamaTask: - """Create an instance of SamaTask from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SamaTask.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SamaTask) in the input: " + str(obj)) - - _obj = SamaTask.parse_obj({ - "priority": obj.get("priority"), - "reserve_for": obj.get("reserve_for"), - "data": SamaTaskData.from_dict(obj.get("data")) if obj.get("data") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sama_task_data.py b/lightly/openapi_generated/swagger_client/models/sama_task_data.py deleted file mode 100644 index 781fd1b34..000000000 --- a/lightly/openapi_generated/swagger_client/models/sama_task_data.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr - -class SamaTaskData(BaseModel): - """ - SamaTaskData - """ - id: StrictInt = Field(...) - url: StrictStr = Field(..., description="A URL which allows anyone in possession of said URL for the time specified by the expiresIn query param to access the resource") - image: Optional[StrictStr] = Field(None, description="A URL which allows anyone in possession of said URL for the time specified by the expiresIn query param to access the resource") - lightly_file_name: Optional[StrictStr] = Field(None, alias="lightlyFileName", description="The original fileName of the sample. This is unique within a dataset") - lightly_meta_info: Optional[StrictStr] = Field(None, alias="lightlyMetaInfo") - __properties = ["id", "url", "image", "lightlyFileName", "lightlyMetaInfo"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SamaTaskData: - """Create an instance of SamaTaskData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SamaTaskData: - """Create an instance of SamaTaskData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SamaTaskData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SamaTaskData) in the input: " + str(obj)) - - _obj = SamaTaskData.parse_obj({ - "id": obj.get("id"), - "url": obj.get("url"), - "image": obj.get("image"), - "lightly_file_name": obj.get("lightlyFileName"), - "lightly_meta_info": obj.get("lightlyMetaInfo") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_create_request.py b/lightly/openapi_generated/swagger_client/models/sample_create_request.py deleted file mode 100644 index 3c292a76a..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_create_request.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.crop_data import CropData -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData -from lightly.openapi_generated.swagger_client.models.video_frame_data import VideoFrameData - -class SampleCreateRequest(BaseModel): - """ - SampleCreateRequest - """ - file_name: StrictStr = Field(..., alias="fileName") - thumb_name: Optional[StrictStr] = Field(None, alias="thumbName") - exif: Optional[Dict[str, Any]] = None - meta_data: Optional[SampleMetaData] = Field(None, alias="metaData") - custom_meta_data: Optional[Dict[str, Any]] = Field(None, alias="customMetaData") - video_frame_data: Optional[VideoFrameData] = Field(None, alias="videoFrameData") - crop_data: Optional[CropData] = Field(None, alias="cropData") - __properties = ["fileName", "thumbName", "exif", "metaData", "customMetaData", "videoFrameData", "cropData"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleCreateRequest: - """Create an instance of SampleCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of meta_data - if self.meta_data: - _dict['metaData' if by_alias else 'meta_data'] = self.meta_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of video_frame_data - if self.video_frame_data: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = self.video_frame_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of crop_data - if self.crop_data: - _dict['cropData' if by_alias else 'crop_data'] = self.crop_data.to_dict(by_alias=by_alias) - # set to None if custom_meta_data (nullable) is None - # and __fields_set__ contains the field - if self.custom_meta_data is None and "custom_meta_data" in self.__fields_set__: - _dict['customMetaData' if by_alias else 'custom_meta_data'] = None - - # set to None if video_frame_data (nullable) is None - # and __fields_set__ contains the field - if self.video_frame_data is None and "video_frame_data" in self.__fields_set__: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = None - - # set to None if crop_data (nullable) is None - # and __fields_set__ contains the field - if self.crop_data is None and "crop_data" in self.__fields_set__: - _dict['cropData' if by_alias else 'crop_data'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleCreateRequest: - """Create an instance of SampleCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleCreateRequest) in the input: " + str(obj)) - - _obj = SampleCreateRequest.parse_obj({ - "file_name": obj.get("fileName"), - "thumb_name": obj.get("thumbName"), - "exif": obj.get("exif"), - "meta_data": SampleMetaData.from_dict(obj.get("metaData")) if obj.get("metaData") is not None else None, - "custom_meta_data": obj.get("customMetaData"), - "video_frame_data": VideoFrameData.from_dict(obj.get("videoFrameData")) if obj.get("videoFrameData") is not None else None, - "crop_data": CropData.from_dict(obj.get("cropData")) if obj.get("cropData") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_data.py b/lightly/openapi_generated/swagger_client/models/sample_data.py deleted file mode 100644 index 84d3c39fb..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_data.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.crop_data import CropData -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData -from lightly.openapi_generated.swagger_client.models.sample_type import SampleType -from lightly.openapi_generated.swagger_client.models.video_frame_data import VideoFrameData - -class SampleData(BaseModel): - """ - SampleData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - type: SampleType = Field(...) - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - file_name: StrictStr = Field(..., alias="fileName") - thumb_name: Optional[StrictStr] = Field(None, alias="thumbName") - exif: Optional[Dict[str, Any]] = None - index: Optional[StrictInt] = None - created_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="lastModifiedAt", description="unix timestamp in milliseconds") - meta_data: Optional[SampleMetaData] = Field(None, alias="metaData") - custom_meta_data: Optional[Dict[str, Any]] = Field(None, alias="customMetaData") - video_frame_data: Optional[VideoFrameData] = Field(None, alias="videoFrameData") - crop_data: Optional[CropData] = Field(None, alias="cropData") - __properties = ["id", "type", "datasetId", "fileName", "thumbName", "exif", "index", "createdAt", "lastModifiedAt", "metaData", "customMetaData", "videoFrameData", "cropData"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleData: - """Create an instance of SampleData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of meta_data - if self.meta_data: - _dict['metaData' if by_alias else 'meta_data'] = self.meta_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of video_frame_data - if self.video_frame_data: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = self.video_frame_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of crop_data - if self.crop_data: - _dict['cropData' if by_alias else 'crop_data'] = self.crop_data.to_dict(by_alias=by_alias) - # set to None if thumb_name (nullable) is None - # and __fields_set__ contains the field - if self.thumb_name is None and "thumb_name" in self.__fields_set__: - _dict['thumbName' if by_alias else 'thumb_name'] = None - - # set to None if exif (nullable) is None - # and __fields_set__ contains the field - if self.exif is None and "exif" in self.__fields_set__: - _dict['exif' if by_alias else 'exif'] = None - - # set to None if custom_meta_data (nullable) is None - # and __fields_set__ contains the field - if self.custom_meta_data is None and "custom_meta_data" in self.__fields_set__: - _dict['customMetaData' if by_alias else 'custom_meta_data'] = None - - # set to None if video_frame_data (nullable) is None - # and __fields_set__ contains the field - if self.video_frame_data is None and "video_frame_data" in self.__fields_set__: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = None - - # set to None if crop_data (nullable) is None - # and __fields_set__ contains the field - if self.crop_data is None and "crop_data" in self.__fields_set__: - _dict['cropData' if by_alias else 'crop_data'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleData: - """Create an instance of SampleData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleData) in the input: " + str(obj)) - - _obj = SampleData.parse_obj({ - "id": obj.get("id"), - "type": obj.get("type"), - "dataset_id": obj.get("datasetId"), - "file_name": obj.get("fileName"), - "thumb_name": obj.get("thumbName"), - "exif": obj.get("exif"), - "index": obj.get("index"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "meta_data": SampleMetaData.from_dict(obj.get("metaData")) if obj.get("metaData") is not None else None, - "custom_meta_data": obj.get("customMetaData"), - "video_frame_data": VideoFrameData.from_dict(obj.get("videoFrameData")) if obj.get("videoFrameData") is not None else None, - "crop_data": CropData.from_dict(obj.get("cropData")) if obj.get("cropData") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_data_modes.py b/lightly/openapi_generated/swagger_client/models/sample_data_modes.py deleted file mode 100644 index 736754e2e..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_data_modes.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, StrictStr, conint, constr, validator -from lightly.openapi_generated.swagger_client.models.crop_data import CropData -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData -from lightly.openapi_generated.swagger_client.models.sample_type import SampleType -from lightly.openapi_generated.swagger_client.models.video_frame_data import VideoFrameData - -class SampleDataModes(BaseModel): - """ - SampleDataModes - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - type: Optional[SampleType] = None - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - file_name: Optional[StrictStr] = Field(None, alias="fileName") - thumb_name: Optional[StrictStr] = Field(None, alias="thumbName") - exif: Optional[Dict[str, Any]] = None - index: Optional[StrictInt] = None - created_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="lastModifiedAt", description="unix timestamp in milliseconds") - meta_data: Optional[SampleMetaData] = Field(None, alias="metaData") - custom_meta_data: Optional[Dict[str, Any]] = Field(None, alias="customMetaData") - video_frame_data: Optional[VideoFrameData] = Field(None, alias="videoFrameData") - crop_data: Optional[CropData] = Field(None, alias="cropData") - __properties = ["id", "type", "datasetId", "fileName", "thumbName", "exif", "index", "createdAt", "lastModifiedAt", "metaData", "customMetaData", "videoFrameData", "cropData"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleDataModes: - """Create an instance of SampleDataModes from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of meta_data - if self.meta_data: - _dict['metaData' if by_alias else 'meta_data'] = self.meta_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of video_frame_data - if self.video_frame_data: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = self.video_frame_data.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of crop_data - if self.crop_data: - _dict['cropData' if by_alias else 'crop_data'] = self.crop_data.to_dict(by_alias=by_alias) - # set to None if thumb_name (nullable) is None - # and __fields_set__ contains the field - if self.thumb_name is None and "thumb_name" in self.__fields_set__: - _dict['thumbName' if by_alias else 'thumb_name'] = None - - # set to None if exif (nullable) is None - # and __fields_set__ contains the field - if self.exif is None and "exif" in self.__fields_set__: - _dict['exif' if by_alias else 'exif'] = None - - # set to None if custom_meta_data (nullable) is None - # and __fields_set__ contains the field - if self.custom_meta_data is None and "custom_meta_data" in self.__fields_set__: - _dict['customMetaData' if by_alias else 'custom_meta_data'] = None - - # set to None if video_frame_data (nullable) is None - # and __fields_set__ contains the field - if self.video_frame_data is None and "video_frame_data" in self.__fields_set__: - _dict['videoFrameData' if by_alias else 'video_frame_data'] = None - - # set to None if crop_data (nullable) is None - # and __fields_set__ contains the field - if self.crop_data is None and "crop_data" in self.__fields_set__: - _dict['cropData' if by_alias else 'crop_data'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleDataModes: - """Create an instance of SampleDataModes from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleDataModes.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleDataModes) in the input: " + str(obj)) - - _obj = SampleDataModes.parse_obj({ - "id": obj.get("id"), - "type": obj.get("type"), - "dataset_id": obj.get("datasetId"), - "file_name": obj.get("fileName"), - "thumb_name": obj.get("thumbName"), - "exif": obj.get("exif"), - "index": obj.get("index"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "meta_data": SampleMetaData.from_dict(obj.get("metaData")) if obj.get("metaData") is not None else None, - "custom_meta_data": obj.get("customMetaData"), - "video_frame_data": VideoFrameData.from_dict(obj.get("videoFrameData")) if obj.get("videoFrameData") is not None else None, - "crop_data": CropData.from_dict(obj.get("cropData")) if obj.get("cropData") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_meta_data.py b/lightly/openapi_generated/swagger_client/models/sample_meta_data.py deleted file mode 100644 index 2153a9487..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_meta_data.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist - -class SampleMetaData(BaseModel): - """ - SampleMetaData - """ - custom: Optional[Dict[str, Any]] = None - dynamic: Optional[Dict[str, Any]] = None - sharpness: Optional[Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)]] = None - luminance: Optional[Union[confloat(le=100, ge=0, strict=True), conint(le=100, ge=0, strict=True)]] = None - size_in_bytes: Optional[conint(strict=True, ge=0)] = Field(None, alias="sizeInBytes") - snr: Optional[Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)]] = None - uniform_row_ratio: Optional[Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="uniformRowRatio") - mean: Optional[conlist(Union[confloat(le=1, ge=0, strict=True), conint(le=1, ge=0, strict=True)], max_items=3, min_items=3)] = None - shape: Optional[conlist(conint(strict=True, ge=0), max_items=3, min_items=3)] = None - std: Optional[conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=3, min_items=3)] = None - sum_of_squares: Optional[conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=3, min_items=3)] = Field(None, alias="sumOfSquares") - sum_of_values: Optional[conlist(Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)], max_items=3, min_items=3)] = Field(None, alias="sumOfValues") - __properties = ["custom", "dynamic", "sharpness", "luminance", "sizeInBytes", "snr", "uniformRowRatio", "mean", "shape", "std", "sumOfSquares", "sumOfValues"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleMetaData: - """Create an instance of SampleMetaData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # set to None if custom (nullable) is None - # and __fields_set__ contains the field - if self.custom is None and "custom" in self.__fields_set__: - _dict['custom' if by_alias else 'custom'] = None - - # set to None if dynamic (nullable) is None - # and __fields_set__ contains the field - if self.dynamic is None and "dynamic" in self.__fields_set__: - _dict['dynamic' if by_alias else 'dynamic'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleMetaData: - """Create an instance of SampleMetaData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleMetaData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleMetaData) in the input: " + str(obj)) - - _obj = SampleMetaData.parse_obj({ - "custom": obj.get("custom"), - "dynamic": obj.get("dynamic"), - "sharpness": obj.get("sharpness"), - "luminance": obj.get("luminance"), - "size_in_bytes": obj.get("sizeInBytes"), - "snr": obj.get("snr"), - "uniform_row_ratio": obj.get("uniformRowRatio"), - "mean": obj.get("mean"), - "shape": obj.get("shape"), - "std": obj.get("std"), - "sum_of_squares": obj.get("sumOfSquares"), - "sum_of_values": obj.get("sumOfValues") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_partial_mode.py b/lightly/openapi_generated/swagger_client/models/sample_partial_mode.py deleted file mode 100644 index 65574d616..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_partial_mode.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SamplePartialMode(str, Enum): - """ - ids: return only the id fileNames: return the id and fileName full: return all data - """ - - """ - allowed enum values - """ - IDS = 'ids' - FILENAMES = 'fileNames' - FULL = 'full' - - @classmethod - def from_json(cls, json_str: str) -> 'SamplePartialMode': - """Create an instance of SamplePartialMode from a JSON string""" - return SamplePartialMode(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/sample_sort_by.py b/lightly/openapi_generated/swagger_client/models/sample_sort_by.py deleted file mode 100644 index 4ead865e5..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_sort_by.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SampleSortBy(str, Enum): - """ - SampleSortBy - """ - - """ - allowed enum values - """ - ID = '_id' - INDEX = 'index' - - @classmethod - def from_json(cls, json_str: str) -> 'SampleSortBy': - """Create an instance of SampleSortBy from a JSON string""" - return SampleSortBy(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/sample_type.py b/lightly/openapi_generated/swagger_client/models/sample_type.py deleted file mode 100644 index 8b31e0739..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_type.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SampleType(str, Enum): - """ - Type of the sample (VideoFrame vs IMAGE vs CROP). Determined by the API! - """ - - """ - allowed enum values - """ - CROP = 'CROP' - IMAGE = 'IMAGE' - VIDEO_FRAME = 'VIDEO_FRAME' - - @classmethod - def from_json(cls, json_str: str) -> 'SampleType': - """Create an instance of SampleType from a JSON string""" - return SampleType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/sample_update_request.py b/lightly/openapi_generated/swagger_client/models/sample_update_request.py deleted file mode 100644 index 7aa1a199b..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_update_request.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.sample_meta_data import SampleMetaData - -class SampleUpdateRequest(BaseModel): - """ - SampleUpdateRequest - """ - file_name: Optional[StrictStr] = Field(None, alias="fileName") - thumb_name: Optional[StrictStr] = Field(None, alias="thumbName") - exif: Optional[Dict[str, Any]] = None - meta_data: Optional[SampleMetaData] = Field(None, alias="metaData") - custom_meta_data: Optional[Dict[str, Any]] = Field(None, alias="customMetaData") - __properties = ["fileName", "thumbName", "exif", "metaData", "customMetaData"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleUpdateRequest: - """Create an instance of SampleUpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of meta_data - if self.meta_data: - _dict['metaData' if by_alias else 'meta_data'] = self.meta_data.to_dict(by_alias=by_alias) - # set to None if custom_meta_data (nullable) is None - # and __fields_set__ contains the field - if self.custom_meta_data is None and "custom_meta_data" in self.__fields_set__: - _dict['customMetaData' if by_alias else 'custom_meta_data'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleUpdateRequest: - """Create an instance of SampleUpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleUpdateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleUpdateRequest) in the input: " + str(obj)) - - _obj = SampleUpdateRequest.parse_obj({ - "file_name": obj.get("fileName"), - "thumb_name": obj.get("thumbName"), - "exif": obj.get("exif"), - "meta_data": SampleMetaData.from_dict(obj.get("metaData")) if obj.get("metaData") is not None else None, - "custom_meta_data": obj.get("customMetaData") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sample_write_urls.py b/lightly/openapi_generated/swagger_client/models/sample_write_urls.py deleted file mode 100644 index 73435bcba..000000000 --- a/lightly/openapi_generated/swagger_client/models/sample_write_urls.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class SampleWriteUrls(BaseModel): - """ - SampleWriteUrls - """ - full: StrictStr = Field(...) - thumb: StrictStr = Field(...) - __properties = ["full", "thumb"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SampleWriteUrls: - """Create an instance of SampleWriteUrls from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SampleWriteUrls: - """Create an instance of SampleWriteUrls from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SampleWriteUrls.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SampleWriteUrls) in the input: " + str(obj)) - - _obj = SampleWriteUrls.parse_obj({ - "full": obj.get("full"), - "thumb": obj.get("thumb") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sampling_config.py b/lightly/openapi_generated/swagger_client/models/sampling_config.py deleted file mode 100644 index 8a837226e..000000000 --- a/lightly/openapi_generated/swagger_client/models/sampling_config.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.sampling_config_stopping_condition import SamplingConfigStoppingCondition - -class SamplingConfig(BaseModel): - """ - SamplingConfig - """ - stopping_condition: Optional[SamplingConfigStoppingCondition] = Field(None, alias="stoppingCondition") - __properties = ["stoppingCondition"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SamplingConfig: - """Create an instance of SamplingConfig from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of stopping_condition - if self.stopping_condition: - _dict['stoppingCondition' if by_alias else 'stopping_condition'] = self.stopping_condition.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SamplingConfig: - """Create an instance of SamplingConfig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SamplingConfig.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SamplingConfig) in the input: " + str(obj)) - - _obj = SamplingConfig.parse_obj({ - "stopping_condition": SamplingConfigStoppingCondition.from_dict(obj.get("stoppingCondition")) if obj.get("stoppingCondition") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sampling_config_stopping_condition.py b/lightly/openapi_generated/swagger_client/models/sampling_config_stopping_condition.py deleted file mode 100644 index 2a560883a..000000000 --- a/lightly/openapi_generated/swagger_client/models/sampling_config_stopping_condition.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt - -class SamplingConfigStoppingCondition(BaseModel): - """ - SamplingConfigStoppingCondition - """ - n_samples: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="nSamples", description="How many samples/images should be used for the sampling. 0-1 represents a percentage of all. 1-N are absolute numbers") - min_distance: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="minDistance", description="The minimum distance sampled images should have. Before the distance would fall below, the sampling is stopped.") - __properties = ["nSamples", "minDistance"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SamplingConfigStoppingCondition: - """Create an instance of SamplingConfigStoppingCondition from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SamplingConfigStoppingCondition: - """Create an instance of SamplingConfigStoppingCondition from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SamplingConfigStoppingCondition.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SamplingConfigStoppingCondition) in the input: " + str(obj)) - - _obj = SamplingConfigStoppingCondition.parse_obj({ - "n_samples": obj.get("nSamples"), - "min_distance": obj.get("minDistance") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sampling_create_request.py b/lightly/openapi_generated/swagger_client/models/sampling_create_request.py deleted file mode 100644 index 5f2ef5648..000000000 --- a/lightly/openapi_generated/swagger_client/models/sampling_create_request.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, constr, validator -from lightly.openapi_generated.swagger_client.models.sampling_config import SamplingConfig -from lightly.openapi_generated.swagger_client.models.sampling_method import SamplingMethod - -class SamplingCreateRequest(BaseModel): - """ - SamplingCreateRequest - """ - new_tag_name: constr(strict=True, min_length=3) = Field(..., alias="newTagName", description="The name of the tag") - method: SamplingMethod = Field(...) - config: SamplingConfig = Field(...) - preselected_tag_id: Optional[constr(strict=True)] = Field(None, alias="preselectedTagId", description="MongoDB ObjectId") - query_tag_id: Optional[constr(strict=True)] = Field(None, alias="queryTagId", description="MongoDB ObjectId") - score_type: Optional[constr(strict=True, min_length=1)] = Field(None, alias="scoreType", description="Type of active learning score") - row_count: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="rowCount", description="temporary rowCount until the API/DB is aware how many they are..") - __properties = ["newTagName", "method", "config", "preselectedTagId", "queryTagId", "scoreType", "rowCount"] - - @validator('new_tag_name') - def new_tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('preselected_tag_id') - def preselected_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('query_tag_id') - def query_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SamplingCreateRequest: - """Create an instance of SamplingCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of config - if self.config: - _dict['config' if by_alias else 'config'] = self.config.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SamplingCreateRequest: - """Create an instance of SamplingCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SamplingCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SamplingCreateRequest) in the input: " + str(obj)) - - _obj = SamplingCreateRequest.parse_obj({ - "new_tag_name": obj.get("newTagName"), - "method": obj.get("method"), - "config": SamplingConfig.from_dict(obj.get("config")) if obj.get("config") is not None else None, - "preselected_tag_id": obj.get("preselectedTagId"), - "query_tag_id": obj.get("queryTagId"), - "score_type": obj.get("scoreType"), - "row_count": obj.get("rowCount") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/sampling_method.py b/lightly/openapi_generated/swagger_client/models/sampling_method.py deleted file mode 100644 index 9bdef6708..000000000 --- a/lightly/openapi_generated/swagger_client/models/sampling_method.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SamplingMethod(str, Enum): - """ - SamplingMethod - """ - - """ - allowed enum values - """ - ACTIVE_LEARNING = 'ACTIVE_LEARNING' - CORAL = 'CORAL' - CORESET = 'CORESET' - RANDOM = 'RANDOM' - - @classmethod - def from_json(cls, json_str: str) -> 'SamplingMethod': - """Create an instance of SamplingMethod from a JSON string""" - return SamplingMethod(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/sector.py b/lightly/openapi_generated/swagger_client/models/sector.py deleted file mode 100644 index b9e0cfa80..000000000 --- a/lightly/openapi_generated/swagger_client/models/sector.py +++ /dev/null @@ -1,64 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class Sector(str, Enum): - """ - Sector - """ - - """ - allowed enum values - """ - ADVERTISING = 'ADVERTISING' - AGRICULTURE = 'AGRICULTURE' - AUTOMOTIVE = 'AUTOMOTIVE' - EDUCATION = 'EDUCATION' - ENERGY = 'ENERGY' - ENTERTAINMENT = 'ENTERTAINMENT' - ENVIRONMENTAL = 'ENVIRONMENTAL' - FINANCE = 'FINANCE' - FOOD = 'FOOD' - HEALTHCARE = 'HEALTHCARE' - INTERNET_OF_THINGS = 'INTERNET_OF_THINGS' - LOGISTICS = 'LOGISTICS' - MACHINE_LEARNING = 'MACHINE_LEARNING' - MANUFACTURING = 'MANUFACTURING' - MEDICINE = 'MEDICINE' - RECYCLING = 'RECYCLING' - RETAIL = 'RETAIL' - ROBOTICS = 'ROBOTICS' - SECURITY = 'SECURITY' - SOFTWARE_DEVELOPMENT = 'SOFTWARE_DEVELOPMENT' - SPORTS = 'SPORTS' - SURVEILLANCE = 'SURVEILLANCE' - TRANSPORTATION = 'TRANSPORTATION' - OTHER = 'OTHER' - - @classmethod - def from_json(cls, json_str: str) -> 'Sector': - """Create an instance of Sector from a JSON string""" - return Sector(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config.py b/lightly/openapi_generated/swagger_client/models/selection_config.py deleted file mode 100644 index bfdc07ed0..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.selection_config_entry import SelectionConfigEntry - -class SelectionConfig(BaseModel): - """ - SelectionConfig - """ - n_samples: Optional[conint(strict=True, ge=-1)] = Field(None, alias="nSamples") - proportion_samples: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="proportionSamples") - strategies: conlist(SelectionConfigEntry, min_items=1) = Field(...) - __properties = ["nSamples", "proportionSamples", "strategies"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfig: - """Create an instance of SelectionConfig from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfig: - """Create an instance of SelectionConfig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfig.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfig) in the input: " + str(obj)) - - _obj = SelectionConfig.parse_obj({ - "n_samples": obj.get("nSamples"), - "proportion_samples": obj.get("proportionSamples"), - "strategies": [SelectionConfigEntry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_all_of.py b/lightly/openapi_generated/swagger_client/models/selection_config_all_of.py deleted file mode 100644 index 3d04824fa..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_all_of.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.selection_config_entry import SelectionConfigEntry - -class SelectionConfigAllOf(BaseModel): - """ - SelectionConfigAllOf - """ - strategies: conlist(SelectionConfigEntry, min_items=1) = Field(...) - __properties = ["strategies"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigAllOf: - """Create an instance of SelectionConfigAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigAllOf: - """Create an instance of SelectionConfigAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigAllOf) in the input: " + str(obj)) - - _obj = SelectionConfigAllOf.parse_obj({ - "strategies": [SelectionConfigEntry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_base.py b/lightly/openapi_generated/swagger_client/models/selection_config_base.py deleted file mode 100644 index 51b358cf1..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_base.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint - -class SelectionConfigBase(BaseModel): - """ - SelectionConfigBase - """ - n_samples: Optional[conint(strict=True, ge=-1)] = Field(None, alias="nSamples") - proportion_samples: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="proportionSamples") - __properties = ["nSamples", "proportionSamples"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigBase: - """Create an instance of SelectionConfigBase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigBase: - """Create an instance of SelectionConfigBase from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigBase.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigBase) in the input: " + str(obj)) - - _obj = SelectionConfigBase.parse_obj({ - "n_samples": obj.get("nSamples"), - "proportion_samples": obj.get("proportionSamples") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_entry.py b/lightly/openapi_generated/swagger_client/models/selection_config_entry.py deleted file mode 100644 index 973d438f3..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_entry.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.selection_config_entry_input import SelectionConfigEntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_entry_strategy import SelectionConfigEntryStrategy - -class SelectionConfigEntry(BaseModel): - """ - SelectionConfigEntry - """ - input: SelectionConfigEntryInput = Field(...) - strategy: SelectionConfigEntryStrategy = Field(...) - __properties = ["input", "strategy"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigEntry: - """Create an instance of SelectionConfigEntry from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of input - if self.input: - _dict['input' if by_alias else 'input'] = self.input.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of strategy - if self.strategy: - _dict['strategy' if by_alias else 'strategy'] = self.strategy.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigEntry: - """Create an instance of SelectionConfigEntry from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigEntry.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigEntry) in the input: " + str(obj)) - - _obj = SelectionConfigEntry.parse_obj({ - "input": SelectionConfigEntryInput.from_dict(obj.get("input")) if obj.get("input") is not None else None, - "strategy": SelectionConfigEntryStrategy.from_dict(obj.get("strategy")) if obj.get("strategy") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_entry_input.py b/lightly/openapi_generated/swagger_client/models/selection_config_entry_input.py deleted file mode 100644 index 28b2d923b..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_entry_input.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.selection_input_predictions_name import SelectionInputPredictionsName -from lightly.openapi_generated.swagger_client.models.selection_input_type import SelectionInputType - -class SelectionConfigEntryInput(BaseModel): - """ - SelectionConfigEntryInput - """ - type: SelectionInputType = Field(...) - task: Optional[constr(strict=True)] = Field(None, description="Since we sometimes stitch together SelectionInputTask+ActiveLearningScoreType, they need to follow the same specs of ActiveLearningScoreType. However, this can be an empty string due to internal logic. ") - score: Optional[constr(strict=True, min_length=1)] = Field(None, description="Type of active learning score") - key: Optional[constr(strict=True, min_length=1)] = None - name: Optional[SelectionInputPredictionsName] = None - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - tag_name: Optional[constr(strict=True, min_length=3)] = Field(None, alias="tagName", description="The name of the tag") - random_seed: Optional[StrictInt] = Field(None, alias="randomSeed") - categories: Optional[conlist(constr(strict=True, min_length=1), min_items=1, unique_items=True)] = None - __properties = ["type", "task", "score", "key", "name", "datasetId", "tagName", "randomSeed", "categories"] - - @validator('task') - def task_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('score') - def score_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_name') - def tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigEntryInput: - """Create an instance of SelectionConfigEntryInput from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigEntryInput: - """Create an instance of SelectionConfigEntryInput from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigEntryInput.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigEntryInput) in the input: " + str(obj)) - - _obj = SelectionConfigEntryInput.parse_obj({ - "type": obj.get("type"), - "task": obj.get("task"), - "score": obj.get("score"), - "key": obj.get("key"), - "name": obj.get("name"), - "dataset_id": obj.get("datasetId"), - "tag_name": obj.get("tagName"), - "random_seed": obj.get("randomSeed"), - "categories": obj.get("categories") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_entry_strategy.py b/lightly/openapi_generated/swagger_client/models/selection_config_entry_strategy.py deleted file mode 100644 index 67bf84527..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_entry_strategy.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt -from lightly.openapi_generated.swagger_client.models.selection_strategy_threshold_operation import SelectionStrategyThresholdOperation -from lightly.openapi_generated.swagger_client.models.selection_strategy_type import SelectionStrategyType - -class SelectionConfigEntryStrategy(BaseModel): - """ - SelectionConfigEntryStrategy - """ - type: SelectionStrategyType = Field(...) - stopping_condition_minimum_distance: Optional[Union[StrictFloat, StrictInt]] = None - threshold: Optional[Union[StrictFloat, StrictInt]] = None - operation: Optional[SelectionStrategyThresholdOperation] = None - target: Optional[Dict[str, Any]] = None - __properties = ["type", "stopping_condition_minimum_distance", "threshold", "operation", "target"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigEntryStrategy: - """Create an instance of SelectionConfigEntryStrategy from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigEntryStrategy: - """Create an instance of SelectionConfigEntryStrategy from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigEntryStrategy.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigEntryStrategy) in the input: " + str(obj)) - - _obj = SelectionConfigEntryStrategy.parse_obj({ - "type": obj.get("type"), - "stopping_condition_minimum_distance": obj.get("stopping_condition_minimum_distance"), - "threshold": obj.get("threshold"), - "operation": obj.get("operation"), - "target": obj.get("target") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3.py deleted file mode 100644 index 80aed78fb..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry import SelectionConfigV3Entry - -class SelectionConfigV3(BaseModel): - """ - SelectionConfigV3 - """ - n_samples: Optional[conint(strict=True, ge=-1)] = Field(None, alias="nSamples") - proportion_samples: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="proportionSamples") - strategies: conlist(SelectionConfigV3Entry, min_items=1) = Field(...) - __properties = ["nSamples", "proportionSamples", "strategies"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3: - """Create an instance of SelectionConfigV3 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3: - """Create an instance of SelectionConfigV3 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3) in the input: " + str(obj)) - - _obj = SelectionConfigV3.parse_obj({ - "n_samples": obj.get("nSamples"), - "proportion_samples": obj.get("proportionSamples"), - "strategies": [SelectionConfigV3Entry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_all_of.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_all_of.py deleted file mode 100644 index 84770bdd9..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_all_of.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, conlist -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry import SelectionConfigV3Entry - -class SelectionConfigV3AllOf(BaseModel): - """ - SelectionConfigV3AllOf - """ - strategies: conlist(SelectionConfigV3Entry, min_items=1) = Field(...) - __properties = ["strategies"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3AllOf: - """Create an instance of SelectionConfigV3AllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3AllOf: - """Create an instance of SelectionConfigV3AllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3AllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3AllOf) in the input: " + str(obj)) - - _obj = SelectionConfigV3AllOf.parse_obj({ - "strategies": [SelectionConfigV3Entry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry.py deleted file mode 100644 index 834cbd317..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_input import SelectionConfigV3EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy import SelectionConfigV3EntryStrategy - -class SelectionConfigV3Entry(BaseModel): - """ - SelectionConfigV3Entry - """ - input: SelectionConfigV3EntryInput = Field(...) - strategy: SelectionConfigV3EntryStrategy = Field(...) - __properties = ["input", "strategy"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3Entry: - """Create an instance of SelectionConfigV3Entry from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of input - if self.input: - _dict['input' if by_alias else 'input'] = self.input.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of strategy - if self.strategy: - _dict['strategy' if by_alias else 'strategy'] = self.strategy.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3Entry: - """Create an instance of SelectionConfigV3Entry from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3Entry.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3Entry) in the input: " + str(obj)) - - _obj = SelectionConfigV3Entry.parse_obj({ - "input": SelectionConfigV3EntryInput.from_dict(obj.get("input")) if obj.get("input") is not None else None, - "strategy": SelectionConfigV3EntryStrategy.from_dict(obj.get("strategy")) if obj.get("strategy") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_input.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_input.py deleted file mode 100644 index aac4c59da..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_input.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.selection_input_predictions_name import SelectionInputPredictionsName -from lightly.openapi_generated.swagger_client.models.selection_input_type import SelectionInputType - -class SelectionConfigV3EntryInput(BaseModel): - """ - SelectionConfigV3EntryInput - """ - type: SelectionInputType = Field(...) - task: Optional[constr(strict=True)] = Field(None, description="Since we sometimes stitch together SelectionInputTask+ActiveLearningScoreType, they need to follow the same specs of ActiveLearningScoreType. However, this can be an empty string due to internal logic. ") - score: Optional[constr(strict=True, min_length=1)] = Field(None, description="Type of active learning score") - key: Optional[constr(strict=True, min_length=1)] = None - name: Optional[SelectionInputPredictionsName] = None - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - tag_name: Optional[constr(strict=True, min_length=3)] = Field(None, alias="tagName", description="The name of the tag") - random_seed: Optional[StrictInt] = Field(None, alias="randomSeed") - categories: Optional[conlist(constr(strict=True, min_length=1), min_items=1, unique_items=True)] = None - __properties = ["type", "task", "score", "key", "name", "datasetId", "tagName", "randomSeed", "categories"] - - @validator('task') - def task_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('score') - def score_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_name') - def tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3EntryInput: - """Create an instance of SelectionConfigV3EntryInput from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3EntryInput: - """Create an instance of SelectionConfigV3EntryInput from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3EntryInput.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3EntryInput) in the input: " + str(obj)) - - _obj = SelectionConfigV3EntryInput.parse_obj({ - "type": obj.get("type"), - "task": obj.get("task"), - "score": obj.get("score"), - "key": obj.get("key"), - "name": obj.get("name"), - "dataset_id": obj.get("datasetId"), - "tag_name": obj.get("tagName"), - "random_seed": obj.get("randomSeed"), - "categories": obj.get("categories") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy.py deleted file mode 100644 index a9e00e1ea..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, confloat, conint -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of_target_range import SelectionConfigV3EntryStrategyAllOfTargetRange -from lightly.openapi_generated.swagger_client.models.selection_strategy_threshold_operation import SelectionStrategyThresholdOperation -from lightly.openapi_generated.swagger_client.models.selection_strategy_type_v3 import SelectionStrategyTypeV3 - -class SelectionConfigV3EntryStrategy(BaseModel): - """ - SelectionConfigV3EntryStrategy - """ - type: SelectionStrategyTypeV3 = Field(...) - stopping_condition_minimum_distance: Optional[Union[StrictFloat, StrictInt]] = None - threshold: Optional[Union[StrictFloat, StrictInt]] = None - operation: Optional[SelectionStrategyThresholdOperation] = None - target: Optional[Dict[str, Any]] = None - num_nearest_neighbors: Optional[Union[confloat(ge=2, strict=True), conint(ge=2, strict=True)]] = Field(None, alias="numNearestNeighbors", description="It is the number of nearest datapoints used to compute the typicality of each sample. ") - stopping_condition_minimum_typicality: Optional[Union[confloat(gt=0, strict=True), conint(gt=0, strict=True)]] = Field(None, alias="stoppingConditionMinimumTypicality", description="It is the minimal allowed typicality of the selected samples. When the typicality of the selected samples reaches this, the selection stops. It should be a number between 0 and 1. ") - strength: Optional[Union[confloat(le=1000000000, ge=-1000000000, strict=True), conint(le=1000000000, ge=-1000000000, strict=True)]] = Field(None, description="The relative strength of this strategy compared to other strategies. The default value is 1.0, which is set in the worker for backwards compatibility. The minimum and maximum values of +-10^9 are used to prevent numerical issues. ") - stopping_condition_max_sum: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="stoppingConditionMaxSum", description="When the sum of inputs reaches this, the selection stops. Only compatible with the WEIGHTS strategy. Similar to the stopping_condition_minimum_distance for the DIVERSITY strategy. ") - target_range: Optional[SelectionConfigV3EntryStrategyAllOfTargetRange] = Field(None, alias="targetRange") - __properties = ["type", "stopping_condition_minimum_distance", "threshold", "operation", "target", "numNearestNeighbors", "stoppingConditionMinimumTypicality", "strength", "stoppingConditionMaxSum", "targetRange"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3EntryStrategy: - """Create an instance of SelectionConfigV3EntryStrategy from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of target_range - if self.target_range: - _dict['targetRange' if by_alias else 'target_range'] = self.target_range.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3EntryStrategy: - """Create an instance of SelectionConfigV3EntryStrategy from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3EntryStrategy.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3EntryStrategy) in the input: " + str(obj)) - - _obj = SelectionConfigV3EntryStrategy.parse_obj({ - "type": obj.get("type"), - "stopping_condition_minimum_distance": obj.get("stopping_condition_minimum_distance"), - "threshold": obj.get("threshold"), - "operation": obj.get("operation"), - "target": obj.get("target"), - "num_nearest_neighbors": obj.get("numNearestNeighbors"), - "stopping_condition_minimum_typicality": obj.get("stoppingConditionMinimumTypicality"), - "strength": obj.get("strength"), - "stopping_condition_max_sum": obj.get("stoppingConditionMaxSum"), - "target_range": SelectionConfigV3EntryStrategyAllOfTargetRange.from_dict(obj.get("targetRange")) if obj.get("targetRange") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of.py deleted file mode 100644 index 30adac0db..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of_target_range import SelectionConfigV3EntryStrategyAllOfTargetRange -from lightly.openapi_generated.swagger_client.models.selection_strategy_type_v3 import SelectionStrategyTypeV3 - -class SelectionConfigV3EntryStrategyAllOf(BaseModel): - """ - SelectionConfigV3EntryStrategyAllOf - """ - type: SelectionStrategyTypeV3 = Field(...) - num_nearest_neighbors: Optional[Union[confloat(ge=2, strict=True), conint(ge=2, strict=True)]] = Field(None, alias="numNearestNeighbors", description="It is the number of nearest datapoints used to compute the typicality of each sample. ") - stopping_condition_minimum_typicality: Optional[Union[confloat(gt=0, strict=True), conint(gt=0, strict=True)]] = Field(None, alias="stoppingConditionMinimumTypicality", description="It is the minimal allowed typicality of the selected samples. When the typicality of the selected samples reaches this, the selection stops. It should be a number between 0 and 1. ") - strength: Optional[Union[confloat(le=1000000000, ge=-1000000000, strict=True), conint(le=1000000000, ge=-1000000000, strict=True)]] = Field(None, description="The relative strength of this strategy compared to other strategies. The default value is 1.0, which is set in the worker for backwards compatibility. The minimum and maximum values of +-10^9 are used to prevent numerical issues. ") - stopping_condition_max_sum: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="stoppingConditionMaxSum", description="When the sum of inputs reaches this, the selection stops. Only compatible with the WEIGHTS strategy. Similar to the stopping_condition_minimum_distance for the DIVERSITY strategy. ") - target_range: Optional[SelectionConfigV3EntryStrategyAllOfTargetRange] = Field(None, alias="targetRange") - __properties = ["type", "numNearestNeighbors", "stoppingConditionMinimumTypicality", "strength", "stoppingConditionMaxSum", "targetRange"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3EntryStrategyAllOf: - """Create an instance of SelectionConfigV3EntryStrategyAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of target_range - if self.target_range: - _dict['targetRange' if by_alias else 'target_range'] = self.target_range.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3EntryStrategyAllOf: - """Create an instance of SelectionConfigV3EntryStrategyAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3EntryStrategyAllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3EntryStrategyAllOf) in the input: " + str(obj)) - - _obj = SelectionConfigV3EntryStrategyAllOf.parse_obj({ - "type": obj.get("type"), - "num_nearest_neighbors": obj.get("numNearestNeighbors"), - "stopping_condition_minimum_typicality": obj.get("stoppingConditionMinimumTypicality"), - "strength": obj.get("strength"), - "stopping_condition_max_sum": obj.get("stoppingConditionMaxSum"), - "target_range": SelectionConfigV3EntryStrategyAllOfTargetRange.from_dict(obj.get("targetRange")) if obj.get("targetRange") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of_target_range.py b/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of_target_range.py deleted file mode 100644 index 73495ae9c..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v3_entry_strategy_all_of_target_range.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint - -class SelectionConfigV3EntryStrategyAllOfTargetRange(BaseModel): - """ - If specified, it tries to select samples such that their sum of inputs is >= min_sum and <= max_sum. Only compatible with the WEIGHTS strategy. - """ - min_sum: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="minSum", description="Target minimum sum of inputs. ") - max_sum: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="maxSum", description="Target maximum sum of inputs. Must be >= min_sum. ") - __properties = ["minSum", "maxSum"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV3EntryStrategyAllOfTargetRange: - """Create an instance of SelectionConfigV3EntryStrategyAllOfTargetRange from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV3EntryStrategyAllOfTargetRange: - """Create an instance of SelectionConfigV3EntryStrategyAllOfTargetRange from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV3EntryStrategyAllOfTargetRange.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV3EntryStrategyAllOfTargetRange) in the input: " + str(obj)) - - _obj = SelectionConfigV3EntryStrategyAllOfTargetRange.parse_obj({ - "min_sum": obj.get("minSum"), - "max_sum": obj.get("maxSum") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v4.py b/lightly/openapi_generated/swagger_client/models/selection_config_v4.py deleted file mode 100644 index 75ecb7e82..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v4.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional, Union -from pydantic import Extra, BaseModel, Field, confloat, conint, conlist, constr -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry import SelectionConfigV4Entry - -class SelectionConfigV4(BaseModel): - """ - SelectionConfigV4 - """ - n_samples: Optional[conint(strict=True, ge=-1)] = Field(None, alias="nSamples") - proportion_samples: Optional[Union[confloat(le=1.0, ge=0.0, strict=True), conint(le=1, ge=0, strict=True)]] = Field(None, alias="proportionSamples") - strategies: conlist(SelectionConfigV4Entry, min_items=1) = Field(...) - lightly_path_regex: Optional[constr(strict=True, min_length=1)] = Field(None, alias="lightlyPathRegex", description="The Lightly Path Regex to extract information from filenames for metadata balancing and more. Docs are coming soon.") - __properties = ["nSamples", "proportionSamples", "strategies", "lightlyPathRegex"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV4: - """Create an instance of SelectionConfigV4 from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV4: - """Create an instance of SelectionConfigV4 from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV4.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV4) in the input: " + str(obj)) - - _obj = SelectionConfigV4.parse_obj({ - "n_samples": obj.get("nSamples"), - "proportion_samples": obj.get("proportionSamples"), - "strategies": [SelectionConfigV4Entry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None, - "lightly_path_regex": obj.get("lightlyPathRegex") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v4_all_of.py b/lightly/openapi_generated/swagger_client/models/selection_config_v4_all_of.py deleted file mode 100644 index 2081502e6..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v4_all_of.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, conlist, constr -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry import SelectionConfigV4Entry - -class SelectionConfigV4AllOf(BaseModel): - """ - SelectionConfigV4AllOf - """ - strategies: conlist(SelectionConfigV4Entry, min_items=1) = Field(...) - lightly_path_regex: Optional[constr(strict=True, min_length=1)] = Field(None, alias="lightlyPathRegex", description="The Lightly Path Regex to extract information from filenames for metadata balancing and more. Docs are coming soon.") - __properties = ["strategies", "lightlyPathRegex"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV4AllOf: - """Create an instance of SelectionConfigV4AllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in strategies (list) - _items = [] - if self.strategies: - for _item in self.strategies: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['strategies' if by_alias else 'strategies'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV4AllOf: - """Create an instance of SelectionConfigV4AllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV4AllOf.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV4AllOf) in the input: " + str(obj)) - - _obj = SelectionConfigV4AllOf.parse_obj({ - "strategies": [SelectionConfigV4Entry.from_dict(_item) for _item in obj.get("strategies")] if obj.get("strategies") is not None else None, - "lightly_path_regex": obj.get("lightlyPathRegex") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry.py b/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry.py deleted file mode 100644 index b2d584866..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_input import SelectionConfigV4EntryInput -from lightly.openapi_generated.swagger_client.models.selection_config_v4_entry_strategy import SelectionConfigV4EntryStrategy - -class SelectionConfigV4Entry(BaseModel): - """ - SelectionConfigV4Entry - """ - input: SelectionConfigV4EntryInput = Field(...) - strategy: SelectionConfigV4EntryStrategy = Field(...) - __properties = ["input", "strategy"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV4Entry: - """Create an instance of SelectionConfigV4Entry from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of input - if self.input: - _dict['input' if by_alias else 'input'] = self.input.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of strategy - if self.strategy: - _dict['strategy' if by_alias else 'strategy'] = self.strategy.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV4Entry: - """Create an instance of SelectionConfigV4Entry from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV4Entry.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV4Entry) in the input: " + str(obj)) - - _obj = SelectionConfigV4Entry.parse_obj({ - "input": SelectionConfigV4EntryInput.from_dict(obj.get("input")) if obj.get("input") is not None else None, - "strategy": SelectionConfigV4EntryStrategy.from_dict(obj.get("strategy")) if obj.get("strategy") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_input.py b/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_input.py deleted file mode 100644 index 73e239a05..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_input.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.selection_input_predictions_name import SelectionInputPredictionsName -from lightly.openapi_generated.swagger_client.models.selection_input_type import SelectionInputType - -class SelectionConfigV4EntryInput(BaseModel): - """ - SelectionConfigV4EntryInput - """ - type: SelectionInputType = Field(...) - task: Optional[constr(strict=True)] = Field(None, description="Since we sometimes stitch together SelectionInputTask+ActiveLearningScoreType, they need to follow the same specs of ActiveLearningScoreType. However, this can be an empty string due to internal logic. ") - score: Optional[constr(strict=True, min_length=1)] = Field(None, description="Type of active learning score") - key: Optional[constr(strict=True, min_length=1)] = None - name: Optional[SelectionInputPredictionsName] = None - dataset_id: Optional[constr(strict=True)] = Field(None, alias="datasetId", description="MongoDB ObjectId") - tag_name: Optional[constr(strict=True, min_length=3)] = Field(None, alias="tagName", description="The name of the tag") - random_seed: Optional[StrictInt] = Field(None, alias="randomSeed") - categories: Optional[conlist(constr(strict=True, min_length=1), min_items=1, unique_items=True)] = None - __properties = ["type", "task", "score", "key", "name", "datasetId", "tagName", "randomSeed", "categories"] - - @validator('task') - def task_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('score') - def score_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_name') - def tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV4EntryInput: - """Create an instance of SelectionConfigV4EntryInput from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV4EntryInput: - """Create an instance of SelectionConfigV4EntryInput from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV4EntryInput.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV4EntryInput) in the input: " + str(obj)) - - _obj = SelectionConfigV4EntryInput.parse_obj({ - "type": obj.get("type"), - "task": obj.get("task"), - "score": obj.get("score"), - "key": obj.get("key"), - "name": obj.get("name"), - "dataset_id": obj.get("datasetId"), - "tag_name": obj.get("tagName"), - "random_seed": obj.get("randomSeed"), - "categories": obj.get("categories") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_strategy.py b/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_strategy.py deleted file mode 100644 index 5f12dac71..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_config_v4_entry_strategy.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, confloat, conint -from lightly.openapi_generated.swagger_client.models.selection_config_v3_entry_strategy_all_of_target_range import SelectionConfigV3EntryStrategyAllOfTargetRange -from lightly.openapi_generated.swagger_client.models.selection_strategy_threshold_operation import SelectionStrategyThresholdOperation -from lightly.openapi_generated.swagger_client.models.selection_strategy_type_v3 import SelectionStrategyTypeV3 - -class SelectionConfigV4EntryStrategy(BaseModel): - """ - SelectionConfigV4EntryStrategy - """ - type: SelectionStrategyTypeV3 = Field(...) - stopping_condition_minimum_distance: Optional[Union[StrictFloat, StrictInt]] = None - threshold: Optional[Union[StrictFloat, StrictInt]] = None - operation: Optional[SelectionStrategyThresholdOperation] = None - target: Optional[Dict[str, Any]] = None - num_nearest_neighbors: Optional[Union[confloat(ge=2, strict=True), conint(ge=2, strict=True)]] = Field(None, alias="numNearestNeighbors", description="It is the number of nearest datapoints used to compute the typicality of each sample. ") - stopping_condition_minimum_typicality: Optional[Union[confloat(gt=0, strict=True), conint(gt=0, strict=True)]] = Field(None, alias="stoppingConditionMinimumTypicality", description="It is the minimal allowed typicality of the selected samples. When the typicality of the selected samples reaches this, the selection stops. It should be a number between 0 and 1. ") - strength: Optional[Union[confloat(le=1000000000, ge=-1000000000, strict=True), conint(le=1000000000, ge=-1000000000, strict=True)]] = Field(None, description="The relative strength of this strategy compared to other strategies. The default value is 1.0, which is set in the worker for backwards compatibility. The minimum and maximum values of +-10^9 are used to prevent numerical issues. ") - stopping_condition_max_sum: Optional[Union[confloat(ge=0.0, strict=True), conint(ge=0, strict=True)]] = Field(None, alias="stoppingConditionMaxSum", description="When the sum of inputs reaches this, the selection stops. Only compatible with the WEIGHTS strategy. Similar to the stopping_condition_minimum_distance for the DIVERSITY strategy. ") - target_range: Optional[SelectionConfigV3EntryStrategyAllOfTargetRange] = Field(None, alias="targetRange") - __properties = ["type", "stopping_condition_minimum_distance", "threshold", "operation", "target", "numNearestNeighbors", "stoppingConditionMinimumTypicality", "strength", "stoppingConditionMaxSum", "targetRange"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SelectionConfigV4EntryStrategy: - """Create an instance of SelectionConfigV4EntryStrategy from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of target_range - if self.target_range: - _dict['targetRange' if by_alias else 'target_range'] = self.target_range.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SelectionConfigV4EntryStrategy: - """Create an instance of SelectionConfigV4EntryStrategy from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SelectionConfigV4EntryStrategy.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SelectionConfigV4EntryStrategy) in the input: " + str(obj)) - - _obj = SelectionConfigV4EntryStrategy.parse_obj({ - "type": obj.get("type"), - "stopping_condition_minimum_distance": obj.get("stopping_condition_minimum_distance"), - "threshold": obj.get("threshold"), - "operation": obj.get("operation"), - "target": obj.get("target"), - "num_nearest_neighbors": obj.get("numNearestNeighbors"), - "stopping_condition_minimum_typicality": obj.get("stoppingConditionMinimumTypicality"), - "strength": obj.get("strength"), - "stopping_condition_max_sum": obj.get("stoppingConditionMaxSum"), - "target_range": SelectionConfigV3EntryStrategyAllOfTargetRange.from_dict(obj.get("targetRange")) if obj.get("targetRange") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/selection_input_predictions_name.py b/lightly/openapi_generated/swagger_client/models/selection_input_predictions_name.py deleted file mode 100644 index b7864f0b3..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_input_predictions_name.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SelectionInputPredictionsName(str, Enum): - """ - SelectionInputPredictionsName - """ - - """ - allowed enum values - """ - CLASS_DISTRIBUTION = 'CLASS_DISTRIBUTION' - CATEGORY_COUNT = 'CATEGORY_COUNT' - - @classmethod - def from_json(cls, json_str: str) -> 'SelectionInputPredictionsName': - """Create an instance of SelectionInputPredictionsName from a JSON string""" - return SelectionInputPredictionsName(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/selection_input_type.py b/lightly/openapi_generated/swagger_client/models/selection_input_type.py deleted file mode 100644 index cbbfa6841..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_input_type.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SelectionInputType(str, Enum): - """ - SelectionInputType - """ - - """ - allowed enum values - """ - EMBEDDINGS = 'EMBEDDINGS' - SCORES = 'SCORES' - METADATA = 'METADATA' - PREDICTIONS = 'PREDICTIONS' - RANDOM = 'RANDOM' - - @classmethod - def from_json(cls, json_str: str) -> 'SelectionInputType': - """Create an instance of SelectionInputType from a JSON string""" - return SelectionInputType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/selection_strategy_threshold_operation.py b/lightly/openapi_generated/swagger_client/models/selection_strategy_threshold_operation.py deleted file mode 100644 index e416e2f5f..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_strategy_threshold_operation.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SelectionStrategyThresholdOperation(str, Enum): - """ - SelectionStrategyThresholdOperation - """ - - """ - allowed enum values - """ - SMALLER = 'SMALLER' - SMALLER_EQUAL = 'SMALLER_EQUAL' - BIGGER = 'BIGGER' - BIGGER_EQUAL = 'BIGGER_EQUAL' - - @classmethod - def from_json(cls, json_str: str) -> 'SelectionStrategyThresholdOperation': - """Create an instance of SelectionStrategyThresholdOperation from a JSON string""" - return SelectionStrategyThresholdOperation(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/selection_strategy_type.py b/lightly/openapi_generated/swagger_client/models/selection_strategy_type.py deleted file mode 100644 index 686f2054b..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_strategy_type.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SelectionStrategyType(str, Enum): - """ - SelectionStrategyType - """ - - """ - allowed enum values - """ - DIVERSITY = 'DIVERSITY' - WEIGHTS = 'WEIGHTS' - THRESHOLD = 'THRESHOLD' - BALANCE = 'BALANCE' - SIMILARITY = 'SIMILARITY' - - @classmethod - def from_json(cls, json_str: str) -> 'SelectionStrategyType': - """Create an instance of SelectionStrategyType from a JSON string""" - return SelectionStrategyType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/selection_strategy_type_v3.py b/lightly/openapi_generated/swagger_client/models/selection_strategy_type_v3.py deleted file mode 100644 index 4d1984560..000000000 --- a/lightly/openapi_generated/swagger_client/models/selection_strategy_type_v3.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SelectionStrategyTypeV3(str, Enum): - """ - SelectionStrategyTypeV3 - """ - - """ - allowed enum values - """ - DIVERSITY = 'DIVERSITY' - WEIGHTS = 'WEIGHTS' - THRESHOLD = 'THRESHOLD' - BALANCE = 'BALANCE' - SIMILARITY = 'SIMILARITY' - TYPICALITY = 'TYPICALITY' - - @classmethod - def from_json(cls, json_str: str) -> 'SelectionStrategyTypeV3': - """Create an instance of SelectionStrategyTypeV3 from a JSON string""" - return SelectionStrategyTypeV3(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/service_account_basic_data.py b/lightly/openapi_generated/swagger_client/models/service_account_basic_data.py deleted file mode 100644 index 9b89aebe2..000000000 --- a/lightly/openapi_generated/swagger_client/models/service_account_basic_data.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, conint, constr - -class ServiceAccountBasicData(BaseModel): - """ - ServiceAccountBasicData - """ - id: StrictStr = Field(...) - name: StrictStr = Field(...) - token: constr(strict=True, min_length=5) = Field(..., description="The user's token to be used for authentication via token querystring") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "name", "token", "createdAt"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> ServiceAccountBasicData: - """Create an instance of ServiceAccountBasicData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ServiceAccountBasicData: - """Create an instance of ServiceAccountBasicData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ServiceAccountBasicData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in ServiceAccountBasicData) in the input: " + str(obj)) - - _obj = ServiceAccountBasicData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "token": obj.get("token"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/set_embeddings_is_processed_flag_by_id_body_request.py b/lightly/openapi_generated/swagger_client/models/set_embeddings_is_processed_flag_by_id_body_request.py deleted file mode 100644 index 84990149b..000000000 --- a/lightly/openapi_generated/swagger_client/models/set_embeddings_is_processed_flag_by_id_body_request.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt - -class SetEmbeddingsIsProcessedFlagByIdBodyRequest(BaseModel): - """ - SetEmbeddingsIsProcessedFlagByIdBodyRequest - """ - row_count: Union[StrictFloat, StrictInt] = Field(..., alias="rowCount", description="Number of rows in the embeddings file") - __properties = ["rowCount"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SetEmbeddingsIsProcessedFlagByIdBodyRequest: - """Create an instance of SetEmbeddingsIsProcessedFlagByIdBodyRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SetEmbeddingsIsProcessedFlagByIdBodyRequest: - """Create an instance of SetEmbeddingsIsProcessedFlagByIdBodyRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SetEmbeddingsIsProcessedFlagByIdBodyRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SetEmbeddingsIsProcessedFlagByIdBodyRequest) in the input: " + str(obj)) - - _obj = SetEmbeddingsIsProcessedFlagByIdBodyRequest.parse_obj({ - "row_count": obj.get("rowCount") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/shared_access_config_create_request.py b/lightly/openapi_generated/swagger_client/models/shared_access_config_create_request.py deleted file mode 100644 index 1cec404a1..000000000 --- a/lightly/openapi_generated/swagger_client/models/shared_access_config_create_request.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictStr, conlist -from lightly.openapi_generated.swagger_client.models.creator import Creator -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType - -class SharedAccessConfigCreateRequest(BaseModel): - """ - SharedAccessConfigCreateRequest - """ - access_type: SharedAccessType = Field(..., alias="accessType") - users: Optional[conlist(StrictStr)] = Field(None, description="List of users with access to the dataset.") - teams: Optional[conlist(StrictStr)] = Field(None, description="List of teams with access to the dataset.") - creator: Optional[Creator] = None - __properties = ["accessType", "users", "teams", "creator"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SharedAccessConfigCreateRequest: - """Create an instance of SharedAccessConfigCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SharedAccessConfigCreateRequest: - """Create an instance of SharedAccessConfigCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SharedAccessConfigCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SharedAccessConfigCreateRequest) in the input: " + str(obj)) - - _obj = SharedAccessConfigCreateRequest.parse_obj({ - "access_type": obj.get("accessType"), - "users": obj.get("users"), - "teams": obj.get("teams"), - "creator": obj.get("creator") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/shared_access_config_data.py b/lightly/openapi_generated/swagger_client/models/shared_access_config_data.py deleted file mode 100644 index 8c393fef7..000000000 --- a/lightly/openapi_generated/swagger_client/models/shared_access_config_data.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List -from pydantic import Extra, BaseModel, Field, StrictStr, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.shared_access_type import SharedAccessType - -class SharedAccessConfigData(BaseModel): - """ - SharedAccessConfigData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - owner: StrictStr = Field(..., description="Id of the user who owns the dataset") - access_type: SharedAccessType = Field(..., alias="accessType") - users: conlist(StrictStr) = Field(..., description="List of user mails with access to the dataset") - teams: conlist(StrictStr) = Field(..., description="List of teams with access to the dataset") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: conint(strict=True, ge=0) = Field(..., alias="lastModifiedAt", description="unix timestamp in milliseconds") - __properties = ["id", "owner", "accessType", "users", "teams", "createdAt", "lastModifiedAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> SharedAccessConfigData: - """Create an instance of SharedAccessConfigData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SharedAccessConfigData: - """Create an instance of SharedAccessConfigData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SharedAccessConfigData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in SharedAccessConfigData) in the input: " + str(obj)) - - _obj = SharedAccessConfigData.parse_obj({ - "id": obj.get("id"), - "owner": obj.get("owner"), - "access_type": obj.get("accessType"), - "users": obj.get("users"), - "teams": obj.get("teams"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/shared_access_type.py b/lightly/openapi_generated/swagger_client/models/shared_access_type.py deleted file mode 100644 index 42416f2c2..000000000 --- a/lightly/openapi_generated/swagger_client/models/shared_access_type.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class SharedAccessType(str, Enum): - """ - SharedAccessType - """ - - """ - allowed enum values - """ - WRITE = 'WRITE' - - @classmethod - def from_json(cls, json_str: str) -> 'SharedAccessType': - """Create an instance of SharedAccessType from a JSON string""" - return SharedAccessType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/tag_active_learning_scores_data.py b/lightly/openapi_generated/swagger_client/models/tag_active_learning_scores_data.py deleted file mode 100644 index 96d7b3a23..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_active_learning_scores_data.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, conint, constr, validator - -class TagActiveLearningScoresData(BaseModel): - """ - Array of scores belonging to tag - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - tag_id: constr(strict=True) = Field(..., alias="tagId", description="MongoDB ObjectId") - score_type: constr(strict=True, min_length=1) = Field(..., alias="scoreType", description="Type of active learning score") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - __properties = ["id", "tagId", "scoreType", "createdAt"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_id') - def tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('score_type') - def score_type_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9_+=,.@:\/-]*$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_+=,.@:\/-]*$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagActiveLearningScoresData: - """Create an instance of TagActiveLearningScoresData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagActiveLearningScoresData: - """Create an instance of TagActiveLearningScoresData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagActiveLearningScoresData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagActiveLearningScoresData) in the input: " + str(obj)) - - _obj = TagActiveLearningScoresData.parse_obj({ - "id": obj.get("id"), - "tag_id": obj.get("tagId"), - "score_type": obj.get("scoreType"), - "created_at": obj.get("createdAt") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_operation.py b/lightly/openapi_generated/swagger_client/models/tag_arithmetics_operation.py deleted file mode 100644 index 491303003..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_operation.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class TagArithmeticsOperation(str, Enum): - """ - The possible arithmetic operations that can be done between multiple tags. - """ - - """ - allowed enum values - """ - UNION = 'UNION' - INTERSECTION = 'INTERSECTION' - DIFFERENCE = 'DIFFERENCE' - - @classmethod - def from_json(cls, json_str: str) -> 'TagArithmeticsOperation': - """Create an instance of TagArithmeticsOperation from a JSON string""" - return TagArithmeticsOperation(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_request.py b/lightly/openapi_generated/swagger_client/models/tag_arithmetics_request.py deleted file mode 100644 index e40238101..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_request.py +++ /dev/null @@ -1,124 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.tag_arithmetics_operation import TagArithmeticsOperation -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class TagArithmeticsRequest(BaseModel): - """ - TagArithmeticsRequest - """ - tag_id1: constr(strict=True) = Field(..., alias="tagId1", description="MongoDB ObjectId") - tag_id2: constr(strict=True) = Field(..., alias="tagId2", description="MongoDB ObjectId") - operation: TagArithmeticsOperation = Field(...) - new_tag_name: Optional[constr(strict=True, min_length=3)] = Field(None, alias="newTagName", description="The name of the tag") - creator: Optional[TagCreator] = None - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["tagId1", "tagId2", "operation", "newTagName", "creator", "runId"] - - @validator('tag_id1') - def tag_id1_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('tag_id2') - def tag_id2_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('new_tag_name') - def new_tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagArithmeticsRequest: - """Create an instance of TagArithmeticsRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagArithmeticsRequest: - """Create an instance of TagArithmeticsRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagArithmeticsRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagArithmeticsRequest) in the input: " + str(obj)) - - _obj = TagArithmeticsRequest.parse_obj({ - "tag_id1": obj.get("tagId1"), - "tag_id2": obj.get("tagId2"), - "operation": obj.get("operation"), - "new_tag_name": obj.get("newTagName"), - "creator": obj.get("creator"), - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_response.py b/lightly/openapi_generated/swagger_client/models/tag_arithmetics_response.py deleted file mode 100644 index 21070676a..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_arithmetics_response.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from lightly.openapi_generated.swagger_client.models.create_entity_response import CreateEntityResponse -from lightly.openapi_generated.swagger_client.models.tag_bit_mask_response import TagBitMaskResponse -from typing import Any, List -from pydantic import StrictStr, Field, Extra - -TAGARITHMETICSRESPONSE_ONE_OF_SCHEMAS = ["CreateEntityResponse", "TagBitMaskResponse"] - -class TagArithmeticsResponse(BaseModel): - """ - TagArithmeticsResponse - """ - # data type: CreateEntityResponse - oneof_schema_1_validator: Optional[CreateEntityResponse] = None - # data type: TagBitMaskResponse - oneof_schema_2_validator: Optional[TagBitMaskResponse] = None - actual_instance: Any - one_of_schemas: List[str] = Field(TAGARITHMETICSRESPONSE_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = TagArithmeticsResponse.construct() - error_messages = [] - match = 0 - # validate data type: CreateEntityResponse - if not isinstance(v, CreateEntityResponse): - error_messages.append(f"Error! Input type `{type(v)}` is not `CreateEntityResponse`") - else: - match += 1 - # validate data type: TagBitMaskResponse - if not isinstance(v, TagBitMaskResponse): - error_messages.append(f"Error! Input type `{type(v)}` is not `TagBitMaskResponse`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in TagArithmeticsResponse with oneOf schemas: CreateEntityResponse, TagBitMaskResponse. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in TagArithmeticsResponse with oneOf schemas: CreateEntityResponse, TagBitMaskResponse. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> TagArithmeticsResponse: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> TagArithmeticsResponse: - """Returns the object represented by the json string""" - instance = TagArithmeticsResponse.construct() - error_messages = [] - match = 0 - - # deserialize data into CreateEntityResponse - try: - instance.actual_instance = CreateEntityResponse.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into TagBitMaskResponse - try: - instance.actual_instance = TagBitMaskResponse.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into TagArithmeticsResponse with oneOf schemas: CreateEntityResponse, TagBitMaskResponse. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into TagArithmeticsResponse with oneOf schemas: CreateEntityResponse, TagBitMaskResponse. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json(by_alias=by_alias) - else: - return json.dumps(self.actual_instance) - - def to_dict(self, by_alias: bool = False) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict(by_alias=by_alias) - else: - # primitive type - return self.actual_instance - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict(by_alias=by_alias)) - diff --git a/lightly/openapi_generated/swagger_client/models/tag_bit_mask_response.py b/lightly/openapi_generated/swagger_client/models/tag_bit_mask_response.py deleted file mode 100644 index e24a5e8af..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_bit_mask_response.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, constr, validator - -class TagBitMaskResponse(BaseModel): - """ - TagBitMaskResponse - """ - bit_mask_data: constr(strict=True) = Field(..., alias="bitMaskData", description="BitMask as a base16 (hex) string") - __properties = ["bitMaskData"] - - @validator('bit_mask_data') - def bit_mask_data_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^0x[a-f0-9]+$", value): - raise ValueError(r"must validate the regular expression /^0x[a-f0-9]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagBitMaskResponse: - """Create an instance of TagBitMaskResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagBitMaskResponse: - """Create an instance of TagBitMaskResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagBitMaskResponse.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagBitMaskResponse) in the input: " + str(obj)) - - _obj = TagBitMaskResponse.parse_obj({ - "bit_mask_data": obj.get("bitMaskData") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data.py b/lightly/openapi_generated/swagger_client/models/tag_change_data.py deleted file mode 100644 index 863f30ec9..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data.py +++ /dev/null @@ -1,131 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel -from lightly.openapi_generated.swagger_client.models.tag_change_data_arithmetics import TagChangeDataArithmetics -from lightly.openapi_generated.swagger_client.models.tag_change_data_initial import TagChangeDataInitial -from lightly.openapi_generated.swagger_client.models.tag_change_data_metadata import TagChangeDataMetadata -from lightly.openapi_generated.swagger_client.models.tag_change_data_rename import TagChangeDataRename -from lightly.openapi_generated.swagger_client.models.tag_change_data_sampler import TagChangeDataSampler -from lightly.openapi_generated.swagger_client.models.tag_change_data_samples import TagChangeDataSamples -from lightly.openapi_generated.swagger_client.models.tag_change_data_scatterplot import TagChangeDataScatterplot -from lightly.openapi_generated.swagger_client.models.tag_change_data_upsize import TagChangeDataUpsize - -class TagChangeData(BaseModel): - """ - TagChangeData - """ - initial: Optional[TagChangeDataInitial] = None - rename: Optional[TagChangeDataRename] = None - upsize: Optional[TagChangeDataUpsize] = None - arithmetics: Optional[TagChangeDataArithmetics] = None - metadata: Optional[TagChangeDataMetadata] = None - samples: Optional[TagChangeDataSamples] = None - scatterplot: Optional[TagChangeDataScatterplot] = None - sampler: Optional[TagChangeDataSampler] = None - additional_properties: Dict[str, Any] = {} - __properties = ["initial", "rename", "upsize", "arithmetics", "metadata", "samples", "scatterplot", "sampler"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeData: - """Create an instance of TagChangeData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - "additional_properties" - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of initial - if self.initial: - _dict['initial' if by_alias else 'initial'] = self.initial.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of rename - if self.rename: - _dict['rename' if by_alias else 'rename'] = self.rename.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of upsize - if self.upsize: - _dict['upsize' if by_alias else 'upsize'] = self.upsize.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of arithmetics - if self.arithmetics: - _dict['arithmetics' if by_alias else 'arithmetics'] = self.arithmetics.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of metadata - if self.metadata: - _dict['metadata' if by_alias else 'metadata'] = self.metadata.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of samples - if self.samples: - _dict['samples' if by_alias else 'samples'] = self.samples.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of scatterplot - if self.scatterplot: - _dict['scatterplot' if by_alias else 'scatterplot'] = self.scatterplot.to_dict(by_alias=by_alias) - # override the default output from pydantic by calling `to_dict()` of sampler - if self.sampler: - _dict['sampler' if by_alias else 'sampler'] = self.sampler.to_dict(by_alias=by_alias) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeData: - """Create an instance of TagChangeData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeData.parse_obj(obj) - - _obj = TagChangeData.parse_obj({ - "initial": TagChangeDataInitial.from_dict(obj.get("initial")) if obj.get("initial") is not None else None, - "rename": TagChangeDataRename.from_dict(obj.get("rename")) if obj.get("rename") is not None else None, - "upsize": TagChangeDataUpsize.from_dict(obj.get("upsize")) if obj.get("upsize") is not None else None, - "arithmetics": TagChangeDataArithmetics.from_dict(obj.get("arithmetics")) if obj.get("arithmetics") is not None else None, - "metadata": TagChangeDataMetadata.from_dict(obj.get("metadata")) if obj.get("metadata") is not None else None, - "samples": TagChangeDataSamples.from_dict(obj.get("samples")) if obj.get("samples") is not None else None, - "scatterplot": TagChangeDataScatterplot.from_dict(obj.get("scatterplot")) if obj.get("scatterplot") is not None else None, - "sampler": TagChangeDataSampler.from_dict(obj.get("sampler")) if obj.get("sampler") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_arithmetics.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_arithmetics.py deleted file mode 100644 index db2a7fc3e..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_arithmetics.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class TagChangeDataArithmetics(BaseModel): - """ - TagChangeDataArithmetics - """ - operation: StrictStr = Field(...) - tag1: StrictStr = Field(...) - tag2: StrictStr = Field(...) - __properties = ["operation", "tag1", "tag2"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataArithmetics: - """Create an instance of TagChangeDataArithmetics from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataArithmetics: - """Create an instance of TagChangeDataArithmetics from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataArithmetics.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataArithmetics) in the input: " + str(obj)) - - _obj = TagChangeDataArithmetics.parse_obj({ - "operation": obj.get("operation"), - "tag1": obj.get("tag1"), - "tag2": obj.get("tag2") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_initial.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_initial.py deleted file mode 100644 index 4a109787a..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_initial.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator - -class TagChangeDataInitial(BaseModel): - """ - TagChangeDataInitial - """ - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["runId"] - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataInitial: - """Create an instance of TagChangeDataInitial from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataInitial: - """Create an instance of TagChangeDataInitial from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataInitial.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataInitial) in the input: " + str(obj)) - - _obj = TagChangeDataInitial.parse_obj({ - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_metadata.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_metadata.py deleted file mode 100644 index 676893f11..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_metadata.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Union -from pydantic import Extra, BaseModel, Field, confloat, conint -from lightly.openapi_generated.swagger_client.models.tag_change_data_operation_method import TagChangeDataOperationMethod - -class TagChangeDataMetadata(BaseModel): - """ - TagChangeDataMetadata - """ - method: TagChangeDataOperationMethod = Field(...) - count: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - added: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - removed: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - changes: Dict[str, Any] = Field(...) - __properties = ["method", "count", "added", "removed", "changes"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataMetadata: - """Create an instance of TagChangeDataMetadata from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataMetadata: - """Create an instance of TagChangeDataMetadata from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataMetadata.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataMetadata) in the input: " + str(obj)) - - _obj = TagChangeDataMetadata.parse_obj({ - "method": obj.get("method"), - "count": obj.get("count"), - "added": obj.get("added"), - "removed": obj.get("removed"), - "changes": obj.get("changes") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_operation_method.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_operation_method.py deleted file mode 100644 index 6a20dc2f0..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_operation_method.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class TagChangeDataOperationMethod(str, Enum): - """ - TagChangeDataOperationMethod - """ - - """ - allowed enum values - """ - SELECTED = 'selected' - ADDED = 'added' - REMOVED = 'removed' - - @classmethod - def from_json(cls, json_str: str) -> 'TagChangeDataOperationMethod': - """Create an instance of TagChangeDataOperationMethod from a JSON string""" - return TagChangeDataOperationMethod(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_rename.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_rename.py deleted file mode 100644 index 864c50769..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_rename.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class TagChangeDataRename(BaseModel): - """ - TagChangeDataRename - """ - var_from: StrictStr = Field(..., alias="from") - to: StrictStr = Field(...) - __properties = ["from", "to"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataRename: - """Create an instance of TagChangeDataRename from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataRename: - """Create an instance of TagChangeDataRename from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataRename.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataRename) in the input: " + str(obj)) - - _obj = TagChangeDataRename.parse_obj({ - "var_from": obj.get("from"), - "to": obj.get("to") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_sampler.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_sampler.py deleted file mode 100644 index 405f0ead1..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_sampler.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class TagChangeDataSampler(BaseModel): - """ - TagChangeDataSampler - """ - method: StrictStr = Field(...) - __properties = ["method"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataSampler: - """Create an instance of TagChangeDataSampler from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataSampler: - """Create an instance of TagChangeDataSampler from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataSampler.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataSampler) in the input: " + str(obj)) - - _obj = TagChangeDataSampler.parse_obj({ - "method": obj.get("method") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_samples.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_samples.py deleted file mode 100644 index 2ef45e798..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_samples.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Union -from pydantic import Extra, BaseModel, Field, confloat, conint -from lightly.openapi_generated.swagger_client.models.tag_change_data_operation_method import TagChangeDataOperationMethod - -class TagChangeDataSamples(BaseModel): - """ - TagChangeDataSamples - """ - method: TagChangeDataOperationMethod = Field(...) - count: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - added: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - removed: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - __properties = ["method", "count", "added", "removed"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataSamples: - """Create an instance of TagChangeDataSamples from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataSamples: - """Create an instance of TagChangeDataSamples from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataSamples.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataSamples) in the input: " + str(obj)) - - _obj = TagChangeDataSamples.parse_obj({ - "method": obj.get("method"), - "count": obj.get("count"), - "added": obj.get("added"), - "removed": obj.get("removed") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_scatterplot.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_scatterplot.py deleted file mode 100644 index 102409e93..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_scatterplot.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictStr, confloat, conint -from lightly.openapi_generated.swagger_client.models.tag_change_data_operation_method import TagChangeDataOperationMethod - -class TagChangeDataScatterplot(BaseModel): - """ - TagChangeDataScatterplot - """ - method: TagChangeDataOperationMethod = Field(...) - view: Optional[StrictStr] = None - count: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - added: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - removed: Union[confloat(ge=0, strict=True), conint(ge=0, strict=True)] = Field(...) - __properties = ["method", "view", "count", "added", "removed"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataScatterplot: - """Create an instance of TagChangeDataScatterplot from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataScatterplot: - """Create an instance of TagChangeDataScatterplot from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataScatterplot.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataScatterplot) in the input: " + str(obj)) - - _obj = TagChangeDataScatterplot.parse_obj({ - "method": obj.get("method"), - "view": obj.get("view"), - "count": obj.get("count"), - "added": obj.get("added"), - "removed": obj.get("removed") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_data_upsize.py b/lightly/openapi_generated/swagger_client/models/tag_change_data_upsize.py deleted file mode 100644 index 951266ae2..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_data_upsize.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, constr, validator - -class TagChangeDataUpsize(BaseModel): - """ - TagChangeDataUpsize - """ - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - var_from: Union[StrictFloat, StrictInt] = Field(..., alias="from") - to: Union[StrictFloat, StrictInt] = Field(...) - __properties = ["runId", "from", "to"] - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeDataUpsize: - """Create an instance of TagChangeDataUpsize from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeDataUpsize: - """Create an instance of TagChangeDataUpsize from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeDataUpsize.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeDataUpsize) in the input: " + str(obj)) - - _obj = TagChangeDataUpsize.parse_obj({ - "run_id": obj.get("runId"), - "var_from": obj.get("from"), - "to": obj.get("to") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_change_entry.py b/lightly/openapi_generated/swagger_client/models/tag_change_entry.py deleted file mode 100644 index a84181b4b..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_change_entry.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, conint -from lightly.openapi_generated.swagger_client.models.tag_change_data import TagChangeData -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class TagChangeEntry(BaseModel): - """ - TagChangeEntry - """ - user_id: StrictStr = Field(..., alias="userId") - creator: TagCreator = Field(...) - ts: conint(strict=True, ge=0) = Field(..., description="unix timestamp in milliseconds") - changes: TagChangeData = Field(...) - __properties = ["userId", "creator", "ts", "changes"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagChangeEntry: - """Create an instance of TagChangeEntry from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of changes - if self.changes: - _dict['changes' if by_alias else 'changes'] = self.changes.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagChangeEntry: - """Create an instance of TagChangeEntry from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagChangeEntry.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagChangeEntry) in the input: " + str(obj)) - - _obj = TagChangeEntry.parse_obj({ - "user_id": obj.get("userId"), - "creator": obj.get("creator"), - "ts": obj.get("ts"), - "changes": TagChangeData.from_dict(obj.get("changes")) if obj.get("changes") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_create_request.py b/lightly/openapi_generated/swagger_client/models/tag_create_request.py deleted file mode 100644 index d95e9f739..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_create_request.py +++ /dev/null @@ -1,150 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictInt, constr, validator -from lightly.openapi_generated.swagger_client.models.tag_change_data import TagChangeData -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class TagCreateRequest(BaseModel): - """ - TagCreateRequest - """ - name: constr(strict=True, min_length=3) = Field(..., description="The name of the tag") - prev_tag_id: constr(strict=True) = Field(..., alias="prevTagId", description="MongoDB ObjectId") - query_tag_id: Optional[constr(strict=True)] = Field(None, alias="queryTagId", description="MongoDB ObjectId") - preselected_tag_id: Optional[constr(strict=True)] = Field(None, alias="preselectedTagId", description="MongoDB ObjectId") - bit_mask_data: constr(strict=True) = Field(..., alias="bitMaskData", description="BitMask as a base16 (hex) string") - tot_size: StrictInt = Field(..., alias="totSize") - creator: Optional[TagCreator] = None - changes: Optional[TagChangeData] = None - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["name", "prevTagId", "queryTagId", "preselectedTagId", "bitMaskData", "totSize", "creator", "changes", "runId"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('prev_tag_id') - def prev_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('query_tag_id') - def query_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('preselected_tag_id') - def preselected_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('bit_mask_data') - def bit_mask_data_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^0x[a-f0-9]+$", value): - raise ValueError(r"must validate the regular expression /^0x[a-f0-9]+$/") - return value - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagCreateRequest: - """Create an instance of TagCreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of changes - if self.changes: - _dict['changes' if by_alias else 'changes'] = self.changes.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagCreateRequest: - """Create an instance of TagCreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagCreateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagCreateRequest) in the input: " + str(obj)) - - _obj = TagCreateRequest.parse_obj({ - "name": obj.get("name"), - "prev_tag_id": obj.get("prevTagId"), - "query_tag_id": obj.get("queryTagId"), - "preselected_tag_id": obj.get("preselectedTagId"), - "bit_mask_data": obj.get("bitMaskData"), - "tot_size": obj.get("totSize"), - "creator": obj.get("creator"), - "changes": TagChangeData.from_dict(obj.get("changes")) if obj.get("changes") is not None else None, - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_creator.py b/lightly/openapi_generated/swagger_client/models/tag_creator.py deleted file mode 100644 index 91d84d8f2..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_creator.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class TagCreator(str, Enum): - """ - TagCreator - """ - - """ - allowed enum values - """ - UNKNOWN = 'UNKNOWN' - USER_WEBAPP = 'USER_WEBAPP' - USER_PIP = 'USER_PIP' - USER_PIP_LIGHTLY_MAGIC = 'USER_PIP_LIGHTLY_MAGIC' - USER_WORKER = 'USER_WORKER' - SAMPLER_ACTIVE_LEARNING = 'SAMPLER_ACTIVE_LEARNING' - SAMPLER_CORAL = 'SAMPLER_CORAL' - SAMPLER_CORESET = 'SAMPLER_CORESET' - SAMPLER_RANDOM = 'SAMPLER_RANDOM' - - @classmethod - def from_json(cls, json_str: str) -> 'TagCreator': - """Create an instance of TagCreator from a JSON string""" - return TagCreator(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/tag_data.py b/lightly/openapi_generated/swagger_client/models/tag_data.py deleted file mode 100644 index be48c1995..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_data.py +++ /dev/null @@ -1,181 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import Extra, BaseModel, Field, StrictInt, conint, conlist, constr, validator -from lightly.openapi_generated.swagger_client.models.tag_change_entry import TagChangeEntry - -class TagData(BaseModel): - """ - TagData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - dataset_id: constr(strict=True) = Field(..., alias="datasetId", description="MongoDB ObjectId") - prev_tag_id: Optional[constr(strict=True)] = Field(..., alias="prevTagId", description="MongoObjectID or null. Generally: The prevTagId is this tag's parent, i.e. it is a superset of this tag. Sampler: The prevTagId is the initial-tag if there was no preselectedTagId, otherwise, it's the preselectedTagId. ") - query_tag_id: Optional[constr(strict=True)] = Field(None, alias="queryTagId", description="MongoDB ObjectId") - preselected_tag_id: Optional[constr(strict=True)] = Field(None, alias="preselectedTagId", description="MongoDB ObjectId") - name: constr(strict=True, min_length=3) = Field(..., description="The name of the tag") - bit_mask_data: constr(strict=True) = Field(..., alias="bitMaskData", description="BitMask as a base16 (hex) string") - tot_size: StrictInt = Field(..., alias="totSize") - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - last_modified_at: Optional[conint(strict=True, ge=0)] = Field(None, alias="lastModifiedAt", description="unix timestamp in milliseconds") - changes: Optional[conlist(TagChangeEntry)] = None - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["id", "datasetId", "prevTagId", "queryTagId", "preselectedTagId", "name", "bitMaskData", "totSize", "createdAt", "lastModifiedAt", "changes", "runId"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('dataset_id') - def dataset_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('prev_tag_id') - def prev_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('query_tag_id') - def query_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('preselected_tag_id') - def preselected_tag_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('bit_mask_data') - def bit_mask_data_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^0x[a-f0-9]+$", value): - raise ValueError(r"must validate the regular expression /^0x[a-f0-9]+$/") - return value - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagData: - """Create an instance of TagData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in changes (list) - _items = [] - if self.changes: - for _item in self.changes: - if _item: - _items.append(_item.to_dict(by_alias=by_alias)) - _dict['changes' if by_alias else 'changes'] = _items - # set to None if prev_tag_id (nullable) is None - # and __fields_set__ contains the field - if self.prev_tag_id is None and "prev_tag_id" in self.__fields_set__: - _dict['prevTagId' if by_alias else 'prev_tag_id'] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagData: - """Create an instance of TagData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagData) in the input: " + str(obj)) - - _obj = TagData.parse_obj({ - "id": obj.get("id"), - "dataset_id": obj.get("datasetId"), - "prev_tag_id": obj.get("prevTagId"), - "query_tag_id": obj.get("queryTagId"), - "preselected_tag_id": obj.get("preselectedTagId"), - "name": obj.get("name"), - "bit_mask_data": obj.get("bitMaskData"), - "tot_size": obj.get("totSize"), - "created_at": obj.get("createdAt"), - "last_modified_at": obj.get("lastModifiedAt"), - "changes": [TagChangeEntry.from_dict(_item) for _item in obj.get("changes")] if obj.get("changes") is not None else None, - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_update_request.py b/lightly/openapi_generated/swagger_client/models/tag_update_request.py deleted file mode 100644 index bafe031b4..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_update_request.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.tag_change_data import TagChangeData -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class TagUpdateRequest(BaseModel): - """ - TagUpdateRequest - """ - update_creator: Optional[TagCreator] = Field(None, alias="updateCreator") - name: constr(strict=True, min_length=3) = Field(..., description="The name of the tag") - bit_mask_data: Optional[constr(strict=True)] = Field(None, alias="bitMaskData", description="BitMask as a base16 (hex) string") - changes: Optional[TagChangeData] = None - __properties = ["updateCreator", "name", "bitMaskData", "changes"] - - @validator('name') - def name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('bit_mask_data') - def bit_mask_data_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^0x[a-f0-9]+$", value): - raise ValueError(r"must validate the regular expression /^0x[a-f0-9]+$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagUpdateRequest: - """Create an instance of TagUpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of changes - if self.changes: - _dict['changes' if by_alias else 'changes'] = self.changes.to_dict(by_alias=by_alias) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagUpdateRequest: - """Create an instance of TagUpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagUpdateRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagUpdateRequest) in the input: " + str(obj)) - - _obj = TagUpdateRequest.parse_obj({ - "update_creator": obj.get("updateCreator"), - "name": obj.get("name"), - "bit_mask_data": obj.get("bitMaskData"), - "changes": TagChangeData.from_dict(obj.get("changes")) if obj.get("changes") is not None else None - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/tag_upsize_request.py b/lightly/openapi_generated/swagger_client/models/tag_upsize_request.py deleted file mode 100644 index d5c294d78..000000000 --- a/lightly/openapi_generated/swagger_client/models/tag_upsize_request.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, constr, validator -from lightly.openapi_generated.swagger_client.models.tag_creator import TagCreator - -class TagUpsizeRequest(BaseModel): - """ - TagUpsizeRequest - """ - upsize_tag_name: constr(strict=True, min_length=3) = Field(..., alias="upsizeTagName", description="The name of the tag") - upsize_tag_creator: TagCreator = Field(..., alias="upsizeTagCreator") - run_id: Optional[constr(strict=True)] = Field(None, alias="runId", description="MongoDB ObjectId") - __properties = ["upsizeTagName", "upsizeTagCreator", "runId"] - - @validator('upsize_tag_name') - def upsize_tag_name_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$", value): - raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9][a-zA-Z0-9 .:;=@_-]+$/") - return value - - @validator('run_id') - def run_id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if value is None: - return value - - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TagUpsizeRequest: - """Create an instance of TagUpsizeRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TagUpsizeRequest: - """Create an instance of TagUpsizeRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TagUpsizeRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TagUpsizeRequest) in the input: " + str(obj)) - - _obj = TagUpsizeRequest.parse_obj({ - "upsize_tag_name": obj.get("upsizeTagName"), - "upsize_tag_creator": obj.get("upsizeTagCreator"), - "run_id": obj.get("runId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/task_type.py b/lightly/openapi_generated/swagger_client/models/task_type.py deleted file mode 100644 index 9a645473f..000000000 --- a/lightly/openapi_generated/swagger_client/models/task_type.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class TaskType(str, Enum): - """ - The type of the prediction or label task - """ - - """ - allowed enum values - """ - CLASSIFICATION = 'CLASSIFICATION' - OBJECT_DETECTION = 'OBJECT_DETECTION' - SEMANTIC_SEGMENTATION = 'SEMANTIC_SEGMENTATION' - INSTANCE_SEGMENTATION = 'INSTANCE_SEGMENTATION' - KEYPOINT_DETECTION = 'KEYPOINT_DETECTION' - - @classmethod - def from_json(cls, json_str: str) -> 'TaskType': - """Create an instance of TaskType from a JSON string""" - return TaskType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/team_basic_data.py b/lightly/openapi_generated/swagger_client/models/team_basic_data.py deleted file mode 100644 index 13bdfa2c3..000000000 --- a/lightly/openapi_generated/swagger_client/models/team_basic_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, constr, validator -from lightly.openapi_generated.swagger_client.models.team_role import TeamRole - -class TeamBasicData(BaseModel): - """ - TeamBasicData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: StrictStr = Field(...) - role: TeamRole = Field(...) - __properties = ["id", "name", "role"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TeamBasicData: - """Create an instance of TeamBasicData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TeamBasicData: - """Create an instance of TeamBasicData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TeamBasicData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TeamBasicData) in the input: " + str(obj)) - - _obj = TeamBasicData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "role": obj.get("role") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/team_data.py b/lightly/openapi_generated/swagger_client/models/team_data.py deleted file mode 100644 index 346245050..000000000 --- a/lightly/openapi_generated/swagger_client/models/team_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr, conint, constr, validator - -class TeamData(BaseModel): - """ - TeamData - """ - id: constr(strict=True) = Field(..., description="MongoDB ObjectId") - name: StrictStr = Field(...) - created_at: conint(strict=True, ge=0) = Field(..., alias="createdAt", description="unix timestamp in milliseconds") - valid_until: conint(strict=True, ge=0) = Field(..., alias="validUntil", description="unix timestamp in milliseconds") - __properties = ["id", "name", "createdAt", "validUntil"] - - @validator('id') - def id_validate_regular_expression(cls, value): - """Validates the regular expression""" - if not re.match(r"^[a-f0-9]{24}$", value): - raise ValueError(r"must validate the regular expression /^[a-f0-9]{24}$/") - return value - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> TeamData: - """Create an instance of TeamData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> TeamData: - """Create an instance of TeamData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return TeamData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TeamData) in the input: " + str(obj)) - - _obj = TeamData.parse_obj({ - "id": obj.get("id"), - "name": obj.get("name"), - "created_at": obj.get("createdAt"), - "valid_until": obj.get("validUntil") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/team_role.py b/lightly/openapi_generated/swagger_client/models/team_role.py deleted file mode 100644 index 47a073695..000000000 --- a/lightly/openapi_generated/swagger_client/models/team_role.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class TeamRole(str, Enum): - """ - TeamRole - """ - - """ - allowed enum values - """ - OWNER = 'OWNER' - ADMIN = 'ADMIN' - MEMBER = 'MEMBER' - SERVICEACCOUNT = 'SERVICEACCOUNT' - - @classmethod - def from_json(cls, json_str: str) -> 'TeamRole': - """Create an instance of TeamRole from a JSON string""" - return TeamRole(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/trigger2d_embedding_job_request.py b/lightly/openapi_generated/swagger_client/models/trigger2d_embedding_job_request.py deleted file mode 100644 index ed534fd31..000000000 --- a/lightly/openapi_generated/swagger_client/models/trigger2d_embedding_job_request.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.dimensionality_reduction_method import DimensionalityReductionMethod - -class Trigger2dEmbeddingJobRequest(BaseModel): - """ - Trigger2dEmbeddingJobRequest - """ - dimensionality_reduction_method: DimensionalityReductionMethod = Field(..., alias="dimensionalityReductionMethod") - __properties = ["dimensionalityReductionMethod"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> Trigger2dEmbeddingJobRequest: - """Create an instance of Trigger2dEmbeddingJobRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Trigger2dEmbeddingJobRequest: - """Create an instance of Trigger2dEmbeddingJobRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Trigger2dEmbeddingJobRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Trigger2dEmbeddingJobRequest) in the input: " + str(obj)) - - _obj = Trigger2dEmbeddingJobRequest.parse_obj({ - "dimensionality_reduction_method": obj.get("dimensionalityReductionMethod") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/update_docker_worker_registry_entry_request.py b/lightly/openapi_generated/swagger_client/models/update_docker_worker_registry_entry_request.py deleted file mode 100644 index 4db776513..000000000 --- a/lightly/openapi_generated/swagger_client/models/update_docker_worker_registry_entry_request.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import Extra, BaseModel, Field, StrictStr -from lightly.openapi_generated.swagger_client.models.docker_worker_state import DockerWorkerState - -class UpdateDockerWorkerRegistryEntryRequest(BaseModel): - """ - UpdateDockerWorkerRegistryEntryRequest - """ - state: DockerWorkerState = Field(...) - docker_version: Optional[StrictStr] = Field(None, alias="dockerVersion") - __properties = ["state", "dockerVersion"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> UpdateDockerWorkerRegistryEntryRequest: - """Create an instance of UpdateDockerWorkerRegistryEntryRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> UpdateDockerWorkerRegistryEntryRequest: - """Create an instance of UpdateDockerWorkerRegistryEntryRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return UpdateDockerWorkerRegistryEntryRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in UpdateDockerWorkerRegistryEntryRequest) in the input: " + str(obj)) - - _obj = UpdateDockerWorkerRegistryEntryRequest.parse_obj({ - "state": obj.get("state"), - "docker_version": obj.get("dockerVersion") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/update_team_membership_request.py b/lightly/openapi_generated/swagger_client/models/update_team_membership_request.py deleted file mode 100644 index d5a65559f..000000000 --- a/lightly/openapi_generated/swagger_client/models/update_team_membership_request.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field -from lightly.openapi_generated.swagger_client.models.team_role import TeamRole - -class UpdateTeamMembershipRequest(BaseModel): - """ - UpdateTeamMembershipRequest - """ - role: TeamRole = Field(...) - __properties = ["role"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> UpdateTeamMembershipRequest: - """Create an instance of UpdateTeamMembershipRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> UpdateTeamMembershipRequest: - """Create an instance of UpdateTeamMembershipRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return UpdateTeamMembershipRequest.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in UpdateTeamMembershipRequest) in the input: " + str(obj)) - - _obj = UpdateTeamMembershipRequest.parse_obj({ - "role": obj.get("role") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/user_type.py b/lightly/openapi_generated/swagger_client/models/user_type.py deleted file mode 100644 index ff333fa72..000000000 --- a/lightly/openapi_generated/swagger_client/models/user_type.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import json -import pprint -import re # noqa: F401 -from enum import Enum -from aenum import no_arg # type: ignore - - - - - -class UserType(str, Enum): - """ - UserType - """ - - """ - allowed enum values - """ - FREE = 'FREE' - PROFESSIONAL = 'PROFESSIONAL' - ENTERPRISE = 'ENTERPRISE' - ADMIN = 'ADMIN' - - @classmethod - def from_json(cls, json_str: str) -> 'UserType': - """Create an instance of UserType from a JSON string""" - return UserType(json.loads(json_str)) - - diff --git a/lightly/openapi_generated/swagger_client/models/video_frame_data.py b/lightly/openapi_generated/swagger_client/models/video_frame_data.py deleted file mode 100644 index d2d4a0f8b..000000000 --- a/lightly/openapi_generated/swagger_client/models/video_frame_data.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import Extra, BaseModel, Field, StrictFloat, StrictInt, StrictStr - -class VideoFrameData(BaseModel): - """ - VideoFrameData - """ - source_video: Optional[StrictStr] = Field(None, alias="sourceVideo", description="Name of the source video.") - source_video_frame_index: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="sourceVideoFrameIndex", description="Index of the frame in the source video.") - source_video_frame_timestamp: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="sourceVideoFrameTimestamp", description="Timestamp of the frame in the source video.") - __properties = ["sourceVideo", "sourceVideoFrameIndex", "sourceVideoFrameTimestamp"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> VideoFrameData: - """Create an instance of VideoFrameData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> VideoFrameData: - """Create an instance of VideoFrameData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return VideoFrameData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in VideoFrameData) in the input: " + str(obj)) - - _obj = VideoFrameData.parse_obj({ - "source_video": obj.get("sourceVideo"), - "source_video_frame_index": obj.get("sourceVideoFrameIndex"), - "source_video_frame_timestamp": obj.get("sourceVideoFrameTimestamp") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/models/write_csv_url_data.py b/lightly/openapi_generated/swagger_client/models/write_csv_url_data.py deleted file mode 100644 index aee3a1d43..000000000 --- a/lightly/openapi_generated/swagger_client/models/write_csv_url_data.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - - -from pydantic import Extra, BaseModel, Field, StrictStr - -class WriteCSVUrlData(BaseModel): - """ - WriteCSVUrlData - """ - signed_write_url: StrictStr = Field(..., alias="signedWriteUrl") - embedding_id: StrictStr = Field(..., alias="embeddingId") - __properties = ["signedWriteUrl", "embeddingId"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - use_enum_values = True - extra = Extra.forbid - - def to_str(self, by_alias: bool = False) -> str: - """Returns the string representation of the model""" - return pprint.pformat(self.dict(by_alias=by_alias)) - - def to_json(self, by_alias: bool = False) -> str: - """Returns the JSON representation of the model""" - return json.dumps(self.to_dict(by_alias=by_alias)) - - @classmethod - def from_json(cls, json_str: str) -> WriteCSVUrlData: - """Create an instance of WriteCSVUrlData from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self, by_alias: bool = False): - """Returns the dictionary representation of the model""" - _dict = self.dict(by_alias=by_alias, - exclude={ - }, - exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> WriteCSVUrlData: - """Create an instance of WriteCSVUrlData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return WriteCSVUrlData.parse_obj(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in WriteCSVUrlData) in the input: " + str(obj)) - - _obj = WriteCSVUrlData.parse_obj({ - "signed_write_url": obj.get("signedWriteUrl"), - "embedding_id": obj.get("embeddingId") - }) - return _obj - diff --git a/lightly/openapi_generated/swagger_client/rest.py b/lightly/openapi_generated/swagger_client/rest.py deleted file mode 100644 index b837bfd5a..000000000 --- a/lightly/openapi_generated/swagger_client/rest.py +++ /dev/null @@ -1,301 +0,0 @@ -# coding: utf-8 - -""" - Lightly API - - Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Contact: support@lightly.ai - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -import io -import json -import logging -import re -import ssl - -from urllib.parse import urlencode, quote_plus -import urllib3 - -from lightly.openapi_generated.swagger_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries - - if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name - - - if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - - # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body, allow_nan=False) - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str) or isinstance(body, bytes): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) diff --git a/mypy.ini b/mypy.ini index a4c18e97f..2d77fd6c2 100644 --- a/mypy.ini +++ b/mypy.ini @@ -74,27 +74,6 @@ exclude = (?x)( lightly/data/_utils.py | lightly/data/multi_view_collate.py | lightly/core.py | - lightly/api/api_workflow_compute_worker.py | - lightly/api/api_workflow_predictions.py | - lightly/api/download.py | - lightly/api/api_workflow_export.py | - lightly/api/api_workflow_download_dataset.py | - lightly/api/bitmask.py | - lightly/api/_version_checking.py | - lightly/api/serve.py | - lightly/api/patch.py | - lightly/api/swagger_api_client.py | - lightly/api/api_workflow_collaboration.py | - lightly/api/utils.py | - lightly/api/api_workflow_datasets.py | - lightly/api/api_workflow_selection.py | - lightly/api/swagger_rest_client.py | - lightly/api/api_workflow_datasources.py | - lightly/api/api_workflow_upload_embeddings.py | - lightly/api/api_workflow_client.py | - lightly/api/api_workflow_upload_metadata.py | - lightly/api/api_workflow_tags.py | - lightly/api/api_workflow_artifacts.py | lightly/utils/cropping/crop_image_by_bounding_boxes.py | lightly/utils/cropping/read_yolo_label_file.py | lightly/utils/debug.py | @@ -138,16 +117,6 @@ exclude = (?x)( tests/data/test_LightlyDataset.py | tests/embedding/test_callbacks.py | tests/embedding/test_embedding.py | - tests/api/test_serve.py | - tests/api/test_swagger_rest_client.py | - tests/api/test_rest_parser.py | - tests/api/test_utils.py | - tests/api/benchmark_video_download.py | - tests/api/test_BitMask.py | - tests/api/test_patch.py | - tests/api/test_download.py | - tests/api/test_version_checking.py | - tests/api/test_swagger_api_client.py | tests/utils/test_debug.py | tests/utils/benchmarking/test_benchmark_module.py | tests/utils/benchmarking/test_topk.py | @@ -166,22 +135,6 @@ exclude = (?x)( tests/models/test_ProjectionHeads.py | tests/models/test_ModelsBYOL.py | tests/conftest.py | - tests/api_workflow/test_api_workflow_selection.py | - tests/api_workflow/test_api_workflow_datasets.py | - tests/api_workflow/mocked_api_workflow_client.py | - tests/api_workflow/test_api_workflow_compute_worker.py | - tests/api_workflow/test_api_workflow_artifacts.py | - tests/api_workflow/test_api_workflow_download_dataset.py | - tests/api_workflow/utils.py | - tests/api_workflow/test_api_workflow_client.py | - tests/api_workflow/test_api_workflow_export.py | - tests/api_workflow/test_api_workflow_datasources.py | - tests/api_workflow/test_api_workflow_tags.py | - tests/api_workflow/test_api_workflow_upload_custom_metadata.py | - tests/api_workflow/test_api_workflow_upload_embeddings.py | - tests/api_workflow/test_api_workflow_collaboration.py | - tests/api_workflow/test_api_workflow_predictions.py | - tests/api_workflow/test_api_workflow.py | # Let's not type check deprecated active learning: lightly/active_learning | # Let's not type deprecated models: diff --git a/requirements/base.txt b/requirements/base.txt index cd12091ad..0a0eab2e3 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -4,9 +4,9 @@ hydra-core>=1.0.0 lightly_utils~=0.0.0 numpy>=1.18.1 python_dateutil>=2.5.3 -requests>=2.23.0 +# requests>=2.23.0 six>=1.10 tqdm>=4.44 -urllib3 >= 1.25.3 -pydantic >= 1.10.5, < 2 -aenum >= 3.1.11 \ No newline at end of file +# urllib3 >= 1.25.3 +# pydantic >= 1.10.5, < 2 +# aenum >= 3.1.11 \ No newline at end of file diff --git a/tests/UNMOCKED_end2end_tests/delete_datasets_test_unmocked_cli.py b/tests/UNMOCKED_end2end_tests/delete_datasets_test_unmocked_cli.py index a671d7745..eea012e6c 100644 --- a/tests/UNMOCKED_end2end_tests/delete_datasets_test_unmocked_cli.py +++ b/tests/UNMOCKED_end2end_tests/delete_datasets_test_unmocked_cli.py @@ -1,6 +1,6 @@ import sys -from lightly.api import ApiWorkflowClient +from lightly_api import ApiWorkflowClient if __name__ == "__main__": if len(sys.argv) == 1 + 3: diff --git a/tests/UNMOCKED_end2end_tests/scripts_for_reproducing_problems/test_api_latency.py b/tests/UNMOCKED_end2end_tests/scripts_for_reproducing_problems/test_api_latency.py index 9d58ea06f..31800f8bd 100644 --- a/tests/UNMOCKED_end2end_tests/scripts_for_reproducing_problems/test_api_latency.py +++ b/tests/UNMOCKED_end2end_tests/scripts_for_reproducing_problems/test_api_latency.py @@ -4,8 +4,7 @@ import numpy as np from tqdm import tqdm -from lightly.api import ApiWorkflowClient -from lightly.openapi_generated.swagger_client import ApiClient, Configuration, QuotaApi +from lightly_api import ApiWorkflowClient, ApiClient, Configuration, QuotaApi if __name__ == "__main__": token = os.getenv("LIGHTLY_TOKEN") diff --git a/tests/api/benchmark_video_download.py b/tests/api/benchmark_video_download.py deleted file mode 100644 index 107b51eb9..000000000 --- a/tests/api/benchmark_video_download.py +++ /dev/null @@ -1,67 +0,0 @@ -import time -import unittest - -import av -import numpy as np -from tqdm import tqdm - -from lightly.api.download import ( - download_all_video_frames, - download_video_frame, - download_video_frames_at_timestamps, -) - - -@unittest.skip("Only used for benchmarks") -class BenchmarkDownloadVideoFrames(unittest.TestCase): - """ - some timings: https://github.com/lightly-ai/lightly/pull/754 - """ - - @classmethod - def setUpClass(cls) -> None: - cls.video_url_12min_100mb = "https://mediandr-a.akamaihd.net/progressive/2018/0912/TV-20180912-1628-0000.ln.mp4" - with av.open(cls.video_url_12min_100mb) as container: - stream = container.streams.video[0] - duration = stream.duration - # This video has its timestamps 0-based - cls.timestamps = np.linspace(0, duration, num=1000).astype(int).tolist() - - def setUp(self) -> None: - self.start_time = time.time() - - def test_download_full(self): - all_video_frames = download_all_video_frames(self.video_url_12min_100mb) - for i, frame in enumerate(tqdm(all_video_frames)): - pass - - # Takes very long for many frames, but is very quick for little frames - # The reason is that - # - every function call has quite some overhead - # - as many frames are skipped by the seek, this only reads a little number of frames per function call. - def test_download_at_timestamps_for_loop(self): - for timestamp in tqdm(self.timestamps): - frame = download_video_frame(self.video_url_12min_100mb, timestamp) - - def test_download_at_timestamps(self): - frames = download_video_frames_at_timestamps( - self.video_url_12min_100mb, self.timestamps - ) - frames = list(tqdm(frames, total=len(self.timestamps))) - - # Takes long as it downloads the whole video first - # Takes long, as it access the frames even at random locations, similar to - # downloading specific frame in a for loop. - def test_download_at_indices_decord(self): - """ - See https://github.com/dmlc/decord/issues/199 - """ - import decord - - vr = decord.VideoReader(self.video_url_12min_100mb) - decord.bridge.set_bridge("torch") - print(f"Took {time.time() - self.start_time}s for creating the video reader.") - frames = vr.get_batch(list(range(0, 18000, 18))) - - def tearDown(self) -> None: - print(f"Took {time.time()-self.start_time}s") diff --git a/tests/api/test_BitMask.py b/tests/api/test_BitMask.py deleted file mode 100644 index 1d477232c..000000000 --- a/tests/api/test_BitMask.py +++ /dev/null @@ -1,195 +0,0 @@ -import unittest -from copy import deepcopy -from random import randint, random, seed - -from lightly.api.bitmask import BitMask - -N = 10 - - -class TestBitMask(unittest.TestCase): - def setup(self, psuccess=1.0): - pass - - def test_get_and_set(self): - mask = BitMask.from_bin("0b11110000") - - self.assertFalse(mask.get_kth_bit(2)) - mask.set_kth_bit(2) - self.assertTrue(mask.get_kth_bit(2)) - - self.assertTrue(mask.get_kth_bit(4)) - mask.unset_kth_bit(4) - self.assertFalse(mask.get_kth_bit(4)) - - def test_large_bitmasks(self): - bitstring = "0b" + "1" * 5678 - mask = BitMask.from_bin(bitstring) - mask_as_bitstring = mask.to_bin() - self.assertEqual(mask_as_bitstring, bitstring) - - def test_bitmask_from_length(self): - length = 4 - mask = BitMask.from_length(length) - self.assertEqual(mask.to_bin(), "0b1111") - - def test_get_and_set_outside_of_range(self): - mask = BitMask.from_bin("0b11110000") - - self.assertFalse(mask.get_kth_bit(100)) - mask.set_kth_bit(100) - self.assertTrue(mask.get_kth_bit(100)) - - def test_inverse(self): - # TODO: proper implementation - return - - x = int("0b11110000", 2) - y = int("0b00001111", 2) - mask = BitMask(x) - mask.invert() - self.assertEqual(mask.x, y) - - x = int("0b010101010101010101", 2) - y = int("0b101010101010101010", 2) - mask = BitMask(x) - mask.invert() - self.assertEqual(mask.x, y) - - def test_store_and_retrieve(self): - x = int("0b01010100100100100100100010010100100100101001001010101010", 2) - mask = BitMask(x) - mask.set_kth_bit(11) - mask.set_kth_bit(22) - mask.set_kth_bit(33) - mask.set_kth_bit(44) - mask.set_kth_bit(55) - mask.set_kth_bit(66) - mask.set_kth_bit(77) - mask.set_kth_bit(88) - mask.set_kth_bit(99) - - somewhere = mask.to_hex() - somewhere_else = mask.to_bin() - - mask_somewhere = BitMask.from_hex(somewhere) - mask_somewhere_else = BitMask.from_bin(somewhere_else) - - self.assertEqual(mask.x, mask_somewhere.x) - self.assertEqual(mask.x, mask_somewhere_else.x) - - def test_union(self): - mask_a = BitMask.from_bin("0b001") - mask_b = BitMask.from_bin("0b100") - mask_a.union(mask_b) - self.assertEqual(mask_a.x, int("0b101", 2)) - - def test_intersection(self): - mask_a = BitMask.from_bin("0b101") - mask_b = BitMask.from_bin("0b100") - mask_a.intersection(mask_b) - self.assertEqual(mask_a.x, int("0b100", 2)) - - def assert_difference(self, bistring_1: str, bitstring_2: str, target: str): - mask_a = BitMask.from_bin(bistring_1) - mask_b = BitMask.from_bin(bitstring_2) - mask_a.difference(mask_b) - self.assertEqual(mask_a.x, int(target, 2)) - - def test_differences(self): - self.assert_difference("0b101", "0b001", "0b100") - self.assert_difference("0b0111", "0b1100", "0b0011") - self.assert_difference("0b10111", "0b01100", "0b10011") - - def random_bitstring(self, length: int): - bitsting = "0b" - for i in range(length): - bitsting += str(randint(0, 1)) - return bitsting - - def test_difference_random(self): - seed(42) - for rep in range(10): - for string_length in range(1, 100, 10): - bitstring_1 = self.random_bitstring(string_length) - bitstring_2 = self.random_bitstring(string_length) - target = "0b" - for bit_1, bit_2 in zip(bitstring_1[2:], bitstring_2[2:]): - if bit_1 == "1" and bit_2 == "0": - target += "1" - else: - target += "0" - self.assert_difference(bitstring_1, bitstring_2, target) - - def test_operator_minus(self): - mask_a = BitMask.from_bin("0b10111") - mask_a_old = deepcopy(mask_a) - mask_b = BitMask.from_bin("0b01100") - mask_target = BitMask.from_bin("0b10011") - diff = mask_a - mask_b - self.assertEqual(diff, mask_target) - self.assertEqual( - mask_a_old, mask_a - ) # make sure the original mask is unchanged. - - def test_equal(self): - mask_a = BitMask.from_bin("0b101") - mask_b = BitMask.from_bin("0b101") - self.assertEqual(mask_a, mask_b) - - def test_masked_select_from_list(self): - n = 1000 - list_ = [randint(0, 1) for _ in range(n - 2)] + [0, 1] - mask = BitMask.from_length(n) - for index, item_ in enumerate(list_): - if item_ == 0: - mask.unset_kth_bit(index) - else: - mask.set_kth_bit(index) - - all_ones = mask.masked_select_from_list(list_) - mask.invert(n) - all_zeros = mask.masked_select_from_list(list_) - self.assertGreater(len(all_ones), 0) - self.assertGreater(len(all_zeros), 0) - self.assertTrue(all([item_ > 0 for item_ in all_ones])) - self.assertTrue(all([item_ == 0 for item_ in all_zeros])) - - def test_masked_select_from_list_example(self): - list_ = [1, 2, 3, 4, 5, 6] - mask = BitMask.from_bin("0b001101") # expected result is [1, 3, 4] - selected = mask.masked_select_from_list(list_) - self.assertListEqual(selected, [1, 3, 4]) - - def test_invert(self): - # get random bitstring - length = 10 - bitstring = self.random_bitstring(10) - - # get inverse - mask = BitMask.from_bin(bitstring) - mask.invert(length) - inverted = mask.to_bin() - - # remove 0b - inverted = inverted[2:] - bitstring = bitstring[2:] - for i in range(min(len(bitstring), len(inverted))): - if bitstring[-i - 1] == "0": - self.assertEqual(inverted[-i - 1], "1") - else: - self.assertEqual(inverted[-i - 1], "0") - - def test_nonzero_bits(self): - mask = BitMask.from_bin("0b0") - indices = [100, 1000, 10_000, 100_000] - - self.assertEqual(mask.x, 0) - for index in indices: - mask.set_kth_bit(index) - - self.assertGreaterEqual(mask.x, 0) - also_indices = mask.to_indices() - - for i, j in zip(indices, also_indices): - self.assertEqual(i, j) diff --git a/tests/api/test_download.py b/tests/api/test_download.py deleted file mode 100644 index 8921d461f..000000000 --- a/tests/api/test_download.py +++ /dev/null @@ -1,608 +0,0 @@ -import json -import os -import sys -import tempfile -import unittest -import warnings -from io import BytesIO -from unittest import mock - -import numpy as np -import tqdm -from PIL import Image - -try: - import av - - AV_AVAILABLE = True -except ImportError: - AV_AVAILABLE = False - -# mock requests module so that files are read from -# disk instead of loading them from a remote url - - -class MockedRequestsModule: - def get(self, url, stream=None, *args, **kwargs): - return MockedResponse(url) - - class Session: - def get(self, url, stream=None, *args, **kwargs): - return MockedResponse(url) - - -class MockedRequestsModulePartialResponse: - def get(self, url, stream=None, *args, **kwargs): - return MockedResponsePartialStream(url) - - def raise_for_status(self): - return - - class Session: - def get(self, url, stream=None, *args, **kwargs): - return MockedResponsePartialStream(url) - - -class MockedResponse: - def __init__(self, raw): - self._raw = raw - - @property - def raw(self): - # instead of returning the byte stream from the url - # we just give back an openend filehandle - return open(self._raw, "rb") - - @property - def status_code(self): - return 200 - - def raise_for_status(self): - return - - def json(self): - # instead of returning the byte stream from the url - # we just load the json and return the dictionary - with open(self._raw, "r") as f: - return json.load(f) - - def __enter__(self): - return self - - def __exit__(self, *args): - pass - - -class MockedResponsePartialStream(MockedResponse): - return_partial_stream = True - - @property - def raw(self): - # instead of returning the byte stream from the url - # we just give back an openend filehandle - stream = open(self._raw, "rb") - if self.return_partial_stream: - bytes = stream.read() - stream_first_part = BytesIO(bytes[:1024]) - MockedResponsePartialStream.return_partial_stream = False - return stream_first_part - else: - return stream - - -import lightly - - -@mock.patch("lightly.api.download.requests", MockedRequestsModulePartialResponse()) -class TestDownloadPartialRespons(unittest.TestCase): - def setUp(self): - self._max_retries = lightly.api.utils.RETRY_MAX_RETRIES - self._max_backoff = lightly.api.utils.RETRY_MAX_BACKOFF - lightly.api.utils.RETRY_MAX_RETRIES = 1 - lightly.api.utils.RETRY_MAX_BACKOFF = 0 - warnings.filterwarnings("ignore") - - def tearDown(self): - lightly.api.utils.RETRY_MAX_RETRIES = self._max_retries - lightly.api.utils.RETRY_MAX_BACKOFF = self._max_backoff - warnings.filterwarnings("default") - - def test_download_image_half_broken_retry_once(self): - lightly.api.utils.RETRY_MAX_RETRIES = 1 - - original = _pil_image() - with tempfile.NamedTemporaryFile(suffix=".png") as file: - original.save(file.name) - # assert that the retry fails - with self.assertRaises(RuntimeError) as error: - image = lightly.api.download.download_image(file.name) - self.assertTrue("Maximum retries exceeded" in str(error.exception)) - self.assertTrue("" in str(error.exception)) - self.assertTrue("image file is truncated" in str(error.exception)) - - def test_download_image_half_broken_retry_twice(self): - lightly.api.utils.RETRY_MAX_RETRIES = 2 - MockedResponse.return_partial_stream = True - original = _pil_image() - with tempfile.NamedTemporaryFile(suffix=".png") as file: - original.save(file.name) - image = lightly.api.download.download_image(file.name) - assert _images_equal(image, original) - - -@mock.patch("lightly.api.download.requests", MockedRequestsModule()) -class TestDownload(unittest.TestCase): - def setUp(self): - self._max_retries = lightly.api.utils.RETRY_MAX_RETRIES - self._max_backoff = lightly.api.utils.RETRY_MAX_BACKOFF - lightly.api.utils.RETRY_MAX_RETRIES = 1 - lightly.api.utils.RETRY_MAX_BACKOFF = 0 - warnings.filterwarnings("ignore") - - def tearDown(self): - lightly.api.utils.RETRY_MAX_RETRIES = self._max_retries - lightly.api.utils.RETRY_MAX_BACKOFF = self._max_backoff - warnings.filterwarnings("default") - - def test_download_image(self): - original = _pil_image() - with tempfile.NamedTemporaryFile(suffix=".png") as file: - original.save(file.name) - for request_kwargs in [None, {"stream": False}]: - with self.subTest(request_kwargs=request_kwargs): - image = lightly.api.download.download_image( - file.name, request_kwargs=request_kwargs - ) - assert _images_equal(image, original) - - def test_download_prediction(self): - original = _json_prediction() - with tempfile.NamedTemporaryFile(suffix=".json", mode="w+") as file: - with open(file.name, "w") as f: - json.dump(original, f) - for request_kwargs in [None, {"stream": False}]: - with self.subTest(request_kwargs=request_kwargs): - response = lightly.api.download.download_prediction_file( - file.name, - request_kwargs=request_kwargs, - ) - self.assertDictEqual(response, original) - - def test_download_image_with_session(self): - session = MockedRequestsModule.Session() - original = _pil_image() - with tempfile.NamedTemporaryFile(suffix=".png") as file: - original.save(file.name) - image = lightly.api.download.download_image(file.name, session=session) - assert _images_equal(image, original) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frames(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - original = _generate_video(file.name) - frames = list(lightly.api.download.download_all_video_frames(file.name)) - for frame, orig in zip(frames, original): - assert _images_equal(frame, orig) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frames_timeout(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - _generate_video(file.name) - with self.assertRaisesRegexp( - RuntimeError, - "Maximum retries exceeded.*av.error.ExitError.*Immediate exit requested.*", - ): - list( - lightly.api.download.download_all_video_frames(file.name, timeout=0) - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_last_video_frame(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - n_frames = 5 - original = _generate_video(file.name, n_frames=n_frames) - timestamps = list(range(1, n_frames + 1)) - for timestamp in timestamps: - with self.subTest(timestamp=timestamp): - if timestamp > n_frames: - with self.assertRaises(RuntimeError): - frame = lightly.api.download.download_video_frame( - file.name, timestamp - ) - else: - frame = lightly.api.download.download_video_frame( - file.name, timestamp - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frames_at_timestamps(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - n_frames = 5 - original = _generate_video(file.name, n_frames=n_frames) - original_timestamps = list(range(1, n_frames + 1)) - frame_indices = list(range(2, len(original) - 1, 2)) - timestamps = [original_timestamps[i] for i in frame_indices] - frames = list( - lightly.api.download.download_video_frames_at_timestamps( - file.name, timestamps - ) - ) - self.assertEqual(len(frames), len(timestamps)) - for frame, timestamp in zip(frames, frame_indices): - orig = original[timestamp] - assert _images_equal(frame, orig) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frames_at_timestamps_timeout(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - n_frames = 5 - _generate_video(file.name, n_frames) - with self.assertRaisesRegexp( - RuntimeError, - "Maximum retries exceeded.*av.error.ExitError.*Immediate exit requested.*", - ): - list( - lightly.api.download.download_video_frames_at_timestamps( - file.name, - timestamps=list(range(1, n_frames + 1)), - timeout=0, - ) - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frames_at_timestamps_wrong_order(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - original = _generate_video(file.name) - timestamps = [2, 1] - with self.assertRaises(ValueError): - frames = list( - lightly.api.download.download_video_frames_at_timestamps( - file.name, timestamps - ) - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frames_at_timestamps_emtpy(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - frames = list( - lightly.api.download.download_video_frames_at_timestamps( - file.name, timestamps=[] - ) - ) - self.assertEqual(len(frames), 0) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frames_restart_throws(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - original = _generate_video(file.name) - with self.assertRaises(ValueError): - # timestamp too small - frames = list( - lightly.api.download.download_all_video_frames( - file.name, timestamp=-1 - ) - ) - - # timestamp too large - frames = list( - lightly.api.download.download_all_video_frames( - file.name, timestamp=len(original) + 1 - ) - ) - self.assertEqual(len(frames), 0) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frames_restart_at_0(self): - # relevant for restarting if the frame iterator is empty - # although it shouldn't be - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - original = _generate_video(file.name) - frames = list( - lightly.api.download.download_all_video_frames( - file.name, timestamp=None - ) - ) - for frame, orig in zip(frames, original): - assert _images_equal(frame, orig) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frames_restart(self): - # relevant if decoding a frame goes wrong for some reason and we - # want to try again - restart_timestamp = 3 - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - original = _generate_video(file.name) - frames = list( - lightly.api.download.download_all_video_frames( - file.name, restart_timestamp - ) - ) - for frame, orig in zip(frames, original[2:]): - assert _images_equal(frame, orig) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frame_fps(self): - for fps in [24, 30, 60]: - with self.subTest(msg=f"fps={fps}"), tempfile.NamedTemporaryFile( - suffix=".avi" - ) as file: - original = _generate_video(file.name, fps=fps) - all_frames = lightly.api.download.download_all_video_frames( - file.name, - as_pil_image=False, - ) - for true_frame in all_frames: - frame = lightly.api.download.download_video_frame( - file.name, - timestamp=true_frame.pts, - as_pil_image=False, - ) - assert frame.pts == true_frame.pts - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frame_timestamp_exception(self): - for fps in [24, 30, 60]: - with self.subTest(msg=f"fps={fps}"), tempfile.NamedTemporaryFile( - suffix=".avi" - ) as file: - original = _generate_video(file.name, fps=fps) - - # this should be the last frame and exist - frame = lightly.api.download.download_video_frame( - file.name, len(original) - ) - assert _images_equal(frame, original[-1]) - - # timestamp after last frame - with self.assertRaises(RuntimeError): - lightly.api.download.download_video_frame( - file.name, len(original) + 1 - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frame_negative_timestamp_exception(self): - for fps in [24, 30, 60]: - with self.subTest(msg=f"fps={fps}"), tempfile.NamedTemporaryFile( - suffix=".avi" - ) as file: - _generate_video(file.name, fps=fps) - with self.assertRaises(ValueError): - lightly.api.download.download_video_frame(file.name, -1) - - def test_download_and_write_file(self): - original = _pil_image() - with tempfile.NamedTemporaryFile( - suffix=".png" - ) as file1, tempfile.NamedTemporaryFile(suffix=".png") as file2: - original.save(file1.name) - lightly.api.download.download_and_write_file(file1.name, file2.name) - image = Image.open(file2.name) - assert _images_equal(original, image) - - def test_download_and_write_file_with_session(self): - session = MockedRequestsModule.Session() - original = _pil_image() - with tempfile.NamedTemporaryFile( - suffix=".png" - ) as file1, tempfile.NamedTemporaryFile(suffix=".png") as file2: - original.save(file1.name) - lightly.api.download.download_and_write_file( - file1.name, file2.name, session=session - ) - image = Image.open(file2.name) - assert _images_equal(original, image) - - def test_download_and_write_all_files(self): - n_files = 3 - max_workers = 2 - originals = [_pil_image(seed=i) for i in range(n_files)] - filenames = [f"filename_{i}.png" for i in range(n_files)] - with tempfile.TemporaryDirectory() as tempdir1, tempfile.TemporaryDirectory() as tempdir2: - for request_kwargs in [None, {"stream": False}]: - with self.subTest(request_kwargs=request_kwargs): - # save images at "remote" location - urls = [ - os.path.join(tempdir1, f"url_{i}.png") for i in range(n_files) - ] - for image, url in zip(originals, urls): - image.save(url) - - # download images from remote to local - file_infos = list(zip(filenames, urls)) - lightly.api.download.download_and_write_all_files( - file_infos, - output_dir=tempdir2, - max_workers=max_workers, - request_kwargs=request_kwargs, - ) - - for orig, filename in zip(originals, filenames): - image = Image.open(os.path.join(tempdir2, filename)) - assert _images_equal(orig, image) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frame_count(self): - fps = 24 - for true_n_frames in [24, 30, 60]: - for suffix in [".avi", ".mpeg"]: - with tempfile.NamedTemporaryFile(suffix=suffix) as file, self.subTest( - msg=f"n_frames={true_n_frames}, extension={suffix}" - ): - _generate_video(file.name, n_frames=true_n_frames, fps=fps) - n_frames = lightly.api.download.video_frame_count(file.name) - assert n_frames == true_n_frames - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_Frame_count_timeout(self): - with tempfile.NamedTemporaryFile(suffix=".avi") as file: - _generate_video(file.name) - with self.assertRaisesRegexp( - RuntimeError, - "Maximum retries exceeded.*av.error.ExitError.*Immediate exit requested.*", - ): - lightly.api.download.video_frame_count(file.name, timeout=0) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_video_frame_count_no_metadata(self): - fps = 24 - for true_n_frames in [24, 30, 60]: - for suffix in [".avi", ".mpeg"]: - with tempfile.NamedTemporaryFile(suffix=suffix) as file, self.subTest( - msg=f"n_frames={true_n_frames}, extension={suffix}" - ): - _generate_video(file.name, n_frames=true_n_frames, fps=fps) - n_frames = lightly.api.download.video_frame_count( - file.name, ignore_metadata=True - ) - assert n_frames == true_n_frames - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frame_counts(self): - true_n_frames = [3, 5] - fps = 24 - for suffix in [".avi", ".mpeg"]: - with tempfile.NamedTemporaryFile( - suffix=suffix - ) as file1, tempfile.NamedTemporaryFile( - suffix=suffix - ) as file2, self.subTest( - msg=f"extension={suffix}" - ): - _generate_video(file1.name, n_frames=true_n_frames[0], fps=fps) - _generate_video(file2.name, n_frames=true_n_frames[1], fps=fps) - frame_counts = lightly.api.download.all_video_frame_counts( - urls=[file1.name, file2.name], - ) - assert sum(frame_counts) == sum(true_n_frames) - assert frame_counts == true_n_frames - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frame_counts_broken(self): - fps = 24 - n_frames = 5 - with tempfile.NamedTemporaryFile( - suffix=".mpeg" - ) as file1, tempfile.NamedTemporaryFile(suffix=".mpeg") as file2: - _generate_video(file1.name, fps=fps, n_frames=n_frames) - _generate_video(file2.name, fps=fps, broken=True) - - urls = [file1.name, file2.name] - result = lightly.api.download.all_video_frame_counts(urls) - assert result == [n_frames, None] - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frame_counts_broken_ignore_exceptions(self): - fps = 24 - n_frames = 5 - with tempfile.NamedTemporaryFile( - suffix=".mpeg" - ) as file1, tempfile.NamedTemporaryFile(suffix=".mpeg") as file2: - _generate_video(file1.name, fps=fps, n_frames=n_frames) - _generate_video(file2.name, fps=fps, broken=True) - - urls = [file1.name, file2.name] - with self.assertRaises(RuntimeError): - result = lightly.api.download.all_video_frame_counts( - urls, - exceptions_indicating_empty_video=tuple(), - ) - - @unittest.skipUnless(AV_AVAILABLE, "Pyav not installed") - def test_download_all_video_frame_counts_progress_bar(self): - true_n_frames = [3, 5] - fps = 24 - pbar = mock.Mock(wraps=tqdm.tqdm(unit="videos")) - with tempfile.NamedTemporaryFile( - suffix=".avi" - ) as file1, tempfile.NamedTemporaryFile(suffix=".avi") as file2: - _generate_video(file1.name, n_frames=true_n_frames[0], fps=fps) - _generate_video(file2.name, n_frames=true_n_frames[1], fps=fps) - frame_counts = lightly.api.download.all_video_frame_counts( - urls=[file1.name, file2.name], - progress_bar=pbar, - ) - assert sum(frame_counts) == sum(true_n_frames) - assert frame_counts == true_n_frames - assert pbar.update.call_count == len(true_n_frames) - - -def _images_equal(image1, image2): - # note that images saved and loaded from disk must - # use a lossless format, otherwise this equality will not hold - return np.all(np.array(image1) == np.array(image2)) - - -def _pil_image(width=100, height=50, seed=0): - np.random.seed(seed) - image = (np.random.randn(width, height, 3) * 255).astype(np.uint8) - image = Image.fromarray(image, mode="RGB") - return image - - -def _json_prediction(): - return { - "string": "Hello World", - "int": 1, - "float": 0.5, - } - - -def _generate_video( - out_file, - n_frames=5, - width=100, - height=50, - seed=0, - fps=24, - broken=False, -): - """Generate a video. - - Use .avi extension if you want to save a lossless video. Use '.mpeg' for - videos which should have streams.frames = 0, so that the whole video must - be loaded to find the total number of frames. Note that mpeg requires - fps = 24. - - """ - is_mpeg = out_file.endswith(".mpeg") - video_format = "libx264rgb" - pixel_format = "rgb24" - - if is_mpeg: - video_format = "mpeg1video" - pixel_format = "yuv420p" - - if broken: - n_frames = 0 - - np.random.seed(seed) - container = av.open(out_file, mode="w") - stream = container.add_stream(video_format, rate=fps) - stream.width = width - stream.height = height - stream.pix_fmt = pixel_format - - if is_mpeg: - frames = [av.VideoFrame(width, height, pixel_format) for i in range(n_frames)] - else: - # save lossless video - stream.options["crf"] = "0" - images = (np.random.randn(n_frames, height, width, 3) * 255).astype(np.uint8) - frames = [ - av.VideoFrame.from_ndarray(image, format=pixel_format) for image in images - ] - - for frame in frames: - for packet in stream.encode(frame): - container.mux(packet) - - if not broken: - # flush the stream - # video cannot be loaded if this is omitted - packet = stream.encode(None) - container.mux(packet) - - container.close() - - pil_images = [frame.to_image() for frame in frames] - return pil_images diff --git a/tests/api/test_patch.py b/tests/api/test_patch.py deleted file mode 100644 index fdaad235b..000000000 --- a/tests/api/test_patch.py +++ /dev/null @@ -1,52 +0,0 @@ -import logging -import pickle - -from lightly.openapi_generated.swagger_client import Configuration - - -def test_make_swagger_configuration_picklable() -> None: - config = Configuration() - # Fix value to make test reproducible on systems with different number of cpus. - config.connection_pool_maxsize = 4 - new_config = pickle.loads(pickle.dumps(config)) - - expected = { - "_Configuration__debug": False, - "_Configuration__logger_file": None, - "_Configuration__logger_format": "%(asctime)s %(levelname)s %(message)s", - "api_key_prefix": {}, - "api_key": {}, - "assert_hostname": None, - "cert_file": None, - "client_side_validation": True, - "connection_pool_maxsize": 4, - "_base_path": "https://api.lightly.ai", - "key_file": None, - "logger_file_handler": None, - # "logger_formatter", ignore because a new object is created on unpickle - # "logger_stream_handler", ignore because a new object is created on unpickle - "logger": { - "package_logger": logging.getLogger( - "lightly.openapi_generated.swagger_client" - ), - "urllib3_logger": logging.getLogger("urllib3"), - }, - "password": None, - "proxy": None, - "refresh_api_key_hook": None, - "safe_chars_for_path_param": "", - "ssl_ca_cert": None, - "temp_folder_path": None, - "username": None, - "verify_ssl": True, - } - # Check that all expected values are set except the ignored ones. - assert all(hasattr(config, key) for key in expected.keys()) - # Check that new_config values are equal to expected values. - assert all(new_config.__dict__[key] == value for key, value in expected.items()) - - # Extra assertions for attributes ignored in the tests above. - assert isinstance(new_config.__dict__["logger_formatter"], logging.Formatter) - assert isinstance( - new_config.__dict__["logger_stream_handler"], logging.StreamHandler - ) diff --git a/tests/api/test_rest_parser.py b/tests/api/test_rest_parser.py deleted file mode 100644 index 860f4c0ac..000000000 --- a/tests/api/test_rest_parser.py +++ /dev/null @@ -1,38 +0,0 @@ -import unittest - -import numpy as np - -from lightly.openapi_generated.swagger_client import ( - ActiveLearningScoreCreateRequest, - ApiClient, - SamplingMethod, - ScoresApi, -) -from lightly.openapi_generated.swagger_client.rest import ApiException - - -class TestRestParser(unittest.TestCase): - @unittest.skip("This test only shows the error, it does not ensure it is solved.") - def test_parse_active_learning_scores(self): - score_value_tuple = ( - np.random.normal(0, 1, size=(999,)).astype(np.float32), - np.random.normal(0, 1, size=(999,)).astype(np.float64), - [12.0] * 999, - ) - api_client = ApiClient() - self._scores_api = ScoresApi(api_client) - for i, score_values in enumerate(score_value_tuple): - with self.subTest(i=i, msg=str(type(score_values))): - body = ActiveLearningScoreCreateRequest( - score_type=SamplingMethod.CORESET, scores=list(score_values) - ) - if isinstance(score_values[0], float): - with self.assertRaises(ApiException): - self._scores_api.create_or_update_active_learning_score_by_tag_id( - body, dataset_id="dataset_id_xyz", tag_id="tag_id_xyz" - ) - else: - with self.assertRaises(AttributeError): - self._scores_api.create_or_update_active_learning_score_by_tag_id( - body, dataset_id="dataset_id_xyz", tag_id="tag_id_xyz" - ) diff --git a/tests/api/test_serve.py b/tests/api/test_serve.py deleted file mode 100644 index d5b91438b..000000000 --- a/tests/api/test_serve.py +++ /dev/null @@ -1,30 +0,0 @@ -from pathlib import Path - -from lightly.api import serve - - -def test__translate_path(tmp_path: Path) -> None: - tmp_file = tmp_path / "hello/world.txt" - assert serve._translate_path(path="/hello/world.txt", directories=[]) == "" - assert serve._translate_path(path="/hello/world.txt", directories=[tmp_path]) == "" - tmp_file.mkdir(parents=True, exist_ok=True) - tmp_file.touch() - assert serve._translate_path( - path="/hello/world.txt", directories=[tmp_path] - ) == str(tmp_file) - assert serve._translate_path( - path="/world.txt", - directories=[tmp_path / "hi", tmp_path / "hello"], - ) == str(tmp_file) - - -def test__translate_path__special_chars(tmp_path: Path) -> None: - (tmp_path / "white space.txt").touch() - assert serve._translate_path( - path="/white%20space.txt", directories=[tmp_path] - ) == str(tmp_path / "white space.txt") - - (tmp_path / "parens(1).txt").touch() - assert serve._translate_path( - path="/parens%281%29.txt", directories=[tmp_path] - ) == str(tmp_path / "parens(1).txt") diff --git a/tests/api/test_swagger_api_client.py b/tests/api/test_swagger_api_client.py deleted file mode 100644 index 98ad22db8..000000000 --- a/tests/api/test_swagger_api_client.py +++ /dev/null @@ -1,37 +0,0 @@ -import pickle - -from pytest_mock import MockerFixture - -from lightly.api.swagger_api_client import LightlySwaggerApiClient -from lightly.api.swagger_rest_client import LightlySwaggerRESTClientObject -from lightly.openapi_generated.swagger_client import Configuration -from lightly.openapi_generated.swagger_client.rest import RESTResponse - - -def test_pickle(mocker: MockerFixture) -> None: - client = LightlySwaggerApiClient(configuration=Configuration(), timeout=5) - client.last_response = mocker.MagicMock(spec_set=RESTResponse).return_value - new_client = pickle.loads(pickle.dumps(client)) - - expected = { - "_pool": None, - "client_side_validation": True, - # "configuration", ignore because some parts of configuration are recreated on unpickling - "cookie": None, - "default_headers": {"User-Agent": "OpenAPI-Generator/1.0.0/python"}, - # "last_response", ignore because it is not copied during pickling - # "rest_client", ignore because some parts of rest client are recreated on unpickling - } - # Check that all expected values are set except the ignored ones. - assert all(hasattr(client, key) for key in expected.keys()) - # Check that new client values are equal to expected values. - assert all(new_client.__dict__[key] == value for key, value in expected.items()) - - # Extra assertions for attributes ignored in the tests above. - assert isinstance(new_client.__dict__["configuration"], Configuration) - assert isinstance( - new_client.__dict__["rest_client"], LightlySwaggerRESTClientObject - ) - # Last reponse is completely removed from client object and is only dynamically - # reassigned in the ApiClient.__call_api method. - assert not hasattr(new_client, "last_response") diff --git a/tests/api/test_swagger_rest_client.py b/tests/api/test_swagger_rest_client.py deleted file mode 100644 index 4f522a7ec..000000000 --- a/tests/api/test_swagger_rest_client.py +++ /dev/null @@ -1,72 +0,0 @@ -import pickle - -from pytest_mock import MockerFixture -from urllib3 import PoolManager, Timeout - -from lightly.api.swagger_rest_client import LightlySwaggerRESTClientObject -from lightly.openapi_generated.swagger_client.configuration import Configuration - - -class TestLightlySwaggerRESTClientObject: - def test__pickle(self) -> None: - client = LightlySwaggerRESTClientObject( - configuration=Configuration(), timeout=5 - ) - new_client = pickle.loads(pickle.dumps(client)) - expected = { - # "configuration", ignore because some parts of configuration are recreated on unpickling - "maxsize": None, - # "pool_manager", ignore because pool_manager is recreated on unpickling - "pools_size": 4, - "timeout": 5, - } - - # Check that all expected values are set except the ignored ones. - assert set(expected.keys()) == set(client.__dict__.keys()) - { - "configuration", - "pool_manager", - } - # Check that new client values are equal to expected values. - assert all(new_client.__dict__[key] == value for key, value in expected.items()) - - # Extra assertions for attributes ignored in the tests above. - assert isinstance(new_client.__dict__["configuration"], Configuration) - assert isinstance(new_client.__dict__["pool_manager"], PoolManager) - - def test_request__timeout(self, mocker: MockerFixture) -> None: - client = LightlySwaggerRESTClientObject( - configuration=Configuration(), timeout=5 - ) - response = mocker.MagicMock() - response.status = 200 - client.pool_manager.request = mocker.MagicMock(return_value=response) - - # use default timeout - client.request(method="GET", url="some-url") - - calls = client.pool_manager.request.mock_calls - _, _, kwargs = calls[0] - assert isinstance(kwargs["timeout"], Timeout) - assert kwargs["timeout"].total == 5 - - # use custom timeout - client.request(method="GET", url="some-url", _request_timeout=10) - calls = client.pool_manager.request.mock_calls - _, _, kwargs = calls[1] - assert isinstance(kwargs["timeout"], Timeout) - assert kwargs["timeout"].total == 10 - - def test_request__connection_read_timeout(self, mocker: MockerFixture) -> None: - client = LightlySwaggerRESTClientObject( - configuration=Configuration(), timeout=(1, 2) - ) - response = mocker.MagicMock() - response.status = 200 - client.pool_manager.request = mocker.MagicMock(return_value=response) - - client.request(method="GET", url="some-url") - calls = client.pool_manager.request.mock_calls - _, _, kwargs = calls[0] - assert isinstance(kwargs["timeout"], Timeout) - assert kwargs["timeout"].connect_timeout == 1 - assert kwargs["timeout"].read_timeout == 2 diff --git a/tests/api/test_utils.py b/tests/api/test_utils.py deleted file mode 100644 index 5be42f030..000000000 --- a/tests/api/test_utils.py +++ /dev/null @@ -1,149 +0,0 @@ -import os -import unittest -from unittest import mock - -import pytest -from PIL import Image - -from lightly.api.utils import ( - DatasourceType, - PIL_to_bytes, - get_lightly_server_location_from_env, - get_signed_url_destination, - getenv, - paginate_endpoint, - retry, -) - - -class TestUtils(unittest.TestCase): - def test_retry_success(self): - def my_func(arg, kwarg=5): - return arg + kwarg - - self.assertEqual(retry(my_func, 5, kwarg=5), 10) - - def test_retry_fail(self): - def my_func(): - raise RuntimeError() - - with self.assertRaises(RuntimeError), mock.patch("time.sleep"): - retry(my_func) - - def test_getenv(self): - os.environ["TEST_ENV_VARIABLE"] = "hello world" - env = getenv("TEST_ENV_VARIABLE", "default") - self.assertEqual(env, "hello world") - - def test_getenv_fail(self): - env = getenv("TEST_ENV_VARIABLE_WHICH_DOES_NOT_EXIST", "hello world") - self.assertEqual(env, "hello world") - - def test_PIL_to_bytes(self): - image = Image.new("RGB", (128, 128)) - - # test with quality=None - PIL_to_bytes(image) - - # test with quality=90 - PIL_to_bytes(image, quality=90) - - # test with quality=90 and ext=jpg - PIL_to_bytes(image, ext="JPEG", quality=90) - - def test_get_signed_url_destination(self): - # S3 - self.assertEqual( - get_signed_url_destination( - "https://lightly.s3.eu-central-1.amazonaws.com/lightly/somewhere/image.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=0123456789%2F20220811%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20220811T065010Z&X-Amz-Expires=601200&X-Amz-Signature=0123456789&X-Amz-SignedHeaders=host&x-id=GetObject" - ), - DatasourceType.S3, - ) - self.assertNotEqual( - get_signed_url_destination("http://someething.with.s3.in.it"), - DatasourceType.S3, - ) - - # GCS - self.assertEqual( - get_signed_url_destination( - "https://storage.googleapis.com/lightly/somewhere/image.jpg?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=lightly%40appspot.gserviceaccount.com%2F20220811%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20220811T065325Z&X-Goog-Expires=601201&X-Goog-SignedHeaders=host&X-Goog-Signature=01234567890" - ), - DatasourceType.GCS, - ) - self.assertNotEqual( - get_signed_url_destination("http://someething.with.google.in.it"), - DatasourceType.GCS, - ) - - # AZURE - self.assertEqual( - get_signed_url_destination( - "https://lightly.blob.core.windows.net/lightly/somewhere/image.jpg?sv=2020-08-04&ss=bfqt&srt=sco&sp=0123456789&se=2022-04-13T20:20:02Z&st=2022-04-13T12:20:02Z&spr=https&sig=0123456789" - ), - DatasourceType.AZURE, - ) - self.assertNotEqual( - get_signed_url_destination("http://someething.with.windows.in.it"), - DatasourceType.AZURE, - ) - - def test_get_lightly_server_location_from_env(self): - os.environ["LIGHTLY_SERVER_LOCATION"] = "https://api.dev.lightly.ai/ " - host = get_lightly_server_location_from_env() - self.assertEqual(host, "https://api.dev.lightly.ai") - - def test_paginate_endpoint(self): - def some_function(page_size=8, page_offset=0): - if page_offset > 3 * page_size: - assert False # should not happen - elif page_offset > 2 * page_size: - return (page_size - 1) * ["a"] - else: - return page_size * ["a"] - - page_size = 8 - some_iterator = paginate_endpoint(some_function, page_size=page_size) - some_list = list(some_iterator) - self.assertEqual((4 * page_size - 1) * ["a"], some_list) - self.assertEqual(len(some_list), (4 * page_size - 1)) - - def test_paginate_endpoint__string(self): - def paginated_function(page_size=8, page_offset=0): - """Returns one page of size page_size, then one page of size page_size - 1.""" - if page_offset > 3 * page_size: - assert False # This should not happen. - elif page_offset > 2 * page_size: - return (page_size - 1) * "a" - else: - return page_size * "a" - - page_size = 8 - some_iterator = paginate_endpoint(paginated_function, page_size=page_size) - some_list = list(some_iterator) - self.assertEqual((4 * page_size - 1) * "a", "".join(some_list)) - self.assertEqual(len(some_list), 4) # Expect four pages of strings. - - def test_paginate_endpoint__multiple_of_page_size(self): - def paginated_function(page_size=8, page_offset=0): - """Returns two pages of size page_size, then an empty page.""" - if page_offset > 3 * page_size: - return [] - elif page_offset > 2 * page_size: - return page_size * ["a"] - else: - return page_size * ["a"] - - page_size = 8 - some_iterator = paginate_endpoint(paginated_function, page_size=page_size) - some_list = list(some_iterator) - self.assertEqual((4 * page_size) * ["a"], some_list) - self.assertEqual(len(some_list), (4 * page_size)) - - def test_paginate_endpoint_empty(self): - def some_function(page_size=8, page_offset=0): - return [] - - some_iterator = paginate_endpoint(some_function, page_size=8) - some_list = list(some_iterator) - self.assertEqual(some_list, []) diff --git a/tests/api/test_version_checking.py b/tests/api/test_version_checking.py deleted file mode 100644 index 5a72d8344..000000000 --- a/tests/api/test_version_checking.py +++ /dev/null @@ -1,87 +0,0 @@ -import os -import time - -import pytest -from pytest_mock import MockerFixture -from urllib3.exceptions import MaxRetryError - -from lightly.api import _version_checking -from lightly.openapi_generated.swagger_client.api import VersioningApi - - -# Overwrite the mock_versioning_api fixture from conftest.py that is applied by default -# for all tests as we want to test the functionality of the versioning api. -@pytest.fixture(autouse=True) -def mock_versioning_api(): - return - - -@pytest.mark.disable_mock_versioning_api -def test_is_latest_version(mocker: MockerFixture) -> None: - mocker.patch.object( - _version_checking.VersioningApi, "get_latest_pip_version", return_value="1.2.8" - ) - assert _version_checking.is_latest_version("1.2.8") - assert not _version_checking.is_latest_version("1.2.7") - assert not _version_checking.is_latest_version("1.1.8") - assert not _version_checking.is_latest_version("0.2.8") - - -def test_is_compatible_version(mocker: MockerFixture) -> None: - mocker.patch.object( - _version_checking.VersioningApi, - "get_minimum_compatible_pip_version", - return_value="1.2.8", - ) - assert _version_checking.is_compatible_version("1.2.8") - assert not _version_checking.is_compatible_version("1.2.7") - assert not _version_checking.is_compatible_version("1.1.8") - assert not _version_checking.is_compatible_version("0.2.8") - - -def test_get_latest_version(mocker: MockerFixture) -> None: - mocker.patch.object( - _version_checking.VersioningApi, "get_latest_pip_version", return_value="1.2.8" - ) - assert _version_checking.get_latest_version("1.2.8") == "1.2.8" - - -def test_get_latest_version__timeout(mocker: MockerFixture) -> None: - mocker.patch.dict(os.environ, {"LIGHTLY_SERVER_LOCATION": "invalid-url"}) - start = time.perf_counter() - with pytest.raises(MaxRetryError): - # Urllib3 raises a timeout error (connection refused) for invalid URLs. - _version_checking.get_latest_version("1.2.8", timeout_sec=0.1) - end = time.perf_counter() - assert end - start < 0.2 # Give some slack for timeout. - - -def test_get_minimum_compatible_version(mocker: MockerFixture) -> None: - mocker.patch.object( - _version_checking.VersioningApi, - "get_minimum_compatible_pip_version", - return_value="1.2.8", - ) - - assert _version_checking.get_minimum_compatible_version() == "1.2.8" - - -def test_get_minimum_compatible_version__timeout(mocker: MockerFixture) -> None: - mocker.patch.dict(os.environ, {"LIGHTLY_SERVER_LOCATION": "invalid-url"}) - start = time.perf_counter() - with pytest.raises(MaxRetryError): - # Urllib3 raises a timeout error (connection refused) for invalid URLs. - _version_checking.get_minimum_compatible_version(timeout_sec=0.1) - end = time.perf_counter() - assert end - start < 0.2 # Give some slack for timeout. - - -def test_check_is_latest_version_in_background(mocker: MockerFixture) -> None: - spy_is_latest_version = mocker.spy(_version_checking, "is_latest_version") - _version_checking.check_is_latest_version_in_background("1.2.8") - time.sleep(0.1) # Wait for thread to run. - spy_is_latest_version.assert_called_once_with(current_version="1.2.8") - - -def test__get_versioning_api() -> None: - assert isinstance(_version_checking._get_versioning_api(), VersioningApi) diff --git a/tests/api_workflow/__init__.py b/tests/api_workflow/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/api_workflow/mocked_api_workflow_client.py b/tests/api_workflow/mocked_api_workflow_client.py deleted file mode 100644 index ae36953fa..000000000 --- a/tests/api_workflow/mocked_api_workflow_client.py +++ /dev/null @@ -1,1114 +0,0 @@ -import csv -import io -import json -import tempfile -import unittest -from collections import defaultdict -from io import IOBase -from typing import * - -import numpy as np -import requests -from requests import Response - -import lightly -from lightly.api.api_workflow_client import ApiWorkflowClient -from lightly.openapi_generated.swagger_client.api import ( - CollaborationApi, - DatasetsApi, - DatasourcesApi, - DockerApi, - EmbeddingsApi, - JobsApi, - MappingsApi, - QuotaApi, - SamplesApi, - SamplingsApi, - ScoresApi, - TagsApi, - VersioningApi, -) -from lightly.openapi_generated.swagger_client.models import ( - AsyncTaskData, - CreateDockerWorkerRegistryEntryRequest, - CreateEntityResponse, - DatasetCreateRequest, - DatasetData, - DatasetEmbeddingData, - DatasourceConfig, - DatasourceConfigAzure, - DatasourceConfigBase, - DatasourceConfigLOCAL, - DatasourceProcessedUntilTimestampRequest, - DatasourceProcessedUntilTimestampResponse, - DatasourceRawSamplesData, - DatasourceRawSamplesDataRow, - DatasourceRawSamplesMetadataData, - DatasourceRawSamplesPredictionsData, - DockerRunData, - DockerRunScheduledCreateRequest, - DockerRunScheduledData, - DockerRunScheduledPriority, - DockerRunScheduledState, - DockerRunState, - DockerWorkerConfigCreateRequest, - DockerWorkerConfigOmniVXCreateRequest, - DockerWorkerConfigV3CreateRequest, - DockerWorkerRegistryEntryData, - DockerWorkerState, - DockerWorkerType, - FilenameAndReadUrl, - InitialTagCreateRequest, - JobResultType, - JobState, - JobStatusData, - JobStatusDataResult, - LabelBoxDataRow, - LabelBoxV4DataRow, - LabelStudioTask, - LabelStudioTaskData, - SampleCreateRequest, - SampleData, - SampleDataModes, - SampleMetaData, - SamplePartialMode, - SampleUpdateRequest, - SampleWriteUrls, - SamplingCreateRequest, - SharedAccessConfigCreateRequest, - SharedAccessConfigData, - SharedAccessType, - TagArithmeticsRequest, - TagBitMaskResponse, - TagCreator, - TagData, - Trigger2dEmbeddingJobRequest, - WriteCSVUrlData, -) -from lightly.openapi_generated.swagger_client.rest import ApiException -from tests.api_workflow import utils - - -def _check_dataset_id(dataset_id: str): - if not isinstance(dataset_id, str) or len(dataset_id) == 0: - raise ApiException(status=400, reason="Invalid dataset id.") - - -N_FILES_ON_SERVER = 100 - - -class MockedEmbeddingsApi(EmbeddingsApi): - def __init__(self, api_client): - EmbeddingsApi.__init__(self, api_client=api_client) - self.embeddings = [ - DatasetEmbeddingData( - id=utils.generate_id(), - name="embedding_newest", - is_processed=True, - created_at=1111111, - ), - DatasetEmbeddingData( - id=utils.generate_id(), - name="default", - is_processed=True, - created_at=0, - ), - ] - - def get_embeddings_csv_write_url_by_id(self, dataset_id: str, **kwargs): - _check_dataset_id(dataset_id) - assert isinstance(dataset_id, str) - response_ = WriteCSVUrlData( - signed_write_url="signed_write_url_valid", embedding_id=utils.generate_id() - ) - return response_ - - def get_embeddings_by_dataset_id( - self, dataset_id, **kwargs - ) -> List[DatasetEmbeddingData]: - _check_dataset_id(dataset_id) - assert isinstance(dataset_id, str) - return self.embeddings - - def trigger2d_embeddings_job( - self, trigger2d_embedding_job_request, dataset_id, embedding_id, **kwargs - ): - _check_dataset_id(dataset_id) - assert isinstance(trigger2d_embedding_job_request, Trigger2dEmbeddingJobRequest) - - def get_embeddings_csv_read_url_by_id(self, dataset_id, embedding_id, **kwargs): - _check_dataset_id(dataset_id) - return "https://my-embedding-read-url.com" - - -class MockedSamplingsApi(SamplingsApi): - def trigger_sampling_by_id( - self, body: SamplingCreateRequest, dataset_id, embedding_id, **kwargs - ): - _check_dataset_id(dataset_id) - assert isinstance(body, SamplingCreateRequest) - assert isinstance(dataset_id, str) - assert isinstance(embedding_id, str) - response_ = AsyncTaskData(job_id="155") - return response_ - - -class MockedJobsApi(JobsApi): - def __init__(self, *args, **kwargs): - self.no_calls = 0 - JobsApi.__init__(self, *args, **kwargs) - - def get_job_status_by_id(self, job_id, **kwargs): - assert isinstance(job_id, str) - self.no_calls += 1 - if self.no_calls > 3: - result = JobStatusDataResult( - type=JobResultType.SAMPLING, data="selection_tag_id_xyz" - ) - response_ = JobStatusData( - id="id_", - status=JobState.FINISHED, - wait_time_till_next_poll=0, - created_at=1234, - finished_at=1357, - result=result, - ) - else: - result = None - response_ = JobStatusData( - id="id_", - status=JobState.RUNNING, - wait_time_till_next_poll=0.001, - created_at=1234, - result=result, - ) - return response_ - - -class MockedTagsApi(TagsApi): - def create_initial_tag_by_dataset_id( - self, initial_tag_create_request, dataset_id, **kwargs - ): - _check_dataset_id(dataset_id) - assert isinstance(initial_tag_create_request, InitialTagCreateRequest) - assert isinstance(dataset_id, str) - response_ = CreateEntityResponse(id=utils.generate_id()) - return response_ - - def get_tag_by_tag_id(self, dataset_id, tag_id, **kwargs): - _check_dataset_id(dataset_id) - assert isinstance(dataset_id, str) - assert isinstance(tag_id, str) - response_ = TagData( - id=tag_id, - dataset_id=dataset_id, - prev_tag_id=utils.generate_id(), - bit_mask_data="0x80bda23e9", - name="second-tag", - tot_size=15, - created_at=1577836800, - changes=[], - ) - return response_ - - def get_tags_by_dataset_id(self, dataset_id, **kwargs): - _check_dataset_id(dataset_id) - - tag_1 = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0xf", - name="initial-tag", - tot_size=4, - created_at=1577836800, - changes=[], - ) - tag_2 = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=tag_1.id, - bit_mask_data="0xf", - name="query_tag_name_xyz", - tot_size=4, - created_at=1577836800, - changes=[], - ) - tag_3 = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=tag_1.id, - bit_mask_data="0x1", - name="preselected_tag_name_xyz", - tot_size=4, - created_at=1577836800, - changes=[], - ) - tag_4 = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=tag_3.id, - bit_mask_data="0x3", - name="selected_tag_xyz", - tot_size=4, - created_at=1577836800, - changes=[], - ) - tag_5 = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name="1000", - tot_size=4, - created_at=1577836800, - changes=[], - ) - tags = [tag_1, tag_2, tag_3, tag_4, tag_5] - no_tags_to_return = getattr(self, "no_tags", 5) - tags = tags[:no_tags_to_return] - return tags - - def perform_tag_arithmetics( - self, tag_arithmetics_request: TagArithmeticsRequest, dataset_id, **kwargs - ): - _check_dataset_id(dataset_id) - if (tag_arithmetics_request.new_tag_name is None) or ( - tag_arithmetics_request.new_tag_name == "" - ): - return TagBitMaskResponse(bit_mask_data="0x2") - else: - return CreateEntityResponse(id="tag-arithmetic-created") - - def perform_tag_arithmetics_bitmask( - self, tag_arithmetics_request: TagArithmeticsRequest, dataset_id, **kwargs - ): - _check_dataset_id(dataset_id) - return TagBitMaskResponse(bit_mask_data="0x2") - - def upsize_tags_by_dataset_id(self, tag_upsize_request, dataset_id, **kwargs): - _check_dataset_id(dataset_id) - assert tag_upsize_request.upsize_tag_creator in ( - TagCreator.USER_PIP, - TagCreator.USER_PIP_LIGHTLY_MAGIC, - ) - - def create_tag_by_dataset_id( - self, tag_create_request, dataset_id, **kwargs - ) -> TagData: - _check_dataset_id(dataset_id) - tag = TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=tag_create_request["prev_tag_id"], - bit_mask_data=tag_create_request["bit_mask_data"], - name=tag_create_request["name"], - tot_size=10, - created_at=1577836800, - changes=[], - ) - return tag - - def delete_tag_by_tag_id(self, dataset_id, tag_id, **kwargs): - _check_dataset_id(dataset_id) - tags = self.get_tags_by_dataset_id(dataset_id) - # assert that tag exists - assert any([tag.id == tag_id for tag in tags]) - # assert that tag is a leaf - assert all([tag.prev_tag_id != tag_id for tag in tags]) - - def export_tag_to_label_studio_tasks( - self, dataset_id: str, tag_id: str, **kwargs - ) -> List[Dict]: - if kwargs["page_offset"] and kwargs["page_offset"] > 0: - return [] - return [ - LabelStudioTask( - id=0, - data=LabelStudioTaskData( - image="https://api.lightly.ai/v1/datasets/62383ab8f9cb290cd83ab5f9/samples/62383cb7e6a0f29e3f31e213/readurlRedirect?type=full&CENSORED", - lightly_file_name="2008_006249_jpg.rf.fdd64460945ca901aa3c7e48ffceea83.jpg", - lightly_meta_info=SampleData( - id="sample_id_0", - type="IMAGE", - dataset_id=dataset_id, - file_name="2008_006249_jpg.rf.fdd64460945ca901aa3c7e48ffceea83.jpg", - exif={}, - index=0, - created_at=1647852727873, - last_modified_at=1647852727873, - meta_data=SampleMetaData( - sharpness=27.31265790443818, - size_in_bytes=48224, - snr=2.1969673926211217, - mean=[ - 0.24441662557257224, - 0.4460417517905863, - 0.6960984853824035, - ], - shape=[167, 500, 3], - std=[ - 0.12448681278605961, - 0.09509570033043004, - 0.0763725998175394, - ], - sum_of_squares=[ - 6282.243860049413, - 17367.702452895475, - 40947.22059208768, - ], - sum_of_values=[ - 20408.78823530978, - 37244.486274513954, - 58124.22352943069, - ], - ), - ), - ), - ).to_dict() # temporary until we have a proper openapi generator - ] - - def export_tag_to_label_box_data_rows( - self, dataset_id: str, tag_id: str, **kwargs - ) -> List[Dict]: - if kwargs["page_offset"] and kwargs["page_offset"] > 0: - return [] - return [ - LabelBoxDataRow( - external_id="2008_007291_jpg.rf.2fca436925b52ea33cf897125a34a2fb.jpg", - image_url="https://api.lightly.ai/v1/datasets/62383ab8f9cb290cd83ab5f9/samples/62383cb7e6a0f29e3f31e233/readurlRedirect?type=CENSORED", - ).to_dict() # temporary until we have a proper openapi generator - ] - - def export_tag_to_label_box_v4_data_rows( - self, dataset_id: str, tag_id: str, **kwargs - ) -> List[Dict]: - if kwargs["page_offset"] and kwargs["page_offset"] > 0: - return [] - return [ - LabelBoxV4DataRow( - row_data="http://localhost:5000/v1/datasets/6401d4534d2ed9112da782f5/samples/6401e455a6045a7faa79b20a/readurlRedirect?type=full&publicToken=token", - global_key="image.png", - media_type="IMAGE", - ).to_dict() # temporary until we have a proper openapi generator - ] - - def export_tag_to_basic_filenames_and_read_urls( - self, dataset_id: str, tag_id: str, **kwargs - ) -> List[Dict]: - if kwargs["page_offset"] and kwargs["page_offset"] > 0: - return [] - return [ - FilenameAndReadUrl( - file_name="export-basic-test-sample-0.png", - read_url="https://storage.googleapis.com/somwhere/export-basic-test-sample-0.png?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=CENSORED", - ).to_dict() # temporary until we have a proper openapi generator - ] - - def export_tag_to_basic_filenames( - self, dataset_id: str, tag_id: str, **kwargs - ) -> str: - if kwargs["page_offset"] and kwargs["page_offset"] > 0: - return "" - return """ -IMG_2276_jpeg_jpg.rf.7411b1902c81bad8cdefd2cc4eb3a97b.jpg -IMG_2285_jpeg_jpg.rf.4a93d99b9f0b6cccfb27bf2f4a13b99e.jpg -IMG_2274_jpeg_jpg.rf.2f319e949748145fb22dcb52bb325a0c.jpg - """ - - -class MockedScoresApi(ScoresApi): - def create_or_update_active_learning_score_by_tag_id( - self, body, dataset_id, tag_id, **kwargs - ) -> CreateEntityResponse: - _check_dataset_id(dataset_id) - if len(body.scores) > 0 and not isinstance(body.scores[0], float): - raise AttributeError - response_ = CreateEntityResponse(id="selected_tag_id_xyz") - return response_ - - -class MockedMappingsApi(MappingsApi): - def __init__(self, samples_api, *args, **kwargs): - self._samples_api = samples_api - MappingsApi.__init__(self, *args, **kwargs) - - self.n_samples = N_FILES_ON_SERVER - sample_names = [f"img_{i}.jpg" for i in range(self.n_samples)] - sample_names.reverse() - self.sample_names = sample_names - - def get_sample_mappings_by_dataset_id(self, dataset_id, field, **kwargs): - if dataset_id == "xyz-no-tags": - return [] - return self.sample_names[: self.n_samples] - - -class MockedSamplesApi(SamplesApi): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.sample_create_requests: List[SampleCreateRequest] = [] - - def get_samples_by_dataset_id(self, dataset_id, **kwargs) -> List[SampleData]: - samples = [] - for i, body in enumerate(self.sample_create_requests): - sample = SampleData( - id=f"{i}_xyz", - dataset_id="dataset_id_xyz", - file_name=body.file_name, - type="Images", - ) - samples.append(sample) - return samples - - def get_samples_partial_by_dataset_id( - self, - dataset_id="dataset_id_xyz", - mode: SamplePartialMode = SamplePartialMode.FULL, - **kwargs, - ) -> List[SampleData]: - samples = [] - for i, body in enumerate(self.sample_create_requests): - if mode == SamplePartialMode.IDS: - sample = SampleDataModes(id=f"{i}_xyz") - elif mode == SamplePartialMode.FILENAMES: - sample = SampleDataModes( - id=f"{i}_xyz", - file_name=body.file_name, - ) - else: - sample = SampleDataModes( - id=f"{i}_xyz", - dataset_id=dataset_id, - file_name=body.file_name, - type="Images", - ) - samples.append(sample) - return samples - - def create_sample_by_dataset_id(self, body, dataset_id, **kwargs): - _check_dataset_id(dataset_id) - assert isinstance(body, SampleCreateRequest) - response_ = CreateEntityResponse(id="xyz") - self.sample_create_requests.append(body) - return response_ - - def get_sample_image_write_url_by_id( - self, dataset_id, sample_id, is_thumbnail, **kwargs - ): - _check_dataset_id(dataset_id) - url = f"{sample_id}_write_url" - return url - - def get_sample_image_read_url_by_id(self, dataset_id, sample_id, type, **kwargs): - _check_dataset_id(dataset_id) - url = f"{sample_id}_write_url" - return url - - def get_sample_image_write_urls_by_id( - self, dataset_id, sample_id, **kwargs - ) -> SampleWriteUrls: - _check_dataset_id(dataset_id) - thumb_url = f"{sample_id}_thumb_write_url" - full_url = f"{sample_id}_full_write_url" - ret = SampleWriteUrls(full=full_url, thumb=thumb_url) - return ret - - def update_sample_by_id(self, body, dataset_id, sample_id, **kwargs): - _check_dataset_id(dataset_id) - assert isinstance(body, SampleUpdateRequest) - - -class MockedDatasetsApi(DatasetsApi): - def __init__(self, api_client): - no_datasets = 3 - self._default_datasets = [ - DatasetData( - name=f"dataset_{i}", - id=utils.generate_id(), - last_modified_at=i, - type="Images", - img_type="full", - size_in_bytes=-1, - n_samples=-1, - created_at=0, - user_id="user_0", - ) - for i in range(no_datasets) - ] - self._shared_datasets = [ - DatasetData( - name=f"shared_dataset_{i}", - id=utils.generate_id(), - last_modified_at=0, - type="Images", - img_type="full", - size_in_bytes=-1, - n_samples=-1, - created_at=0, - user_id="another_user", - ) - for i in range(2) - ] - self.reset() - - @property - def _all_datasets(self) -> List[DatasetData]: - return [*self.datasets, *self.shared_datasets] - - def reset(self): - self.datasets = self._default_datasets - self.shared_datasets = self._shared_datasets - - def get_datasets( - self, - shared: bool = False, - get_assets_of_team: bool = False, - page_size: Optional[int] = None, - page_offset: Optional[int] = None, - ): - start, end = _start_and_end_offset(page_size=page_size, page_offset=page_offset) - if get_assets_of_team: - return [] - if shared: - return self.shared_datasets[start:end] - else: - return self.datasets[start:end] - - def create_dataset(self, dataset_create_request: DatasetCreateRequest, **kwargs): - assert isinstance(dataset_create_request, DatasetCreateRequest) - id = utils.generate_id() - if dataset_create_request.name == "xyz-no-tags": - id = "xyz-no-tags" - dataset = DatasetData( - id=id, - name=dataset_create_request.name, - last_modified_at=len(self.datasets) + 1, - type="Images", - size_in_bytes=-1, - n_samples=-1, - created_at=-1, - user_id=utils.generate_id(), - ) - self.datasets.append(dataset) - response_ = CreateEntityResponse(id=id) - return response_ - - def get_dataset_by_id(self, dataset_id): - _check_dataset_id(dataset_id) - dataset = next( - (dataset for dataset in self._all_datasets if dataset_id == dataset.id), - None, - ) - if dataset is None: - raise ApiException(status=404, reason="Not found") - return dataset - - def register_dataset_upload_by_id(self, body, dataset_id): - _check_dataset_id(dataset_id) - return True - - def delete_dataset_by_id(self, dataset_id, **kwargs) -> None: - _check_dataset_id(dataset_id) - datasets_without_that_id = [ - dataset for dataset in self.datasets if dataset.id != dataset_id - ] - assert len(datasets_without_that_id) == len(self.datasets) - 1 - self.datasets = datasets_without_that_id - - def get_children_of_dataset_id(self, dataset_id, **kwargs): - raise NotImplementedError() - - def get_datasets_enriched(self, **kwargs): - raise NotImplementedError() - - def get_datasets_query_by_name( - self, - dataset_name: str, - page_size: Optional[int] = None, - page_offset: Optional[int] = None, - shared: bool = False, - exact: bool = False, - get_assets_of_team: bool = False, - ) -> List[DatasetData]: - datasets = self.get_datasets( - shared=shared, - get_assets_of_team=get_assets_of_team, - page_size=page_size, - page_offset=page_offset, - ) - if exact: - return [dataset for dataset in datasets if dataset.name == dataset_name] - else: - return [ - dataset - for dataset in datasets - if dataset.name is not None and dataset.name.startswith(dataset_name) - ] - - def update_dataset_by_id(self, body, dataset_id, **kwargs): - raise NotImplementedError() - - -class MockedDatasourcesApi(DatasourcesApi): - def __init__(self, api_client=None): - super().__init__(api_client=api_client) - # maximum numbers of samples returned by list raw samples request - self._max_return_samples = 2 - # default number of samples in every datasource - self._num_samples = 5 - self.reset() - - def reset(self): - local_datasource = DatasourceConfigLOCAL( - type="LOCAL", - full_path="", - web_server_location="https://localhost:1234", - purpose="INPUT_OUTPUT", - ).to_dict() - azure_datasource = DatasourceConfigBase( - type="AZURE", purpose="INPUT_OUTPUT" - ).to_dict() - - self._datasources = { - "dataset_id_xyz": local_datasource, - "dataset_0": azure_datasource, - } - self._processed_until_timestamp = defaultdict(lambda: 0) - self._samples = defaultdict(self._default_samples) - - def _default_samples(self): - return [ - DatasourceRawSamplesDataRow(file_name=f"file_{i}", read_url=f"url_{i}") - for i in range(self._num_samples) - ] - - def get_datasource_by_dataset_id(self, dataset_id: str, **kwargs): - try: - datasource = self._datasources[dataset_id] - return datasource - except Exception: - raise ApiException() - - def get_datasource_processed_until_timestamp_by_dataset_id( - self, dataset_id: str, **kwargs - ) -> DatasourceProcessedUntilTimestampResponse: - timestamp = self._processed_until_timestamp[dataset_id] - return DatasourceProcessedUntilTimestampResponse(timestamp) - - def get_list_of_raw_samples_from_datasource_by_dataset_id( - self, - dataset_id, - cursor: str = None, - _from: int = None, - to: int = None, - relevant_filenames_file_name: str = -1, - use_redirected_read_url: bool = False, - **kwargs, - ) -> DatasourceRawSamplesData: - if relevant_filenames_file_name == -1: - samples = self._samples[dataset_id] - elif ( - isinstance(relevant_filenames_file_name, str) - and len(relevant_filenames_file_name) > 0 - ): - samples = self._samples[dataset_id][::2] - else: - raise RuntimeError("DATASET_DATASOURCE_RELEVANT_FILENAMES_INVALID") - - if cursor is None: - # initial request - assert _from is not None - assert to is not None - cursor_dict = {"from": _from, "to": to} - current = _from - else: - # follow up request - cursor_dict = json.loads(cursor) - current = cursor_dict["current"] - to = cursor_dict["to"] - - next_current = min(current + self._max_return_samples, to + 1) - samples = samples[current:next_current] - cursor_dict["current"] = next_current - cursor = json.dumps(cursor_dict) - has_more = len(samples) > 0 - - return DatasourceRawSamplesData( - has_more=has_more, - cursor=cursor, - data=samples, - ) - - def get_list_of_raw_samples_predictions_from_datasource_by_dataset_id( - self, - dataset_id: str, - task_name: str, - cursor: str = None, - _from: int = None, - to: int = None, - use_redirected_read_url: bool = False, - **kwargs, - ) -> DatasourceRawSamplesPredictionsData: - if cursor is None: - # initial request - assert _from is not None - assert to is not None - cursor_dict = {"from": _from, "to": to} - current = _from - else: - # follow up request - cursor_dict = json.loads(cursor) - current = cursor_dict["current"] - to = cursor_dict["to"] - - next_current = min(current + self._max_return_samples, to + 1) - samples = self._samples[dataset_id][current:next_current] - cursor_dict["current"] = next_current - cursor = json.dumps(cursor_dict) - has_more = len(samples) > 0 - - return DatasourceRawSamplesPredictionsData( - has_more=has_more, - cursor=cursor, - data=samples, - ) - - def get_list_of_raw_samples_metadata_from_datasource_by_dataset_id( - self, - dataset_id: str, - cursor: str = None, - _from: int = None, - to: int = None, - use_redirected_read_url: bool = False, - **kwargs, - ) -> DatasourceRawSamplesMetadataData: - if cursor is None: - # initial request - assert _from is not None - assert to is not None - cursor_dict = {"from": _from, "to": to} - current = _from - else: - # follow up request - cursor_dict = json.loads(cursor) - current = cursor_dict["current"] - to = cursor_dict["to"] - - next_current = min(current + self._max_return_samples, to + 1) - samples = self._samples[dataset_id][current:next_current] - cursor_dict["current"] = next_current - cursor = json.dumps(cursor_dict) - has_more = len(samples) > 0 - - return DatasourceRawSamplesMetadataData( - has_more=has_more, - cursor=cursor, - data=samples, - ) - - def get_prediction_file_read_url_from_datasource_by_dataset_id( - self, *args, **kwargs - ): - return "https://my-read-url.com" - - def update_datasource_by_dataset_id( - self, body: DatasourceConfig, dataset_id: str, **kwargs - ) -> None: - # TODO: Enable assert once we switch/update to new api code generator. - # assert isinstance(body, DatasourceConfig) - self._datasources[dataset_id] = body # type: ignore - - def update_datasource_processed_until_timestamp_by_dataset_id( - self, body, dataset_id, **kwargs - ) -> None: - assert isinstance(body, DatasourceProcessedUntilTimestampRequest) - to = body.processed_until_timestamp - self._processed_until_timestamp[dataset_id] = to # type: ignore - - -class MockedComputeWorkerApi(DockerApi): - def __init__(self, api_client=None): - super().__init__(api_client=api_client) - self._compute_worker_runs = [ - DockerRunData( - id=utils.generate_id(), - user_id="user-id", - docker_version="v1", - dataset_id=utils.generate_id(), - state=DockerRunState.TRAINING, - created_at=0, - last_modified_at=100, - message=None, - artifacts=[], - ) - ] - self._scheduled_compute_worker_runs = [ - DockerRunScheduledData( - id=utils.generate_id(), - dataset_id=utils.generate_id(), - config_id=utils.generate_id(), - priority=DockerRunScheduledPriority.MID, - state=DockerRunScheduledState.OPEN, - created_at=0, - last_modified_at=100, - owner=utils.generate_id(), - runs_on=[], - ) - ] - self._registered_workers = [ - DockerWorkerRegistryEntryData( - id=utils.generate_id(), - user_id="user-id", - name="worker-name-1", - worker_type=DockerWorkerType.FULL, - state=DockerWorkerState.OFFLINE, - created_at=0, - last_modified_at=0, - labels=["label-1"], - ) - ] - - def register_docker_worker(self, body, **kwargs): - assert isinstance(body, CreateDockerWorkerRegistryEntryRequest) - return CreateEntityResponse(id=utils.generate_id()) - - def get_docker_worker_registry_entries(self, **kwargs): - return self._registered_workers - - def create_docker_worker_config(self, body, **kwargs): - assert isinstance(body, DockerWorkerConfigCreateRequest) - return CreateEntityResponse(id=utils.generate_id()) - - def create_docker_worker_config_v3(self, body, **kwargs): - assert isinstance(body, DockerWorkerConfigV3CreateRequest) - return CreateEntityResponse(id=utils.generate_id()) - - def create_docker_worker_config_vx(self, body, **kwargs): - assert isinstance(body, DockerWorkerConfigOmniVXCreateRequest) - return CreateEntityResponse(id=utils.generate_id()) - - def create_docker_run_scheduled_by_dataset_id( - self, docker_run_scheduled_create_request, dataset_id, **kwargs - ): - assert isinstance( - docker_run_scheduled_create_request, DockerRunScheduledCreateRequest - ) - _check_dataset_id(dataset_id) - return CreateEntityResponse(id=utils.generate_id()) - - def get_docker_runs( - self, - page_size: Optional[int] = None, - page_offset: Optional[int] = None, - **kwargs, - ): - start, end = _start_and_end_offset(page_size=page_size, page_offset=page_offset) - return self._compute_worker_runs[start:end] - - def get_docker_runs_count(self, **kwargs): - return len(self._compute_worker_runs) - - def get_docker_runs_scheduled_by_dataset_id( - self, dataset_id, state: Optional[str] = None, **kwargs - ): - runs = self._scheduled_compute_worker_runs - runs = [run for run in runs if run.dataset_id == dataset_id] - return runs - - def cancel_scheduled_docker_run_state_by_id( - self, dataset_id: str, scheduled_id: str, **kwargs - ): - raise NotImplementedError() - - def confirm_docker_run_artifact_creation( - self, run_id: str, artifact_id: str, **kwargs - ): - raise NotImplementedError() - - def create_docker_run(self, body, **kwargs): - raise NotImplementedError() - - def create_docker_run_artifact(self, body, run_id, **kwargs): - raise NotImplementedError() - - def get_docker_license_information(self, **kwargs): - raise NotImplementedError() - - def get_docker_run_artifact_read_url_by_id(self, run_id, artifact_id, **kwargs): - raise NotImplementedError() - - def get_docker_run_by_id(self, run_id, **kwargs): - raise NotImplementedError() - - def get_docker_run_by_scheduled_id(self, scheduled_id, **kwargs): - raise NotImplementedError() - - def get_docker_run_logs_by_id(self, run_id, **kwargs): - raise NotImplementedError() - - def get_docker_run_report_read_url_by_id(self, run_id, **kwargs): - raise NotImplementedError() - - def get_docker_run_report_write_url_by_id(self, run_id, **kwargs): - raise NotImplementedError() - - def get_docker_runs_scheduled_by_state_and_labels(self, **kwargs): - raise NotImplementedError() - - def get_docker_runs_scheduled_by_worker_id(self, worker_id, **kwargs): - raise NotImplementedError() - - def get_docker_worker_config_by_id(self, config_id, **kwargs): - raise NotImplementedError() - - def get_docker_worker_configs(self, **kwargs): - raise NotImplementedError() - - def get_docker_worker_registry_entry_by_id(self, worker_id, **kwargs): - raise NotImplementedError() - - def post_docker_authorization_request(self, body, **kwargs): - raise NotImplementedError() - - def post_docker_usage_stats(self, body, **kwargs): - raise NotImplementedError() - - def post_docker_worker_authorization_request(self, body, **kwargs): - raise NotImplementedError() - - def update_docker_run_by_id(self, body, run_id, **kwargs): - raise NotImplementedError() - - def update_docker_worker_config_by_id(self, body, config_id, **kwargs): - raise NotImplementedError() - - def update_docker_worker_registry_entry_by_id(self, body, worker_id, **kwargs): - raise NotImplementedError() - - def update_scheduled_docker_run_state_by_id( - self, body, dataset_id, worker_id, scheduled_id, **kwargs - ): - raise NotImplementedError() - - -class MockedQuotaApi(QuotaApi): - def get_quota_maximum_dataset_size(self, **kwargs): - return "60000" - - -def mocked_request_put(dst_url: str, data=IOBase) -> Response: - assert isinstance(dst_url, str) - content_bytes: bytes = data.read() - content_str: str = content_bytes.decode("utf-8") - assert content_str.startswith("filenames") - response_ = Response() - response_.status_code = 200 - return response_ - - -class MockedAPICollaboration(CollaborationApi): - def create_or_update_shared_access_config_by_dataset_id( - self, shared_access_config_create_request, dataset_id, **kwargs - ): - assert isinstance( - shared_access_config_create_request, SharedAccessConfigCreateRequest - ) - return CreateEntityResponse(id=utils.generate_id()) - - def get_shared_access_configs_by_dataset_id(self, dataset_id, **kwargs): - write_config = SharedAccessConfigData( - id=utils.generate_id(), - owner="owner-id", - users=["user1@gmail.com", "user2@something.com"], - teams=["some-id"], - created_at=0, - last_modified_at=0, - access_type=SharedAccessType.WRITE, - ) - return [write_config] - - -class MockedApiWorkflowClient(ApiWorkflowClient): - embeddings_filename_base = "img" - n_embedding_rows_on_server = N_FILES_ON_SERVER - - def __init__(self, *args, **kwargs): - ApiWorkflowClient.__init__(self, *args, **kwargs) - - self._selection_api = MockedSamplingsApi(api_client=self.api_client) - self._jobs_api = MockedJobsApi(api_client=self.api_client) - self._tags_api = MockedTagsApi(api_client=self.api_client) - self._embeddings_api = MockedEmbeddingsApi(api_client=self.api_client) - self._samples_api = MockedSamplesApi(api_client=self.api_client) - self._mappings_api = MockedMappingsApi( - api_client=self.api_client, samples_api=self._samples_api - ) - self._scores_api = MockedScoresApi(api_client=self.api_client) - self._datasets_api = MockedDatasetsApi(api_client=self.api_client) - self._datasources_api = MockedDatasourcesApi(api_client=self.api_client) - self._quota_api = MockedQuotaApi(api_client=self.api_client) - self._compute_worker_api = MockedComputeWorkerApi(api_client=self.api_client) - self._collaboration_api = MockedAPICollaboration(api_client=self.api_client) - - lightly.api.api_workflow_client.requests.put = mocked_request_put - - self.wait_time_till_next_poll = 0.001 # for api_workflow_selection - - def upload_file_with_signed_url( - self, - file: IOBase, - signed_write_url: str, - max_backoff: int = 32, - max_retries: int = 5, - headers: Dict = None, - session: Optional[requests.Session] = None, - ) -> Response: - res = Response() - return res - - def _get_csv_reader_from_read_url(self, read_url: str): - n_rows: int = self.n_embedding_rows_on_server - n_dims: int = self.n_dims_embeddings_on_server - - rows_csv = [ - ["filenames"] + [f"embedding_{i}" for i in range(n_dims)] + ["labels"] - ] - for i in range(n_rows): - row = [f"{self.embeddings_filename_base}_{i}.jpg"] - for _ in range(n_dims): - row.append(np.random.uniform(0, 1)) - row.append(i) - rows_csv.append(row) - - # save the csv rows in a temporary in-memory string file - # using a csv writer and then read them as bytes - f = tempfile.SpooledTemporaryFile(mode="rw") - writer = csv.writer(f) - writer.writerows(rows_csv) - f.seek(0) - buffer = io.StringIO(f.read()) - reader = csv.reader(buffer) - - return reader - - -class MockedApiWorkflowSetup(unittest.TestCase): - EMBEDDINGS_FILENAME_BASE: str = "sample" - - def setUp(self, token="token_xyz", dataset_id="dataset_id_xyz") -> None: - self.api_workflow_client = MockedApiWorkflowClient( - token=token, dataset_id=dataset_id - ) - - -def _start_and_end_offset( - page_size: Optional[int], - page_offset: Optional[int], -) -> Union[Tuple[int, int], Tuple[None, None]]: - if page_size is None and page_offset is None: - return None, None - elif page_size is not None and page_offset is not None: - return page_offset, page_offset + page_size - else: - assert False, "page_size and page_offset must either both be None or both set" diff --git a/tests/api_workflow/test_api_workflow.py b/tests/api_workflow/test_api_workflow.py deleted file mode 100644 index 1f5d3fac9..000000000 --- a/tests/api_workflow/test_api_workflow.py +++ /dev/null @@ -1,120 +0,0 @@ -import os -from unittest import mock - -import numpy as np - -import lightly -from tests.api_workflow import utils -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestApiWorkflow(MockedApiWorkflowSetup): - def setUp(self) -> None: - lightly.api.api_workflow_client.__version__ = lightly.__version__ - self.api_workflow_client = MockedApiWorkflowClient(token="token_xyz") - - @mock.patch.dict(os.environ, {"LIGHTLY_TOKEN": "token_xyz"}) - def test_init_with_env_token(self): - MockedApiWorkflowClient() - - def test_error_if_init_without_token(self): - # copy environment variables but remove LIGHTLY_TOKEN if it exists - env_without_token = { - k: v for k, v in os.environ.items() if k != "LIGHTLY_TOKEN" - } - with self.assertRaises(ValueError), mock.patch.dict( - os.environ, env_without_token, clear=True - ): - MockedApiWorkflowClient() - - def test_error_if_version_is_incompatible(self): - lightly.api.api_workflow_client.__version__ = "0.0.0" - with self.assertWarns(UserWarning): - MockedApiWorkflowClient(token="token_xyz") - lightly.api.api_workflow_client.__version__ = lightly.__version__ - - def test_dataset_id_nonexisting(self): - self.api_workflow_client._datasets_api.reset() - assert not hasattr(self.api_workflow_client, "_dataset_id") - with self.assertWarns(UserWarning): - dataset_id = self.api_workflow_client.dataset_id - assert dataset_id == self.api_workflow_client._datasets_api.datasets[-1].id - - def test_dataset_id_existing(self): - id = utils.generate_id() - self.api_workflow_client._dataset_id = id - assert self.api_workflow_client.dataset_id == id - - def test_set_dataset_id_existing(self): - datasets = self.api_workflow_client.get_all_datasets() - self.api_workflow_client.dataset_id = datasets[1].id - - def test_set_dataset_id_missing(self): - with self.assertRaises(ValueError): - self.api_workflow_client.dataset_id = "nonexisting-id" - - def test_reorder_random(self): - no_random_tries = 100 - for iter in range(no_random_tries): - numbers_to_choose_from = list(range(100)) - numbers_all = list(np.random.choice(numbers_to_choose_from, 100)) - filenames_on_server = [f"img_{i}" for i in numbers_all] - - api_workflow_client = MockedApiWorkflowClient( - token="token_xyz", dataset_id="dataset_id_xyz" - ) - api_workflow_client._mappings_api.sample_names = filenames_on_server - - numbers_in_tag = np.copy(numbers_all) - np.random.shuffle(numbers_in_tag) - filenames_for_list = [f"img_{i}" for i in numbers_in_tag] - - list_ordered = api_workflow_client._order_list_by_filenames( - filenames_for_list, list_to_order=numbers_in_tag - ) - list_desired_order = [i for i in numbers_all if i in numbers_in_tag] - assert list_ordered == list_desired_order - - def test_reorder_manual(self): - filenames_on_server = ["a", "b", "c"] - api_workflow_client = MockedApiWorkflowClient( - token="token_xyz", dataset_id="dataset_id_xyz" - ) - api_workflow_client._mappings_api.sample_names = filenames_on_server - filenames_for_list = ["c", "a", "b"] - list_to_order = ["cccc", "aaaa", "bbbb"] - list_ordered = api_workflow_client._order_list_by_filenames( - filenames_for_list, list_to_order=list_to_order - ) - list_desired_order = ["aaaa", "bbbb", "cccc"] - assert list_ordered == list_desired_order - - def test_reorder_wrong_lengths(self): - filenames_on_server = ["a", "b", "c"] - api_workflow_client = MockedApiWorkflowClient( - token="token_xyz", dataset_id="dataset_id_xyz" - ) - api_workflow_client._mappings_api.sample_names = filenames_on_server - filenames_for_list = ["c", "a", "b"] - list_to_order = ["cccc", "aaaa", "bbbb"] - - with self.subTest("filenames_for_list wrong length"): - with self.assertRaises(ValueError): - api_workflow_client._order_list_by_filenames( - filenames_for_list[:-1], list_to_order - ) - - with self.subTest("list_to_order wrong length"): - with self.assertRaises(ValueError): - api_workflow_client._order_list_by_filenames( - filenames_for_list, list_to_order[:-1] - ) - - with self.subTest("filenames_for_list and list_to_order wrong length"): - with self.assertRaises(ValueError): - api_workflow_client._order_list_by_filenames( - filenames_for_list[:-1], list_to_order[:-1] - ) diff --git a/tests/api_workflow/test_api_workflow_artifacts.py b/tests/api_workflow/test_api_workflow_artifacts.py deleted file mode 100644 index 685aa28cf..000000000 --- a/tests/api_workflow/test_api_workflow_artifacts.py +++ /dev/null @@ -1,211 +0,0 @@ -import pytest -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, ArtifactNotExist -from lightly.openapi_generated.swagger_client.api import DockerApi -from lightly.openapi_generated.swagger_client.models import ( - DockerRunArtifactData, - DockerRunArtifactType, - DockerRunData, - DockerRunState, -) -from tests.api_workflow import utils - - -def test_download_compute_worker_run_artifacts(mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="123") - mock_download_compute_worker_run_artifact = mocker.MagicMock( - spec_set=client._download_compute_worker_run_artifact - ) - client._download_compute_worker_run_artifact = ( - mock_download_compute_worker_run_artifact - ) - run_id = utils.generate_id() - artifact_ids = [utils.generate_id(), utils.generate_id()] - run = DockerRunData( - id=run_id, - user_id="user-id", - dataset_id=utils.generate_id(), - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - artifacts=[ - DockerRunArtifactData( - id=artifact_ids[0], - file_name="report.pdf", - type=DockerRunArtifactType.REPORT_PDF, - ), - DockerRunArtifactData( - id=artifact_ids[1], - file_name="checkpoint.ckpt", - type=DockerRunArtifactType.CHECKPOINT, - ), - ], - ) - client.download_compute_worker_run_artifacts(run=run, output_dir="output_dir") - calls = [ - mocker.call( - run_id=run_id, - artifact_id=artifact_ids[0], - output_path="output_dir/report.pdf", - timeout=60, - ), - mocker.call( - run_id=run_id, - artifact_id=artifact_ids[1], - output_path="output_dir/checkpoint.ckpt", - timeout=60, - ), - ] - mock_download_compute_worker_run_artifact.assert_has_calls(calls=calls) - assert mock_download_compute_worker_run_artifact.call_count == len(calls) - - -def test__download_compute_worker_run_artifact_by_type( - mocker: MockerFixture, -) -> None: - client = ApiWorkflowClient(token="123") - mock_download_compute_worker_run_artifact = mocker.MagicMock( - spec_set=client._download_compute_worker_run_artifact - ) - client._download_compute_worker_run_artifact = ( - mock_download_compute_worker_run_artifact - ) - run_id = utils.generate_id() - artifact_ids = [utils.generate_id(), utils.generate_id()] - run = DockerRunData( - id=run_id, - user_id="user-id", - dataset_id=utils.generate_id(), - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - artifacts=[ - DockerRunArtifactData( - id=artifact_ids[0], - file_name="report.pdf", - type=DockerRunArtifactType.REPORT_PDF, - ), - DockerRunArtifactData( - id=artifact_ids[1], - file_name="checkpoint.ckpt", - type=DockerRunArtifactType.CHECKPOINT, - ), - ], - ) - client._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.CHECKPOINT, - output_path="output_dir/checkpoint.ckpt", - timeout=0, - ) - mock_download_compute_worker_run_artifact.assert_called_once_with( - run_id=run_id, - artifact_id=artifact_ids[1], - output_path="output_dir/checkpoint.ckpt", - timeout=0, - ) - - -def test__download_compute_worker_run_artifact_by_type__no_artifacts( - mocker: MockerFixture, -) -> None: - client = ApiWorkflowClient(token="123") - mock_download_compute_worker_run_artifact = mocker.MagicMock( - spec_set=client._download_compute_worker_run_artifact - ) - client._download_compute_worker_run_artifact = ( - mock_download_compute_worker_run_artifact - ) - run = DockerRunData( - id=utils.generate_id(), - user_id="user-id", - dataset_id=utils.generate_id(), - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - artifacts=None, - ) - with pytest.raises(ArtifactNotExist, match="Run has no artifacts."): - client._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.CHECKPOINT, - output_path="output_dir/checkpoint.ckpt", - timeout=0, - ) - - -def test__download_compute_worker_run_artifact_by_type__no_artifact_with_type( - mocker: MockerFixture, -) -> None: - client = ApiWorkflowClient(token="123") - mock_download_compute_worker_run_artifact = mocker.MagicMock( - spec_set=client._download_compute_worker_run_artifact - ) - client._download_compute_worker_run_artifact = ( - mock_download_compute_worker_run_artifact - ) - run = DockerRunData( - id=utils.generate_id(), - user_id="user-id", - dataset_id=utils.generate_id(), - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - artifacts=[ - DockerRunArtifactData( - id=utils.generate_id(), - file_name="report.pdf", - type=DockerRunArtifactType.REPORT_PDF, - ), - ], - ) - with pytest.raises(ArtifactNotExist, match="No artifact with type"): - client._download_compute_worker_run_artifact_by_type( - run=run, - artifact_type=DockerRunArtifactType.CHECKPOINT, - output_path="output_dir/checkpoint.ckpt", - timeout=0, - ) - - -def test__get_compute_worker_run_checkpoint_url( - mocker: MockerFixture, -) -> None: - mocked_client = mocker.MagicMock(spec=ApiWorkflowClient) - mocked_artifact = DockerRunArtifactData( - id=utils.generate_id(), - file_name="report.pdf", - type=DockerRunArtifactType.REPORT_PDF, - ) - mocked_client._get_artifact_by_type.return_value = mocked_artifact - mocked_client._compute_worker_api = mocker.MagicMock(spec_set=DockerApi) - mocked_client._compute_worker_api.get_docker_run_artifact_read_url_by_id.return_value = ( - "some_read_url" - ) - - run = DockerRunData( - id=utils.generate_id(), - user_id="user-id", - dataset_id=utils.generate_id(), - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - artifacts=[mocked_artifact], - ) - read_url = ApiWorkflowClient.get_compute_worker_run_checkpoint_url( - self=mocked_client, run=run - ) - - assert read_url == "some_read_url" - mocked_client._get_artifact_by_type.assert_called_with( - artifact_type=DockerRunArtifactType.CHECKPOINT, run=run - ) - mocked_client._compute_worker_api.get_docker_run_artifact_read_url_by_id.assert_called_with( - run_id=run.id, artifact_id=mocked_artifact.id - ) diff --git a/tests/api_workflow/test_api_workflow_client.py b/tests/api_workflow/test_api_workflow_client.py deleted file mode 100644 index 7ed256d19..000000000 --- a/tests/api_workflow/test_api_workflow_client.py +++ /dev/null @@ -1,102 +0,0 @@ -import os -import platform -import unittest -from unittest import mock - -import requests -from pytest_mock import MockerFixture - -import lightly -from lightly.api.api_workflow_client import LIGHTLY_S3_SSE_KMS_KEY, ApiWorkflowClient - - -class TestApiWorkflowClient(unittest.TestCase): - def test_upload_file_with_signed_url(self): - with mock.patch("lightly.api.api_workflow_client.requests") as requests: - client = ApiWorkflowClient(token="") - file = mock.Mock() - signed_write_url = "" - client.upload_file_with_signed_url( - file=file, - signed_write_url=signed_write_url, - ) - requests.put.assert_called_with(signed_write_url, data=file) - - def test_upload_file_with_signed_url_session(self): - session = mock.Mock() - file = mock.Mock() - signed_write_url = "" - client = ApiWorkflowClient(token="") - client.upload_file_with_signed_url( - file=file, signed_write_url=signed_write_url, session=session - ) - session.put.assert_called_with(signed_write_url, data=file) - - def test_upload_file_with_signed_url_session_sse(self): - session = mock.Mock() - file = mock.Mock() - signed_write_url = "http://somwhere.s3.amazonaws.com/someimage.png" - client = ApiWorkflowClient(token="") - # set the environment var to enable SSE - os.environ[LIGHTLY_S3_SSE_KMS_KEY] = "True" - client.upload_file_with_signed_url( - file=file, signed_write_url=signed_write_url, session=session - ) - session.put.assert_called_with( - signed_write_url, - data=file, - headers={"x-amz-server-side-encryption": "AES256"}, - ) - - def test_upload_file_with_signed_url_session_sse_kms(self): - session = mock.Mock() - file = mock.Mock() - signed_write_url = "http://somwhere.s3.amazonaws.com/someimage.png" - client = ApiWorkflowClient(token="") - # set the environment var to enable SSE with KMS - sseKMSKey = "arn:aws:kms:us-west-2:123456789000:key/1234abcd-12ab-34cd-56ef-1234567890ab" - os.environ[LIGHTLY_S3_SSE_KMS_KEY] = sseKMSKey - client.upload_file_with_signed_url( - file=file, signed_write_url=signed_write_url, session=session - ) - session.put.assert_called_with( - signed_write_url, - data=file, - headers={ - "x-amz-server-side-encryption": "aws:kms", - "x-amz-server-side-encryption-aws-kms-key-id": sseKMSKey, - }, - ) - - def test_upload_file_with_signed_url_raise_status(self): - def raise_connection_error(*args, **kwargs): - raise requests.exceptions.ConnectionError() - - with mock.patch( - "lightly.api.api_workflow_client.requests.put", raise_connection_error - ): - client = ApiWorkflowClient(token="") - with self.assertRaises(requests.exceptions.ConnectionError): - client.upload_file_with_signed_url( - file=mock.Mock(), - signed_write_url="", - ) - - -def test_user_agent_header(mocker: MockerFixture) -> None: - mocker.patch.object(lightly.api.api_workflow_client, "__version__", new="VERSION") - mocked_platform = mocker.patch.object( - lightly.api.api_workflow_client, "platform", spec_set=platform - ) - mocked_platform.system.return_value = "SYSTEM" - mocked_platform.release.return_value = "RELEASE" - mocked_platform.platform.return_value = "PLATFORM" - mocked_platform.processor.return_value = "PROCESSOR" - mocked_platform.python_version.return_value = "PYTHON_VERSION" - - client = ApiWorkflowClient(token="") - - assert ( - client.api_client.user_agent - == f"Lightly/VERSION (SYSTEM/RELEASE; PLATFORM; PROCESSOR;) python/PYTHON_VERSION" - ) diff --git a/tests/api_workflow/test_api_workflow_collaboration.py b/tests/api_workflow/test_api_workflow_collaboration.py deleted file mode 100644 index cb1080456..000000000 --- a/tests/api_workflow/test_api_workflow_collaboration.py +++ /dev/null @@ -1,26 +0,0 @@ -from tests.api_workflow import utils -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestApiWorkflowDatasets(MockedApiWorkflowSetup): - def setUp(self) -> None: - self.api_workflow_client = MockedApiWorkflowClient(token="token_xyz") - - def test_share_empty_dataset(self): - self.api_workflow_client.share_dataset_only_with( - dataset_id=utils.generate_id(), user_emails=[] - ) - - def test_share_dataset(self): - self.api_workflow_client.share_dataset_only_with( - dataset_id=utils.generate_id(), user_emails=["someone@something.com"] - ) - - def test_get_shared_users(self): - user_emails = self.api_workflow_client.get_shared_users( - dataset_id=utils.generate_id() - ) - assert user_emails == ["user1@gmail.com", "user2@something.com"] diff --git a/tests/api_workflow/test_api_workflow_compute_worker.py b/tests/api_workflow/test_api_workflow_compute_worker.py deleted file mode 100644 index 5aa8f8789..000000000 --- a/tests/api_workflow/test_api_workflow_compute_worker.py +++ /dev/null @@ -1,982 +0,0 @@ -import json -import random -from typing import Any, List -from unittest import mock -from unittest.mock import MagicMock - -import pytest -from pydantic import ValidationError -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_compute_worker -from lightly.api.api_workflow_compute_worker import ( - STATE_SCHEDULED_ID_NOT_FOUND, - ComputeWorkerRunInfo, - InvalidConfigurationError, - _config_to_camel_case, - _snake_to_camel_case, - _validate_config, -) -from lightly.openapi_generated.swagger_client.api import DockerApi -from lightly.openapi_generated.swagger_client.api_client import ApiClient -from lightly.openapi_generated.swagger_client.models import ( - DockerRunData, - DockerRunScheduledData, - DockerRunScheduledPriority, - DockerRunScheduledState, - DockerRunState, - DockerWorkerConfigV3Docker, - DockerWorkerConfigV3DockerCorruptnessCheck, - DockerWorkerConfigV3Lightly, - DockerWorkerConfigV3LightlyCollate, - DockerWorkerConfigV3LightlyLoader, - DockerWorkerConfigV4, - DockerWorkerState, - DockerWorkerType, - SelectionConfigV4, - SelectionConfigV4Entry, - SelectionConfigV4EntryInput, - SelectionConfigV4EntryStrategy, - SelectionInputPredictionsName, - SelectionInputType, - SelectionStrategyThresholdOperation, - SelectionStrategyTypeV3, - TagData, -) -from lightly.openapi_generated.swagger_client.rest import ApiException -from tests.api_workflow import utils -from tests.api_workflow.mocked_api_workflow_client import MockedApiWorkflowSetup - - -class TestApiWorkflowComputeWorker(MockedApiWorkflowSetup): - def test_register_compute_worker(self): - # default name - worker_id = self.api_workflow_client.register_compute_worker() - assert worker_id - # custom name - worker_id = self.api_workflow_client.register_compute_worker(name="my-worker") - assert worker_id - - def test_delete_compute_worker(self): - with mock.patch( - "tests.api_workflow.mocked_api_workflow_client.MockedComputeWorkerApi" - ".delete_docker_worker_registry_entry_by_id", - ) as mock_delete_worker: - self.api_workflow_client.delete_compute_worker("worker_id") - mock_delete_worker.assert_called_once_with("worker_id") - - def test_create_compute_worker_config(self): - config_id = self.api_workflow_client.create_compute_worker_config( - worker_config={ - "training": {"task_name": "lightly_pretagging"}, - }, - lightly_config={ - "loader": { - "batch_size": 64, - }, - }, - selection_config={ - "n_samples": 20, - "strategies": [ - { - "input": { - "type": "EMBEDDINGS", - "dataset_id": utils.generate_id(), - "tag_name": "some-tag-name", - }, - "strategy": {"type": "SIMILARITY"}, - }, - ], - }, - ) - assert config_id - - def test_create_compute_worker_config__selection_config_is_class(self) -> None: - config_id = self.api_workflow_client.create_compute_worker_config( - worker_config={ - "pretagging": True, - }, - lightly_config={ - "loader": { - "batch_size": 64, - }, - }, - selection_config=SelectionConfigV4( - n_samples=20, - strategies=[ - SelectionConfigV4Entry( - input=SelectionConfigV4EntryInput( - type=SelectionInputType.EMBEDDINGS, - dataset_id=utils.generate_id(), - tag_name="some-tag-name", - ), - strategy=SelectionConfigV4EntryStrategy( - type=SelectionStrategyTypeV3.SIMILARITY, - ), - ) - ], - ), - ) - assert config_id - - def test_create_compute_worker_config__all_none(self) -> None: - config_id = self.api_workflow_client.create_compute_worker_config( - worker_config=None, - lightly_config=None, - selection_config=None, - ) - assert config_id - - def test_schedule_compute_worker_run(self): - scheduled_run_id = self.api_workflow_client.schedule_compute_worker_run( - worker_config={ - "pretagging": True, - }, - lightly_config={ - "loader": { - "batch_size": 64, - }, - }, - ) - assert scheduled_run_id - - def test_schedule_compute_worker_run__priority(self): - scheduled_run_id = self.api_workflow_client.schedule_compute_worker_run( - worker_config={}, - lightly_config={}, - priority=DockerRunScheduledPriority.HIGH, - ) - assert scheduled_run_id - - def test_schedule_compute_worker_run__runs_on(self): - scheduled_run_id = self.api_workflow_client.schedule_compute_worker_run( - worker_config={}, lightly_config={}, runs_on=["AAA", "BBB"] - ) - assert scheduled_run_id - - def test_get_compute_worker_ids(self): - ids = self.api_workflow_client.get_compute_worker_ids() - assert all(isinstance(id_, str) for id_ in ids) - - def test_get_compute_workers(self): - workers = self.api_workflow_client.get_compute_workers() - assert len(workers) == 1 - assert workers[0].name == "worker-name-1" - assert workers[0].state == DockerWorkerState.OFFLINE - assert workers[0].labels == ["label-1"] - - def test_get_compute_worker_runs(self): - runs = self.api_workflow_client.get_compute_worker_runs() - assert len(runs) > 0 - assert all(isinstance(run, DockerRunData) for run in runs) - - def test_get_scheduled_compute_worker_runs(self): - with mock.patch( - "tests.api_workflow.mocked_api_workflow_client.MockedComputeWorkerApi" - ".get_docker_runs_scheduled_by_dataset_id", - ) as mock_get_runs: - self.api_workflow_client.get_scheduled_compute_worker_runs() - mock_get_runs.assert_called_once_with( - dataset_id=self.api_workflow_client.dataset_id - ) - - with mock.patch( - "tests.api_workflow.mocked_api_workflow_client.MockedComputeWorkerApi" - ".get_docker_runs_scheduled_by_dataset_id", - ) as mock_get_runs: - self.api_workflow_client.get_scheduled_compute_worker_runs(state="state") - mock_get_runs.assert_called_once_with( - dataset_id=self.api_workflow_client.dataset_id, state="state" - ) - - def _check_if_openapi_generated_obj_is_valid(self, obj) -> Any: - api_client = ApiClient() - - obj_as_json = json.dumps(api_client.sanitize_for_serialization(obj)) - - mocked_response = mock.MagicMock() - mocked_response.data = obj_as_json - obj_api = api_client.deserialize(mocked_response, type(obj).__name__) - - self.assertDictEqual(obj.to_dict(), obj_api.to_dict()) - - return obj_api - - def test_selection_config(self): - selection_config = SelectionConfigV4( - n_samples=1, - strategies=[ - SelectionConfigV4Entry( - input=SelectionConfigV4EntryInput( - type=SelectionInputType.EMBEDDINGS - ), - strategy=SelectionConfigV4EntryStrategy( - type=SelectionStrategyTypeV3.DIVERSITY, - stopping_condition_minimum_distance=-1, - ), - ), - SelectionConfigV4Entry( - input=SelectionConfigV4EntryInput( - type=SelectionInputType.SCORES, - task="my-classification-task", - score="uncertainty_margin", - ), - strategy=SelectionConfigV4EntryStrategy( - type=SelectionStrategyTypeV3.WEIGHTS - ), - ), - SelectionConfigV4Entry( - input=SelectionConfigV4EntryInput( - type=SelectionInputType.METADATA, key="lightly.sharpness" - ), - strategy=SelectionConfigV4EntryStrategy( - type=SelectionStrategyTypeV3.THRESHOLD, - threshold=20, - operation=SelectionStrategyThresholdOperation.BIGGER_EQUAL, - ), - ), - SelectionConfigV4Entry( - input=SelectionConfigV4EntryInput( - type=SelectionInputType.PREDICTIONS, - task="my_object_detection_task", - name=SelectionInputPredictionsName.CLASS_DISTRIBUTION, - ), - strategy=SelectionConfigV4EntryStrategy( - type=SelectionStrategyTypeV3.BALANCE, - target={"Ambulance": 0.2, "Bus": 0.4}, - ), - ), - ], - ) - config = DockerWorkerConfigV4( - worker_type=DockerWorkerType.FULL, selection=selection_config - ) - - self._check_if_openapi_generated_obj_is_valid(config) - - -def test_selection_config_from_dict() -> None: - dataset_id = utils.generate_id() - cfg = { - "n_samples": 10, - "proportion_samples": 0.1, - "strategies": [ - { - "input": { - "type": "EMBEDDINGS", - "dataset_id": dataset_id, - "tag_name": "some-tag-name", - }, - "strategy": {"type": "SIMILARITY"}, - }, - { - "input": { - "type": "METADATA", - "key": "lightly.sharpness", - }, - "strategy": { - "type": "THRESHOLD", - "threshold": 20, - "operation": "BIGGER", - }, - }, - ], - } - selection_cfg = api_workflow_compute_worker.selection_config_from_dict(cfg) - assert selection_cfg.n_samples == 10 - assert selection_cfg.proportion_samples == 0.1 - assert selection_cfg.strategies is not None - assert len(selection_cfg.strategies) == 2 - assert selection_cfg.strategies[0].input.type == "EMBEDDINGS" - assert selection_cfg.strategies[0].input.dataset_id == dataset_id - assert selection_cfg.strategies[0].input.tag_name == "some-tag-name" - assert selection_cfg.strategies[0].strategy.type == "SIMILARITY" - assert selection_cfg.strategies[1].input.type == "METADATA" - assert selection_cfg.strategies[1].input.key == "lightly.sharpness" - assert selection_cfg.strategies[1].strategy.type == "THRESHOLD" - assert selection_cfg.strategies[1].strategy.threshold == 20 - assert selection_cfg.strategies[1].strategy.operation == "BIGGER" - # verify that original dict was not mutated - assert isinstance(cfg["strategies"][0]["input"], dict) - - -def test_selection_config_from_dict__missing_strategies() -> None: - cfg = {} - with pytest.raises( - ValidationError, - match=r"strategies\n ensure this value has at least 1 items", - ): - api_workflow_compute_worker.selection_config_from_dict(cfg) - - -def test_selection_config_from_dict__extra_key() -> None: - cfg = {"strategies": [], "invalid-key": 0} - with pytest.raises( - ValidationError, - match=r"invalid-key\n extra fields not permitted", - ): - api_workflow_compute_worker.selection_config_from_dict(cfg) - - -def test_selection_config_from_dict__extra_stratey_key() -> None: - cfg = { - "strategies": [ - { - "input": {"type": "EMBEDDINGS"}, - "strategy": {"type": "DIVERSITY"}, - "invalid-key": {"type": ""}, - }, - ], - } - with pytest.raises( - ValidationError, - match=r"invalid-key\n extra fields not permitted", - ): - api_workflow_compute_worker.selection_config_from_dict(cfg) - - -def test_selection_config_from_dict__extra_strategy_strategy_key() -> None: - cfg = { - "strategies": [ - { - "input": {"type": "EMBEDDINGS"}, - "strategy": { - "type": "DIVERSITY", - "stoppingConditionMinimumDistance": 0, - }, - }, - ], - } - with pytest.raises( - ValidationError, - match=r"stoppingConditionMinimumDistance\n extra fields not permitted", - ): - api_workflow_compute_worker.selection_config_from_dict(cfg) - - -def test_selection_config_from_dict__multiple_references() -> None: - """Test that conversion is successful if the dictionary contains multiple references - to the same object. - """ - strategy = {"input": {"type": "EMBEDDINGS"}, "strategy": {"type": "DIVERSITY"}} - cfg = {"strategies": [strategy, strategy]} - selection_cfg = api_workflow_compute_worker.selection_config_from_dict(cfg) - assert len(selection_cfg.strategies) == 2 - assert selection_cfg.strategies[0] == selection_cfg.strategies[1] - - -def test_get_scheduled_run_by_id() -> None: - run_ids = [utils.generate_id() for _ in range(3)] - scheduled_runs = [ - DockerRunScheduledData( - id=run_id, - dataset_id=utils.generate_id(), - config_id=utils.generate_id(), - priority=DockerRunScheduledPriority.MID, - state=DockerRunScheduledState.OPEN, - created_at=0, - last_modified_at=1, - runs_on=[], - ) - for run_id in run_ids - ] - mocked_compute_worker_api = MagicMock( - get_docker_runs_scheduled_by_dataset_id=lambda dataset_id: scheduled_runs - ) - mocked_api_client = MagicMock( - dataset_id="asdf", _compute_worker_api=mocked_compute_worker_api - ) - - scheduled_run_id = run_ids[2] - scheduled_run_data = ApiWorkflowClient._get_scheduled_run_by_id( - self=mocked_api_client, scheduled_run_id=scheduled_run_id - ) - assert scheduled_run_data.id == scheduled_run_id - - -def test_get_scheduled_run_by_id_not_found() -> None: - scheduled_runs = [ - DockerRunScheduledData( - id=utils.generate_id(), - dataset_id=utils.generate_id(), - config_id=utils.generate_id(), - priority=DockerRunScheduledPriority.LOW, - state=DockerRunScheduledState.OPEN, - created_at=0, - last_modified_at=1, - runs_on=[], - ) - for _ in range(3) - ] - mocked_compute_worker_api = MagicMock( - get_docker_runs_scheduled_by_dataset_id=lambda dataset_id: scheduled_runs - ) - mocked_api_client = MagicMock( - dataset_id="asdf", _compute_worker_api=mocked_compute_worker_api - ) - - scheduled_run_id = "id_5" - with pytest.raises( - ApiException, - match=f"No scheduled run found for run with scheduled_run_id='{scheduled_run_id}'.", - ): - ApiWorkflowClient._get_scheduled_run_by_id( - self=mocked_api_client, scheduled_run_id=scheduled_run_id - ) - - -def test_get_compute_worker_state_and_message_OPEN() -> None: - dataset_id = utils.generate_id() - scheduled_run = DockerRunScheduledData( - id=utils.generate_id(), - dataset_id=dataset_id, - config_id=utils.generate_id(), - priority=DockerRunScheduledPriority.MID, - state=DockerRunScheduledState.OPEN, - created_at=0, - last_modified_at=1, - runs_on=["worker-label"], - ) - - def mocked_raise_exception(*args, **kwargs): - raise ApiException - - mocked_api_client = MagicMock( - dataset_id=dataset_id, - _compute_worker_api=MagicMock( - get_docker_run_by_scheduled_id=mocked_raise_exception - ), - _get_scheduled_run_by_id=lambda id: scheduled_run, - ) - - run_info = ApiWorkflowClient.get_compute_worker_run_info( - self=mocked_api_client, scheduled_run_id="" - ) - assert run_info.state == DockerRunScheduledState.OPEN - assert run_info.message.startswith("Waiting for pickup by Lightly Worker.") - assert run_info.in_end_state() == False - - -def test_create_docker_worker_config_vx_api_error() -> None: - class HttpThing: - def __init__(self, status, reason, data): - self.status = status - self.reason = reason - self.data = data - - def getheaders(self): - return [] - - def mocked_raise_exception(*args, **kwargs): - raise ApiException( - http_resp=HttpThing( - 403, - "Not everything has a reason", - '{"code": "ACCOUNT_SUBSCRIPTION_INSUFFICIENT", "error": "Your current plan allows for 1000000 samples but you tried to use 2000000 samples, please contact sales at sales@lightly.ai to upgrade your account."}', - ) - ) - - client = ApiWorkflowClient(token="123") - client._dataset_id = utils.generate_id() - client._compute_worker_api.create_docker_worker_config_vx = mocked_raise_exception - with pytest.raises( - ApiException, - match=r'"Your current plan allows for 1000000 samples but you tried to use 2000000 samples, please contact sales at sales@lightly.ai to upgrade your account."', - ): - r = client.create_compute_worker_config( - selection_config={ - "n_samples": 2000000, - "strategies": [ - {"input": {"type": "EMBEDDINGS"}, "strategy": {"type": "DIVERSITY"}} - ], - }, - ) - - -def test_create_docker_worker_config_vx_5xx_api_error() -> None: - class HttpThing: - def __init__(self, status, reason, data): - self.status = status - self.reason = reason - self.data = data - - def getheaders(self): - return [] - - def mocked_raise_exception(*args, **kwargs): - raise ApiException( - http_resp=HttpThing( - 502, - "Not everything has a reason", - '{"code": "SOMETHING_BAD", "error": "Server pains"}', - ) - ) - - client = ApiWorkflowClient(token="123") - client._dataset_id = utils.generate_id() - client._compute_worker_api.create_docker_worker_config_vx = mocked_raise_exception - with pytest.raises( - ApiException, - match=r"Server pains", - ): - r = client.create_compute_worker_config( - selection_config={ - "n_samples": 20, - "strategies": [ - {"input": {"type": "EMBEDDINGS"}, "strategy": {"type": "DIVERSITY"}} - ], - }, - ) - - -def test_create_docker_worker_config_vx_no_body_api_error() -> None: - def mocked_raise_exception(*args, **kwargs): - raise ApiException - - client = ApiWorkflowClient(token="123") - client._dataset_id = utils.generate_id() - client._compute_worker_api.create_docker_worker_config_vx = mocked_raise_exception - with pytest.raises( - ApiException, - ): - r = client.create_compute_worker_config( - selection_config={ - "n_samples": 20, - "strategies": [ - {"input": {"type": "EMBEDDINGS"}, "strategy": {"type": "DIVERSITY"}} - ], - }, - ) - - -def test_get_compute_worker_state_and_message_CANCELED() -> None: - def mocked_raise_exception(*args, **kwargs): - raise ApiException - - mocked_api_client = MagicMock( - dataset_id=utils.generate_id(), - _compute_worker_api=MagicMock( - get_docker_run_by_scheduled_id=mocked_raise_exception - ), - _get_scheduled_run_by_id=mocked_raise_exception, - ) - run_info = ApiWorkflowClient.get_compute_worker_run_info( - self=mocked_api_client, scheduled_run_id="" - ) - assert run_info.state == STATE_SCHEDULED_ID_NOT_FOUND - assert run_info.message.startswith("Could not find a job for the given run_id:") - assert run_info.in_end_state() == True - - -def test_get_compute_worker_state_and_message_docker_state() -> None: - message = "SOME_MESSAGE" - docker_run = DockerRunData( - id=utils.generate_id(), - user_id="user-id", - state=DockerRunState.GENERATING_REPORT, - docker_version="", - created_at=0, - last_modified_at=0, - message=message, - ) - mocked_api_client = MagicMock( - dataset_id=utils.generate_id(), - _compute_worker_api=MagicMock( - get_docker_run_by_scheduled_id=lambda scheduled_id: docker_run - ), - ) - - run_info = ApiWorkflowClient.get_compute_worker_run_info( - self=mocked_api_client, scheduled_run_id=utils.generate_id() - ) - assert run_info.state == DockerRunState.GENERATING_REPORT - assert run_info.message == message - assert run_info.in_end_state() == False - - -def test_compute_worker_run_info_generator(mocker) -> None: - states = [f"state_{i}" for i in range(7)] - states[-1] = DockerRunState.COMPLETED - - class MockedApiWorkflowClient: - def __init__(self, states: List[str]): - self.states = states - self.current_state_index = 0 - random.seed(42) - - def get_compute_worker_run_info(self, scheduled_run_id: str): - state = self.states[self.current_state_index] - if random.random() > 0.9: - self.current_state_index += 1 - return ComputeWorkerRunInfo(state=state, message=state) - - mocker.patch("time.sleep", lambda _: None) - - mocked_client = MockedApiWorkflowClient(states) - run_infos = list( - ApiWorkflowClient.compute_worker_run_info_generator( - mocked_client, scheduled_run_id="" - ) - ) - - expected_run_infos = [ - ComputeWorkerRunInfo(state=state, message=state) for state in states - ] - - assert run_infos == expected_run_infos - - -def test_get_compute_worker_runs(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - dataset_id = utils.generate_id() - run_ids = [utils.generate_id(), utils.generate_id()] - client = ApiWorkflowClient(token="123") - mock_compute_worker_api = mocker.create_autospec( - DockerApi, spec_set=True - ).return_value - mock_compute_worker_api.get_docker_runs.side_effect = [ - [ - DockerRunData( - id=run_ids[0], - user_id="user-id", - created_at=20, - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - last_modified_at=0, - ), - DockerRunData( - id=run_ids[1], - user_id="user-id", - created_at=10, - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - last_modified_at=0, - ), - ], - ] - client._compute_worker_api = mock_compute_worker_api - runs = client.get_compute_worker_runs() - assert runs == [ - DockerRunData( - id=run_ids[1], - user_id="user-id", - created_at=10, - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - last_modified_at=0, - ), - DockerRunData( - id=run_ids[0], - user_id="user-id", - created_at=20, - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - last_modified_at=0, - ), - ] - mock_compute_worker_api.get_docker_runs.assert_called_once_with( - page_offset=0, page_size=5000 - ) - - -def test_get_compute_worker_runs__dataset(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - dataset_id = utils.generate_id() - run_id = utils.generate_id() - client = ApiWorkflowClient(token="123") - mock_compute_worker_api = mocker.create_autospec( - DockerApi, spec_set=True - ).return_value - mock_compute_worker_api.get_docker_runs_query_by_dataset_id.side_effect = [ - [ - DockerRunData( - id=run_id, - user_id="user-id", - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - ), - ], - [], - ] - - client._compute_worker_api = mock_compute_worker_api - runs = client.get_compute_worker_runs(dataset_id=dataset_id) - assert runs == [ - DockerRunData( - id=run_id, - user_id="user-id", - dataset_id=dataset_id, - docker_version="", - state=DockerRunState.COMPUTING_METADATA, - created_at=0, - last_modified_at=0, - ), - ] - mock_compute_worker_api.get_docker_runs_query_by_dataset_id.assert_called_once_with( - page_offset=0, page_size=5000, dataset_id=dataset_id - ) - - -def test_get_compute_worker_run_tags__no_tags(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - run_id = utils.generate_id() - client = ApiWorkflowClient(token="123", dataset_id=utils.generate_id()) - mock_compute_worker_api = mocker.create_autospec( - DockerApi, spec_set=True - ).return_value - mock_compute_worker_api.get_docker_run_tags.return_value = [] - client._compute_worker_api = mock_compute_worker_api - tags = client.get_compute_worker_run_tags(run_id=run_id) - assert len(tags) == 0 - mock_compute_worker_api.get_docker_run_tags.assert_called_once_with(run_id=run_id) - - -def test_get_compute_worker_run_tags__single_tag(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - run_id = utils.generate_id() - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - client = ApiWorkflowClient(token="123", dataset_id=dataset_id) - client._dataset_id = dataset_id - mock_compute_worker_api = mocker.create_autospec( - DockerApi, spec_set=True - ).return_value - mock_compute_worker_api.get_docker_run_tags.return_value = [ - TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name="tag-0", - tot_size=0, - created_at=0, - changes=None, - run_id=run_id, - ) - ] - client._compute_worker_api = mock_compute_worker_api - tags = client.get_compute_worker_run_tags(run_id=run_id) - assert len(tags) == 1 - mock_compute_worker_api.get_docker_run_tags.assert_called_once_with(run_id=run_id) - - -def test_get_compute_worker_run_tags__multiple_tags(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - run_id = utils.generate_id() - dataset_id = utils.generate_id() - client = ApiWorkflowClient(token="123", dataset_id=dataset_id) - client._dataset_id = dataset_id - mock_compute_worker_api = mocker.create_autospec( - DockerApi, spec_set=True - ).return_value - - tag_ids = [utils.generate_id() for _ in range(3)] - tag_0 = TagData( - id=tag_ids[0], - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name="tag-0", - tot_size=0, - created_at=0, - changes=None, - run_id=run_id, - ) - tag_1 = TagData( - id=tag_ids[1], - dataset_id=dataset_id, - prev_tag_id=tag_ids[0], - bit_mask_data="0x1", - name="tag-1", - tot_size=0, - created_at=1, - changes=None, - run_id=run_id, - ) - # tag from a different dataset - tag_2 = TagData( - id=tag_ids[2], - dataset_id=utils.generate_id(), - prev_tag_id=None, - bit_mask_data="0x1", - name="tag-2", - tot_size=0, - created_at=2, - changes=None, - run_id=run_id, - ) - # tags are returned ordered by decreasing creation date - mock_compute_worker_api.get_docker_run_tags.return_value = [tag_2, tag_1, tag_0] - client._compute_worker_api = mock_compute_worker_api - tags = client.get_compute_worker_run_tags(run_id="run-0") - assert len(tags) == 2 - assert tags[0] == tag_1 - assert tags[1] == tag_0 - mock_compute_worker_api.get_docker_run_tags.assert_called_once_with(run_id="run-0") - - -def test__config_to_camel_case() -> None: - assert _config_to_camel_case( - { - "lorem_ipsum": "dolor", - "lorem": { - "ipsum_dolor": "sit_amet", - }, - } - ) == { - "loremIpsum": "dolor", - "lorem": { - "ipsumDolor": "sit_amet", - }, - } - - -def test__snake_to_camel_case() -> None: - assert _snake_to_camel_case("lorem") == "lorem" - assert _snake_to_camel_case("lorem_ipsum") == "loremIpsum" - assert _snake_to_camel_case("lorem_ipsum_dolor") == "loremIpsumDolor" - assert _snake_to_camel_case("loremIpsum") == "loremIpsum" # do nothing - - -def test__validate_config__docker() -> None: - obj = DockerWorkerConfigV3Docker( - enable_training=False, - corruptness_check=DockerWorkerConfigV3DockerCorruptnessCheck( - corruption_threshold=0.1, - ), - ) - _validate_config( - cfg={ - "enable_training": False, - "corruptness_check": { - "corruption_threshold": 0.1, - }, - }, - obj=obj, - ) - - -def test__validate_config__docker_typo() -> None: - obj = DockerWorkerConfigV3Docker( - enable_training=False, - corruptness_check=DockerWorkerConfigV3DockerCorruptnessCheck( - corruption_threshold=0.1, - ), - ) - - with pytest.raises( - InvalidConfigurationError, - match="Option 'enable_trainingx' does not exist! Did you mean 'enable_training'?", - ): - _validate_config( - cfg={ - "enable_trainingx": False, - "corruptness_check": { - "corruption_threshold": 0.1, - }, - }, - obj=obj, - ) - - -def test__validate_config__docker_typo_nested() -> None: - obj = DockerWorkerConfigV3Docker( - enable_training=False, - corruptness_check=DockerWorkerConfigV3DockerCorruptnessCheck( - corruption_threshold=0.1, - ), - ) - - with pytest.raises( - InvalidConfigurationError, - match="Option 'corruption_thresholdx' does not exist! Did you mean 'corruption_threshold'?", - ): - _validate_config( - cfg={ - "enable_training": False, - "corruptness_check": { - "corruption_thresholdx": 0.1, - }, - }, - obj=obj, - ) - - -def test__validate_config__lightly() -> None: - obj = DockerWorkerConfigV3Lightly( - loader=DockerWorkerConfigV3LightlyLoader( - num_workers=-1, - batch_size=16, - shuffle=True, - ), - collate=DockerWorkerConfigV3LightlyCollate( - rr_degrees=[-90, 90], - ), - ) - _validate_config( - cfg={ - "loader": { - "num_workers": -1, - "batch_size": 16, - "shuffle": True, - }, - "collate": { - "rr_degrees": [-90, 90], - }, - }, - obj=obj, - ) - - -def test__validate_config__lightly_typo() -> None: - obj = DockerWorkerConfigV3Lightly( - loader=DockerWorkerConfigV3LightlyLoader( - num_workers=-1, - batch_size=16, - shuffle=True, - ) - ) - with pytest.raises( - InvalidConfigurationError, - match="Option 'loaderx' does not exist! Did you mean 'loader'?", - ): - _validate_config( - cfg={ - "loaderx": { - "num_workers": -1, - "batch_size": 16, - "shuffle": True, - }, - }, - obj=obj, - ) - - -def test__validate_config__lightly_typo_nested() -> None: - obj = DockerWorkerConfigV3Lightly( - loader=DockerWorkerConfigV3LightlyLoader( - num_workers=-1, - batch_size=16, - shuffle=True, - ) - ) - with pytest.raises( - InvalidConfigurationError, - match="Option 'num_workersx' does not exist! Did you mean 'num_workers'?", - ): - _validate_config( - cfg={ - "loader": { - "num_workersx": -1, - "batch_size": 16, - "shuffle": True, - }, - }, - obj=obj, - ) diff --git a/tests/api_workflow/test_api_workflow_datasets.py b/tests/api_workflow/test_api_workflow_datasets.py deleted file mode 100644 index dab2ad39d..000000000 --- a/tests/api_workflow/test_api_workflow_datasets.py +++ /dev/null @@ -1,493 +0,0 @@ -from typing import List - -import pytest -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_datasets -from lightly.openapi_generated.swagger_client.api import DatasetsApi -from lightly.openapi_generated.swagger_client.models import ( - Creator, - DatasetCreateRequest, - DatasetData, - DatasetType, -) -from lightly.openapi_generated.swagger_client.rest import ApiException -from tests.api_workflow import utils -from tests.api_workflow.mocked_api_workflow_client import MockedApiWorkflowSetup - - -def _get_datasets(count: int) -> List[DatasetData]: - return [ - DatasetData( - name=f"mock_dataset_{i}", - id=utils.generate_id(), - last_modified_at=0, - type=DatasetType.IMAGES, - img_type="full", - size_in_bytes=-1, - n_samples=-1, - created_at=0, - user_id="user_0", - ) - for i in range(count) - ] - - -class TestApiWorkflowDatasets(MockedApiWorkflowSetup): - def setUp(self, token="token_xyz", dataset_id="dataset_id_xyz") -> None: - super().setUp(token, dataset_id) - self.api_workflow_client._datasets_api.reset() - - def test_create_dataset_existing(self): - with self.assertRaises(ValueError): - self.api_workflow_client.create_dataset(dataset_name="dataset_1") - - def test_dataset_name_exists__own_not_existing(self): - assert not self.api_workflow_client.dataset_name_exists( - dataset_name="not_existing_dataset" - ) - - def test_dataset_exists__raises_error(self): - with self.assertRaises(ApiException) as e: - self.api_workflow_client.dataset_exists(dataset_id=None) - assert e.status != 404 - - def test_dataset_name_exists__own_existing(self): - assert self.api_workflow_client.dataset_name_exists(dataset_name="dataset_1") - - def test_dataset_name_exists__shared_existing(self): - assert self.api_workflow_client.dataset_name_exists( - dataset_name="shared_dataset_1", shared=True - ) - - def test_dataset_name_exists__shared_not_existing(self): - assert not self.api_workflow_client.dataset_name_exists( - dataset_name="not_existing_dataset", shared=True - ) - - def test_dataset_name_exists__own_and_shared_existing(self): - assert self.api_workflow_client.dataset_name_exists( - dataset_name="dataset_1", shared=None - ) - assert self.api_workflow_client.dataset_name_exists( - dataset_name="shared_dataset_1", shared=None - ) - - def test_dataset_name_exists__own_and_shared_not_existing(self): - assert not self.api_workflow_client.dataset_name_exists( - dataset_name="not_existing_dataset", shared=None - ) - - def test_get_datasets_by_name__own_not_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="shared_dataset_1", shared=False - ) - assert datasets == [] - - def test_get_datasets_by_name__own_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="dataset_1", shared=False - ) - assert all(dataset.name == "dataset_1" for dataset in datasets) - assert len(datasets) == 1 - - def test_get_datasets_by_name__shared_not_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="dataset_1", shared=True - ) - assert datasets == [] - - def test_get_datasets_by_name__shared_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="shared_dataset_1", shared=True - ) - assert all(dataset.name == "shared_dataset_1" for dataset in datasets) - assert len(datasets) == 1 - - def test_get_datasets_by_name__own_and_shared_not_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="not_existing_dataset", shared=None - ) - assert datasets == [] - - def test_get_datasets_by_name__own_and_shared_existing(self): - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="dataset_1", shared=None - ) - assert all(dataset.name == "dataset_1" for dataset in datasets) - assert len(datasets) == 1 - - datasets = self.api_workflow_client.get_datasets_by_name( - dataset_name="shared_dataset_1", shared=True - ) - assert all(dataset.name == "shared_dataset_1" for dataset in datasets) - assert len(datasets) == 1 - - def test_get_all_datasets(self): - datasets = self.api_workflow_client.get_all_datasets() - dataset_names = {dataset.name for dataset in datasets} - assert "dataset_1" in dataset_names - assert "shared_dataset_1" in dataset_names - - -def test_create_new_dataset_with_unique_name__new_name(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "dataset_name_exists", return_value=False) - mocked_create_dataset = mocker.patch.object( - ApiWorkflowClient, "_create_dataset_without_check_existing" - ) - dataset_name = "dataset-name" - dataset_type = DatasetType.IMAGES - client = ApiWorkflowClient() - client.create_new_dataset_with_unique_name( - dataset_basename=dataset_name, dataset_type=dataset_type - ) - mocked_create_dataset.assert_called_once_with( - dataset_name=dataset_name, - dataset_type=dataset_type, - ) - - -def test_create_new_dataset_with_unique_name__name_exists( - mocker: MockerFixture, -) -> None: - datasets = _get_datasets(1) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "dataset_name_exists", return_value=True) - mocked_create_dataset = mocker.patch.object( - ApiWorkflowClient, "_create_dataset_without_check_existing" - ) - mocked_datasets_api = mocker.MagicMock() - dataset_name = datasets[0].name - dataset_type = datasets[0].type - actual_dataset_name = f"{dataset_name}_1" - client = ApiWorkflowClient() - client._datasets_api = mocked_datasets_api - client.create_new_dataset_with_unique_name( - dataset_basename=dataset_name, dataset_type=dataset_type - ) - mocked_datasets_api.get_datasets_query_by_name.assert_called_once_with( - dataset_name=dataset_name, - exact=False, - shared=False, - page_offset=0, - page_size=5000, - ) - mocked_create_dataset.assert_called_once_with( - dataset_name=actual_dataset_name, - dataset_type=dataset_type, - ) - - -def test_dataset_exists(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_dataset = mocker.patch.object(ApiWorkflowClient, "get_dataset_by_id") - dataset_id = "dataset-id" - client = ApiWorkflowClient() - assert client.dataset_exists(dataset_id) - mocked_get_dataset.assert_called_once_with(dataset_id) - - -def test_dataset_exists__not_found(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_dataset_by_id", side_effect=ApiException(status=404) - ) - client = ApiWorkflowClient() - assert not client.dataset_exists("foo") - - -def test_dataset_exists__error(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_dataset_by_id", side_effect=RuntimeError("some error") - ) - client = ApiWorkflowClient() - with pytest.raises(RuntimeError) as exception: - client.dataset_exists("foo") - assert str(exception.value) == "some error" - - -def test_dataset_type(mocker: MockerFixture) -> None: - dataset = _get_datasets(1)[0] - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "_get_current_dataset", return_value=dataset) - client = ApiWorkflowClient() - assert client.dataset_type == dataset.type - - -def test_delete_dataset(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._dataset_id = "foo" - client._datasets_api = mock_datasets_api - client.delete_dataset_by_id("foobar") - mock_datasets_api.delete_dataset_by_id.assert_called_once_with(dataset_id="foobar") - assert not hasattr(client, "_dataset_id") - - -def test_get_datasets__shared(mocker: MockerFixture) -> None: - datasets = _get_datasets(2) - # Returns the same set of datasets twice. API client should remove duplicates - mocked_pagination = mocker.patch.object( - api_workflow_datasets.utils, - "paginate_endpoint", - side_effect=[datasets, datasets], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - datasets = client.get_datasets(shared=True) - unique_dataset_ids = set([dataset.id for dataset in datasets]) - assert len(unique_dataset_ids) == len(datasets) - - assert mocked_pagination.call_count == 2 - call_args = mocked_pagination.call_args_list - assert call_args[0][0] == (mock_datasets_api.get_datasets,) - assert call_args[0][1] == {"shared": True} - assert call_args[1][0] == (mock_datasets_api.get_datasets,) - assert call_args[1][1] == {"get_assets_of_team": True} - - -def test_get_datasets__not_shared(mocker: MockerFixture) -> None: - mocked_pagination = mocker.patch.object( - api_workflow_datasets.utils, "paginate_endpoint" - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - client.get_datasets(shared=False) - mocked_pagination.assert_called_once_with( - mock_datasets_api.get_datasets, shared=False - ) - - -def test_get_datasets__shared_None(mocker: MockerFixture) -> None: - mocked_pagination = mocker.patch.object( - api_workflow_datasets.utils, "paginate_endpoint" - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - client.get_datasets(shared=None) - assert mocked_pagination.call_count == 3 - - -def test_get_datasets_by_name__not_shared__paginated(mocker: MockerFixture) -> None: - datasets = _get_datasets(3) - # Returns the same set of datasets twice. API client should remove duplicates. - mocked_paginate_endpoint = mocker.patch.object( - api_workflow_datasets.utils, - "paginate_endpoint", - # There's one call to paginate_endpoint. - # It returns a paginated list of datasets. - return_value=iter([datasets[0], datasets[1]]), - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - - # Note: because the `dataset_name` filtering is mocked away in this test, - # the `dataset_name` passed as argument and in the returned dataset are independent. - datasets_not_shared = client.get_datasets_by_name( - shared=False, dataset_name="some_random_dataset_name" - ) - assert datasets_not_shared == [datasets[0], datasets[1]] - mocked_paginate_endpoint.assert_called_once_with( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - shared=False, - ) - - -def test_get_datasets_by_name__shared__paginated(mocker: MockerFixture) -> None: - datasets = _get_datasets(3) - # Returns the same set of datasets twice. API client should remove duplicates. - mocked_paginate_endpoint = mocker.patch.object( - api_workflow_datasets.utils, - "paginate_endpoint", - side_effect=[ - # There are two calls to paginate_endpoint to get all the team's datasets. - iter([datasets[2]]), - iter([]), - ], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - - # Note: because the `dataset_name` filtering is mocked away in this test, - # the `dataset_name` passed as argument and in the returned dataset are independent. - datasets_shared = client.get_datasets_by_name( - shared=True, dataset_name="some_random_dataset_name" - ) - assert datasets_shared == [datasets[2]] - mocked_paginate_endpoint.assert_has_calls( - [ - mocker.call( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - shared=True, - ), - mocker.call( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - get_assets_of_team=True, - ), - ] - ) - - -def test_get_datasets_by_name__shared_None__paginated(mocker: MockerFixture) -> None: - datasets = _get_datasets(3) - # Returns the same set of datasets twice. API client should remove duplicates. - mocked_paginate_endpoint = mocker.patch.object( - api_workflow_datasets.utils, - "paginate_endpoint", - side_effect=[ - # There are three calls to paginate_endpoint. The first call - # gets all the user's datasets. The second and third calls get - # all the team's datasets. - # The first call returns a paginated list of datasets. - iter([datasets[0], datasets[1]]), - iter([datasets[2]]), - iter([]), - ], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_datasets_api = mocker.MagicMock() - client = ApiWorkflowClient() - client._datasets_api = mock_datasets_api - - # Note: because the `dataset_name` filtering is mocked away in this test, - # the `dataset_name` passed as argument and in the returned dataset are independent. - datasets_shared_none = client.get_datasets_by_name( - shared=None, dataset_name="some_random_dataset_name" - ) - assert datasets_shared_none == [datasets[0], datasets[1], datasets[2]] - mocked_paginate_endpoint.assert_has_calls( - [ - mocker.call( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - shared=False, - ), - mocker.call( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - shared=True, - ), - mocker.call( - mock_datasets_api.get_datasets_query_by_name, - dataset_name="some_random_dataset_name", - exact=True, - get_assets_of_team=True, - ), - ] - ) - - -def test_set_dataset_id__error(mocker: MockerFixture): - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_datasets_by_name", return_value=[]) - client = ApiWorkflowClient() - with pytest.raises(ValueError) as exception: - client.set_dataset_id_by_name("dataset_1") - assert str(exception.value) == ( - "A dataset with the name 'dataset_1' does not exist on the " - "Lightly Platform. Please create it first." - ) - - -def test_set_dataset_id__warning_not_shared(mocker: MockerFixture) -> None: - datasets = _get_datasets(2) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_datasets_by_name", return_value=datasets - ) - mocked_warn = mocker.patch("warnings.warn") - client = ApiWorkflowClient() - - dataset_name = datasets[0].name - dataset_id = datasets[0].id - client.set_dataset_id_by_name(dataset_name, shared=False) - assert client.dataset_id == dataset_id - mocked_warn.assert_called_once_with( - f"Found 2 datasets with the name '{dataset_name}'. Their " - f"ids are {[dataset.id for dataset in datasets]}. " - f"The dataset_id of the client was set to '{dataset_id}'. " - ) - - -def test_set_dataset_id__warning_shared(mocker: MockerFixture) -> None: - datasets = _get_datasets(2) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_datasets_by_name", return_value=datasets - ) - mocked_warn = mocker.patch("warnings.warn") - client = ApiWorkflowClient() - - dataset_name = datasets[0].name - dataset_id = datasets[0].id - client.set_dataset_id_by_name(dataset_name, shared=True) - assert client.dataset_id == dataset_id - mocked_warn.assert_called_once_with( - f"Found 2 datasets with the name '{dataset_name}'. Their " - f"ids are {[dataset.id for dataset in datasets]}. " - f"The dataset_id of the client was set to '{dataset_id}'. " - "We noticed that you set shared=True which also retrieves " - "datasets shared with you. Set shared=False to only consider " - "datasets you own." - ) - - -def test_set_dataset_id__success(mocker: MockerFixture) -> None: - datasets = _get_datasets(1) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_datasets_by_name", return_value=datasets - ) - client = ApiWorkflowClient() - client.set_dataset_id_by_name(datasets[0].name) - assert client.dataset_id == datasets[0].id - - -def test_create_dataset(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - client = ApiWorkflowClient() - client._creator = Creator.USER_PIP - client._datasets_api = mocker.create_autospec(DatasetsApi) - - client.create_dataset(dataset_name="name") - expected_body = DatasetCreateRequest( - name="name", type=DatasetType.IMAGES, creator=Creator.USER_PIP - ) - client._datasets_api.create_dataset.assert_called_once_with( - dataset_create_request=expected_body - ) - - -def test_create_dataset__error(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "dataset_name_exists", return_value=True) - - client = ApiWorkflowClient() - with pytest.raises(ValueError) as exception: - client.create_dataset(dataset_name="name") - assert str(exception.value) == ( - "A dataset with the name 'name' already exists! Please use " - "the `set_dataset_id_by_name()` method instead if you intend to reuse " - "an existing dataset." - ) diff --git a/tests/api_workflow/test_api_workflow_datasources.py b/tests/api_workflow/test_api_workflow_datasources.py deleted file mode 100644 index cbaa46bb7..000000000 --- a/tests/api_workflow/test_api_workflow_datasources.py +++ /dev/null @@ -1,644 +0,0 @@ -import pytest -import tqdm -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_datasources -from lightly.openapi_generated.swagger_client.models import ( - DatasourceConfigAzure, - DatasourceConfigGCS, - DatasourceConfigLOCAL, - DatasourceConfigS3, - DatasourceConfigS3DelegatedAccess, - DatasourcePurpose, - DatasourceRawSamplesDataRow, -) -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data import ( - DatasourceConfigVerifyData, -) -from lightly.openapi_generated.swagger_client.models.datasource_config_verify_data_errors import ( - DatasourceConfigVerifyDataErrors, -) -from lightly.openapi_generated.swagger_client.models.datasource_processed_until_timestamp_response import ( - DatasourceProcessedUntilTimestampResponse, -) -from lightly.openapi_generated.swagger_client.models.datasource_raw_samples_data import ( - DatasourceRawSamplesData, -) - - -class TestDatasourcesMixin: - def test_download_raw_samples(self, mocker: MockerFixture) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_from_datasource_by_dataset_id", - side_effect=[response], - ) - assert client.download_raw_samples() == [("file1", "url1"), ("file2", "url2")] - - def test_download_raw_predictions(self, mocker: MockerFixture) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", - side_effect=[response], - ) - assert client.download_raw_predictions(task_name="task") == [ - ("file1", "url1"), - ("file2", "url2"), - ] - - def test_download_raw_predictions_iter(self, mocker: MockerFixture) -> None: - response_1 = DatasourceRawSamplesData( - hasMore=True, - cursor="cursor1", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - response_2 = DatasourceRawSamplesData( - hasMore=False, - cursor="cursor2", - data=[ - DatasourceRawSamplesDataRow(fileName="file3", readUrl="url3"), - DatasourceRawSamplesDataRow(fileName="file4", readUrl="url4"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", - side_effect=[response_1, response_2], - ) - assert list(client.download_raw_predictions_iter(task_name="task")) == [ - ("file1", "url1"), - ("file2", "url2"), - ("file3", "url3"), - ("file4", "url4"), - ] - client._datasources_api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id.assert_has_calls( - [ - mocker.call( - dataset_id="dataset-id", - task_name="task", - var_from=0, - to=mocker.ANY, - use_redirected_read_url=False, - ), - mocker.call( - dataset_id="dataset-id", - task_name="task", - cursor="cursor1", - use_redirected_read_url=False, - ), - ] - ) - - def test_download_raw_predictions_iter__relevant_filenames_artifact_id( - self, - mocker: MockerFixture, - ) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", - side_effect=[response], - ) - assert list( - client.download_raw_predictions_iter( - task_name="task", - run_id="run-id", - relevant_filenames_artifact_id="relevant-filenames", - ) - ) == [ - ("file1", "url1"), - ("file2", "url2"), - ] - client._datasources_api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id.assert_called_once_with( - dataset_id="dataset-id", - task_name="task", - var_from=0, - to=mocker.ANY, - relevant_filenames_run_id="run-id", - relevant_filenames_artifact_id="relevant-filenames", - use_redirected_read_url=False, - ) - - # should raise ValueError when only run_id is given - with pytest.raises(ValueError): - next( - client.download_raw_predictions_iter(task_name="task", run_id="run-id") - ) - - # should raise ValueError when only relevant_filenames_artifact_id is given - with pytest.raises(ValueError): - next( - client.download_raw_predictions_iter( - task_name="task", - relevant_filenames_artifact_id="relevant-filenames", - ) - ) - - def test_download_raw_metadata(self, mocker: MockerFixture) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", - side_effect=[response], - ) - assert client.download_raw_metadata() == [ - ("file1", "url1"), - ("file2", "url2"), - ] - - def test_download_raw_metadata_iter(self, mocker: MockerFixture) -> None: - response_1 = DatasourceRawSamplesData( - hasMore=True, - cursor="cursor1", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - response_2 = DatasourceRawSamplesData( - hasMore=False, - cursor="cursor2", - data=[ - DatasourceRawSamplesDataRow(fileName="file3", readUrl="url3"), - DatasourceRawSamplesDataRow(fileName="file4", readUrl="url4"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", - side_effect=[response_1, response_2], - ) - assert list(client.download_raw_metadata_iter()) == [ - ("file1", "url1"), - ("file2", "url2"), - ("file3", "url3"), - ("file4", "url4"), - ] - client._datasources_api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id.assert_has_calls( - [ - mocker.call( - dataset_id="dataset-id", - var_from=0, - to=mocker.ANY, - use_redirected_read_url=False, - ), - mocker.call( - dataset_id="dataset-id", - cursor="cursor1", - use_redirected_read_url=False, - ), - ] - ) - - def test_download_raw_metadata_iter__relevant_filenames_artifact_id( - self, mocker: MockerFixture - ) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", - side_effect=[response], - ) - assert list( - client.download_raw_metadata_iter( - run_id="run-id", - relevant_filenames_artifact_id="relevant-filenames", - ) - ) == [ - ("file1", "url1"), - ("file2", "url2"), - ] - client._datasources_api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id.assert_called_once_with( - dataset_id="dataset-id", - var_from=0, - to=mocker.ANY, - relevant_filenames_run_id="run-id", - relevant_filenames_artifact_id="relevant-filenames", - use_redirected_read_url=False, - ) - - # should raise ValueError when only run_id is given - with pytest.raises(ValueError): - next(client.download_raw_metadata_iter(run_id="run-id")) - - # should raise ValueError when only relevant_filenames_artifact_id is given - with pytest.raises(ValueError): - next( - client.download_raw_metadata_iter( - relevant_filenames_artifact_id="relevant-filenames", - ) - ) - - def test_download_new_raw_samples(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - client.get_processed_until_timestamp = mocker.MagicMock(return_value=2) - mocker.patch("time.time", return_value=5) - mocker.patch.object(client, "download_raw_samples") - mocker.patch.object(client, "update_processed_until_timestamp") - client.download_new_raw_samples() - client.download_raw_samples.assert_called_once_with( - from_=2 + 1, - to=5, - relevant_filenames_file_name=None, - use_redirected_read_url=False, - ) - client.update_processed_until_timestamp.assert_called_once_with(timestamp=5) - - def test_download_new_raw_samples__from_beginning( - self, mocker: MockerFixture - ) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - client.get_processed_until_timestamp = mocker.MagicMock(return_value=2) - mocker.patch("time.time", return_value=5) - mocker.patch.object(client, "download_raw_samples") - mocker.patch.object(client, "update_processed_until_timestamp") - client.download_new_raw_samples() - client.download_raw_samples.assert_called_once_with( - from_=3, - to=5, - relevant_filenames_file_name=None, - use_redirected_read_url=False, - ) - client.update_processed_until_timestamp.assert_called_once_with(timestamp=5) - - def test_get_processed_until_timestamp(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_datasource_processed_until_timestamp_by_dataset_id", - return_value=DatasourceProcessedUntilTimestampResponse( - processedUntilTimestamp=5 - ), - ) - assert client.get_processed_until_timestamp() == 5 - client._datasources_api.get_datasource_processed_until_timestamp_by_dataset_id.assert_called_once_with( - dataset_id="dataset-id" - ) - - def test_update_processed_until_timestamp(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_processed_until_timestamp_by_dataset_id", - ) - client.update_processed_until_timestamp(timestamp=10) - kwargs = client._datasources_api.update_datasource_processed_until_timestamp_by_dataset_id.call_args[ - 1 - ] - assert kwargs["dataset_id"] == "dataset-id" - assert ( - kwargs[ - "datasource_processed_until_timestamp_request" - ].processed_until_timestamp - == 10 - ) - - def test_set_azure_config(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_by_dataset_id", - ) - client.set_azure_config( - container_name="my-container/name", - account_name="my-account-name", - sas_token="my-sas-token", - thumbnail_suffix=".lightly/thumbnails/[filename]-thumb-[extension]", - ) - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - assert isinstance( - kwargs["datasource_config"].actual_instance, DatasourceConfigAzure - ) - - def test_set_gcs_config(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_by_dataset_id", - ) - client.set_gcs_config( - resource_path="gs://my-bucket/my-dataset", - project_id="my-project-id", - credentials="my-credentials", - thumbnail_suffix=".lightly/thumbnails/[filename]-thumb-[extension]", - ) - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - assert isinstance( - kwargs["datasource_config"].actual_instance, DatasourceConfigGCS - ) - - def test_set_local_config(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_by_dataset_id", - ) - client.set_local_config( - web_server_location="http://localhost:1234", - relative_path="path/to/my/data", - thumbnail_suffix=".lightly/thumbnails/[filename]-thumb-[extension]", - purpose=DatasourcePurpose.INPUT, - ) - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - datasource_config = kwargs["datasource_config"].actual_instance - assert isinstance(datasource_config, DatasourceConfigLOCAL) - assert datasource_config.type == "LOCAL" - assert datasource_config.web_server_location == "http://localhost:1234" - assert datasource_config.full_path == "path/to/my/data" - assert ( - datasource_config.thumb_suffix - == ".lightly/thumbnails/[filename]-thumb-[extension]" - ) - assert datasource_config.purpose == DatasourcePurpose.INPUT - - # Test defaults - client.set_local_config() - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - datasource_config = kwargs["datasource_config"].actual_instance - assert isinstance(datasource_config, DatasourceConfigLOCAL) - assert datasource_config.type == "LOCAL" - assert datasource_config.web_server_location == "http://localhost:3456" - assert datasource_config.full_path == "" - assert ( - datasource_config.thumb_suffix - == ".lightly/thumbnails/[filename]_thumb.[extension]" - ) - assert datasource_config.purpose == DatasourcePurpose.INPUT_OUTPUT - - def test_set_s3_config(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_by_dataset_id", - ) - client.set_s3_config( - resource_path="s3://my-bucket/my-dataset", - thumbnail_suffix=".lightly/thumbnails/[filename]-thumb-[extension]", - region="eu-central-1", - access_key="my-access-key", - secret_access_key="my-secret-access-key", - ) - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - assert isinstance( - kwargs["datasource_config"].actual_instance, DatasourceConfigS3 - ) - - def test_set_s3_delegated_access_config(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "update_datasource_by_dataset_id", - ) - client.set_s3_delegated_access_config( - resource_path="s3://my-bucket/my-dataset", - thumbnail_suffix=".lightly/thumbnails/[filename]-thumb-[extension]", - region="eu-central-1", - role_arn="arn:aws:iam::000000000000:role.test", - external_id="my-external-id", - ) - kwargs = client._datasources_api.update_datasource_by_dataset_id.call_args[1] - assert isinstance( - kwargs["datasource_config"].actual_instance, - DatasourceConfigS3DelegatedAccess, - ) - - def test_get_prediction_read_url(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_prediction_file_read_url_from_datasource_by_dataset_id", - return_value="read-url", - ) - assert client.get_prediction_read_url(filename="test.json") == "read-url" - client._datasources_api.get_prediction_file_read_url_from_datasource_by_dataset_id.assert_called_once_with( - dataset_id="dataset-id", file_name="test.json" - ) - - def test_get_custom_embedding_read_url(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - mocker.patch.object( - client._datasources_api, - "get_custom_embedding_file_read_url_from_datasource_by_dataset_id", - return_value="read-url", - ) - assert ( - client.get_custom_embedding_read_url(filename="embeddings.csv") - == "read-url" - ) - client._datasources_api.get_custom_embedding_file_read_url_from_datasource_by_dataset_id.assert_called_once_with( - dataset_id="dataset-id", file_name="embeddings.csv" - ) - - def test_list_datasource_permissions(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - client._datasources_api.verify_datasource_by_dataset_id = mocker.MagicMock( - return_value=DatasourceConfigVerifyData( - canRead=True, - canWrite=True, - canList=False, - canOverwrite=True, - errors=None, - ), - ) - assert client.list_datasource_permissions() == { - "can_read": True, - "can_write": True, - "can_list": False, - "can_overwrite": True, - } - - def test_list_datasource_permissions__error(self, mocker: MockerFixture) -> None: - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - client._datasources_api.verify_datasource_by_dataset_id = mocker.MagicMock( - return_value=DatasourceConfigVerifyData( - canRead=True, - canWrite=True, - canList=False, - canOverwrite=True, - errors=DatasourceConfigVerifyDataErrors( - canRead=None, - canWrite=None, - canList="error message", - canOverwrite=None, - ), - ), - ) - assert client.list_datasource_permissions() == { - "can_read": True, - "can_write": True, - "can_list": False, - "can_overwrite": True, - "errors": { - "can_list": "error message", - }, - } - - def test__download_raw_files(self, mocker: MockerFixture) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - download_function = mocker.MagicMock(side_effect=[response]) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - assert client._download_raw_files( - download_function=download_function, - ) == [("file1", "url1"), ("file2", "url2")] - - def test__download_raw_files_iter(self, mocker: MockerFixture) -> None: - response_1 = DatasourceRawSamplesData( - hasMore=True, - cursor="cursor1", - data=[ - DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - DatasourceRawSamplesDataRow(fileName="file2", readUrl="url2"), - ], - ) - response_2 = DatasourceRawSamplesData( - hasMore=False, - cursor="cursor2", - data=[ - DatasourceRawSamplesDataRow(fileName="file3", readUrl="url3"), - DatasourceRawSamplesDataRow(fileName="file4", readUrl="url4"), - ], - ) - download_function = mocker.MagicMock(side_effect=[response_1, response_2]) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - progress_bar = mocker.spy(tqdm, "tqdm") - assert list( - client._download_raw_files_iter( - download_function=download_function, - from_=0, - to=5, - relevant_filenames_file_name="relevant-filenames", - use_redirected_read_url=True, - progress_bar=progress_bar, - foo="bar", - ) - ) == [ - ("file1", "url1"), - ("file2", "url2"), - ("file3", "url3"), - ("file4", "url4"), - ] - download_function.assert_has_calls( - [ - mocker.call( - dataset_id="dataset-id", - var_from=0, - to=5, - relevant_filenames_file_name="relevant-filenames", - use_redirected_read_url=True, - foo="bar", - ), - mocker.call( - dataset_id="dataset-id", - cursor="cursor1", - relevant_filenames_file_name="relevant-filenames", - use_redirected_read_url=True, - foo="bar", - ), - ] - ) - assert progress_bar.update.call_count == 4 - - def test__download_raw_files_iter__no_relevant_filenames( - self, mocker: MockerFixture - ) -> None: - response = DatasourceRawSamplesData(hasMore=False, cursor="", data=[]) - download_function = mocker.MagicMock(side_effect=[response]) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - list(client._download_raw_files_iter(download_function=download_function)) - assert "relevant_filenames_file_name" not in download_function.call_args[1] - - def test__download_raw_files_iter__warning(self, mocker: MockerFixture) -> None: - response = DatasourceRawSamplesData( - hasMore=False, - cursor="", - data=[ - DatasourceRawSamplesDataRow(fileName="/file1", readUrl="url1"), - ], - ) - download_function = mocker.MagicMock(side_effect=[response]) - client = ApiWorkflowClient(token="abc", dataset_id="dataset-id") - with pytest.warns(UserWarning, match="Absolute file paths like /file1"): - list(client._download_raw_files_iter(download_function=download_function)) - - -def test__sample_unseen_and_valid() -> None: - with pytest.warns(UserWarning, match="Absolute file paths like /file1"): - assert not api_workflow_datasources._sample_unseen_and_valid( - sample=DatasourceRawSamplesDataRow(fileName="/file1", readUrl="url1"), - relevant_filenames_file_name=None, - listed_filenames=set(), - ) - - with pytest.warns(UserWarning, match="Using dot notation"): - assert not api_workflow_datasources._sample_unseen_and_valid( - sample=DatasourceRawSamplesDataRow(fileName="./file1", readUrl="url1"), - relevant_filenames_file_name=None, - listed_filenames=set(), - ) - - with pytest.warns(UserWarning, match="Duplicate filename file1"): - assert not api_workflow_datasources._sample_unseen_and_valid( - sample=DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - relevant_filenames_file_name=None, - listed_filenames={"file1"}, - ) - - assert api_workflow_datasources._sample_unseen_and_valid( - sample=DatasourceRawSamplesDataRow(fileName="file1", readUrl="url1"), - relevant_filenames_file_name=None, - listed_filenames=set(), - ) diff --git a/tests/api_workflow/test_api_workflow_download_dataset.py b/tests/api_workflow/test_api_workflow_download_dataset.py deleted file mode 100644 index da695e0e9..000000000 --- a/tests/api_workflow/test_api_workflow_download_dataset.py +++ /dev/null @@ -1,293 +0,0 @@ -import pytest -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_download_dataset -from lightly.openapi_generated.swagger_client.models import ( - DatasetData, - DatasetEmbeddingData, - DatasetType, - ImageType, - TagData, -) -from tests.api_workflow import utils - - -def test_download_dataset__no_image(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - mocked_get_dataset_by_id = mocker.MagicMock( - return_value=DatasetData( - name="dataset", - id=dataset_id, - user_id=utils.generate_id(), - last_modified_at=0, - type=DatasetType.IMAGES, - img_type=ImageType.META, - size_in_bytes=-1, - n_samples=-1, - created_at=0, - ) - ) - mocked_api.get_dataset_by_id = mocked_get_dataset_by_id - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._datasets_api = mocked_api - with pytest.raises(ValueError) as exception: - client.download_dataset(output_dir="path/to/dir") - assert ( - str(exception.value) - == f"Dataset with id {dataset_id} has no downloadable images!" - ) - - -def test_download_dataset__tag_missing(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - mocked_get_dataset_by_id = mocker.MagicMock( - return_value=DatasetData( - name="dataset", - id=utils.generate_id(), - user_id=utils.generate_id(), - last_modified_at=0, - type=DatasetType.IMAGES, - img_type=ImageType.FULL, - size_in_bytes=-1, - n_samples=-1, - created_at=0, - ) - ) - mocked_api.get_dataset_by_id = mocked_get_dataset_by_id - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=[]) - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._datasets_api = mocked_api - with pytest.raises(ValueError) as exception: - client.download_dataset(output_dir="path/to/dir", tag_name="some-tag") - assert str(exception.value) == "Dataset with id dataset-id has no tag some-tag!" - - -def test_download_dataset__ok(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - - mocked_get_dataset_by_id = mocker.MagicMock( - return_value=DatasetData( - name="dataset", - id=dataset_id, - user_id=utils.generate_id(), - last_modified_at=0, - type=DatasetType.IMAGES, - img_type=ImageType.FULL, - size_in_bytes=-1, - n_samples=-1, - created_at=0, - ) - ) - mocked_datasets_api = mocker.MagicMock() - mocked_datasets_api.get_dataset_by_id = mocked_get_dataset_by_id - - mocked_get_sample_mappings_by_dataset_id = mocker.MagicMock(return_value=[1]) - mocked_mappings_api = mocker.MagicMock() - mocked_mappings_api.get_sample_mappings_by_dataset_id = ( - mocked_get_sample_mappings_by_dataset_id - ) - - mocked_get_sample_image_read_url_by_id = mocker.MagicMock( - side_effect=RuntimeError("some error") - ) - mocked_samples_api = mocker.MagicMock() - mocked_samples_api.get_sample_image_read_url_by_id = ( - mocked_get_sample_image_read_url_by_id - ) - - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, - "get_all_tags", - return_value=[ - TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name="some-tag", - tot_size=4, - created_at=1577836800, - changes=[], - ) - ], - ) - mocker.patch.object( - ApiWorkflowClient, "get_filenames", return_value=[f"file{i}" for i in range(3)] - ) - mocker.patch.object(api_workflow_download_dataset, "_get_image_from_read_url") - mocker.patch.object(api_workflow_download_dataset, "_make_dir_and_save_image") - mocked_warning = mocker.patch("warnings.warn") - mocker.patch("tqdm.tqdm") - mocked_executor = mocker.patch.object( - api_workflow_download_dataset, "ThreadPoolExecutor" - ) - mocked_executor.return_value.__enter__.return_value.map = ( - lambda fn, iterables, **_: map(fn, iterables) - ) - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._datasets_api = mocked_datasets_api - client._mappings_api = mocked_mappings_api - client._samples_api = mocked_samples_api - - client.download_dataset(output_dir="path/to/dir", tag_name="some-tag") - - assert mocked_warning.call_count == 2 - warning_text = [str(call_args[0][0]) for call_args in mocked_warning.call_args_list] - assert warning_text == [ - "Downloading of image file0 failed with error some error", - "Warning: Unsuccessful download! Failed at image: 0", - ] - - -def test_get_embedding_data_by_name(mocker: MockerFixture) -> None: - embedding_0 = DatasetEmbeddingData( - id=utils.generate_id(), - name="embedding_0", - created_at=0, - is_processed=False, - ) - embedding_1 = DatasetEmbeddingData( - id=utils.generate_id(), - name="embedding_1", - created_at=1, - is_processed=False, - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, - "get_all_embedding_data", - return_value=[embedding_0, embedding_1], - ) - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - - embedding = client.get_embedding_data_by_name(name="embedding_0") - assert embedding == embedding_0 - - -def test_get_embedding_data_by_name__no_embedding_with_name( - mocker: MockerFixture, -) -> None: - embedding = DatasetEmbeddingData( - id=utils.generate_id(), - name="embedding", - created_at=0, - is_processed=False, - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_all_embedding_data", return_value=[embedding] - ) - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - with pytest.raises(ValueError) as exception: - client.get_embedding_data_by_name(name="other_embedding") - assert str(exception.value) == ( - "There are no embeddings with name 'other_embedding' " - "for dataset with id 'dataset-id'." - ) - - -def test_download_embeddings_csv_by_id(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_download = mocker.patch.object( - api_workflow_download_dataset.download, "download_and_write_file" - ) - mocked_api = mocker.MagicMock() - mocked_get_embeddings_csv_read_url_by_id = mocker.MagicMock(return_value="read_url") - mocked_api.get_embeddings_csv_read_url_by_id = ( - mocked_get_embeddings_csv_read_url_by_id - ) - mocker.patch.object( - api_workflow_download_dataset, - "_get_latest_default_embedding_data", - return_value=None, - ) - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._embeddings_api = mocked_api - - client.download_embeddings_csv_by_id( - embedding_id="embedding_id", - output_path="embeddings.csv", - ) - mocked_get_embeddings_csv_read_url_by_id.assert_called_once_with( - dataset_id="dataset-id", - embedding_id="embedding_id", - ) - mocked_download.assert_called_once_with( - url="read_url", - output_path="embeddings.csv", - ) - - -def test_download_embeddings_csv(mocker: MockerFixture) -> None: - embedding_id = utils.generate_id() - - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mock_get_all_embedding_data = mocker.patch.object( - api_workflow_download_dataset, - "_get_latest_default_embedding_data", - return_value=DatasetEmbeddingData( - id=embedding_id, - name="default_20221209_10h45m49s", - created_at=0, - is_processed=False, - ), - ) - mocker.patch.object(ApiWorkflowClient, "get_all_embedding_data") - mock_download_embeddings_csv_by_id = mocker.patch.object( - ApiWorkflowClient, - "download_embeddings_csv_by_id", - ) - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client.download_embeddings_csv(output_path="embeddings.csv") - mock_get_all_embedding_data.assert_called_once() - mock_download_embeddings_csv_by_id.assert_called_once_with( - embedding_id=embedding_id, - output_path="embeddings.csv", - ) - - -def test_download_embeddings_csv__no_default_embedding(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_all_embedding_data = mocker.patch.object( - ApiWorkflowClient, "get_all_embedding_data", return_value=[] - ) - mocker.patch.object( - api_workflow_download_dataset, - "_get_latest_default_embedding_data", - return_value=None, - ) - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - with pytest.raises(RuntimeError) as exception: - client.download_embeddings_csv(output_path="embeddings.csv") - assert ( - str(exception.value) - == "Could not find embeddings for dataset with id 'dataset-id'." - ) - mocked_get_all_embedding_data.assert_called_once() - - -def test__get_latest_default_embedding_data__no_default_embedding() -> None: - custom_embedding = DatasetEmbeddingData( - id=utils.generate_id(), - name="custom-name", - created_at=0, - is_processed=False, - ) - embedding = api_workflow_download_dataset._get_latest_default_embedding_data( - embeddings=[custom_embedding] - ) - assert embedding is None diff --git a/tests/api_workflow/test_api_workflow_export.py b/tests/api_workflow/test_api_workflow_export.py deleted file mode 100644 index de5af5e8e..000000000 --- a/tests/api_workflow/test_api_workflow_export.py +++ /dev/null @@ -1,309 +0,0 @@ -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_export -from lightly.api import utils as api_utils -from lightly.openapi_generated.swagger_client.models import FileNameFormat, TagData -from tests.api_workflow import utils - - -def _get_tag(dataset_id: str, tag_name: str) -> TagData: - return TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name=tag_name, - tot_size=4, - created_at=1577836800, - changes=[], - ) - - -def test_export_filenames_by_tag_id(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - mocked_paginate = mocker.patch.object( - api_utils, - "paginate_endpoint", - side_effect=[iter(["file0\nfile1"])], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._tags_api = mocked_api - data = client.export_filenames_by_tag_id(tag_id="tag_id") - - assert data == "file0\nfile1" - mocked_paginate.assert_called_once_with( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - ) - - -def test_export_filenames_by_tag_id__two_pages(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - mocked_paginate = mocker.patch.object( - api_utils, - "paginate_endpoint", - side_effect=[ - # Simulate two pages. - iter(["file0\nfile1", "file2\nfile3"]) - ], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._tags_api = mocked_api - data = client.export_filenames_by_tag_id(tag_id="tag_id") - - assert data == "file0\nfile1\nfile2\nfile3" - mocked_paginate.assert_called_once_with( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - ) - - -def test_export_filenames_and_read_urls_by_tag_id(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - mocked_paginate = mocker.patch.object( - api_utils, - "paginate_endpoint", - side_effect=[ - iter(["file0\nfile1"]), - iter(["read_url0\nread_url1"]), - iter(["datasource_url0\ndatasource_url1"]), - ], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._tags_api = mocked_api - data = client.export_filenames_and_read_urls_by_tag_id(tag_id="tag_id") - - assert data == [ - { - "fileName": "file0", - "readUrl": "read_url0", - "datasourceUrl": "datasource_url0", - }, - { - "fileName": "file1", - "readUrl": "read_url1", - "datasourceUrl": "datasource_url1", - }, - ] - mocked_paginate.assert_has_calls( - [ - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.NAME, - ), - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.REDIRECTED_READ_URL, - ), - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.DATASOURCE_FULL, - ), - ] - ) - - -def test_export_filenames_and_read_urls_by_tag_id__two_pages( - mocker: MockerFixture, -) -> None: - dataset_id = utils.generate_id() - mocked_paginate = mocker.patch.object( - api_utils, - "paginate_endpoint", - side_effect=[ - # Simulate two pages. - iter(["file0\nfile1", "file2\nfile3"]), - iter(["read_url0\nread_url1", "read_url2\nread_url3"]), - iter( - ["datasource_url0\ndatasource_url1", "datasource_url2\ndatasource_url3"] - ), - ], - ) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._tags_api = mocked_api - data = client.export_filenames_and_read_urls_by_tag_id(tag_id="tag_id") - - assert data == [ - { - "fileName": "file0", - "readUrl": "read_url0", - "datasourceUrl": "datasource_url0", - }, - { - "fileName": "file1", - "readUrl": "read_url1", - "datasourceUrl": "datasource_url1", - }, - { - "fileName": "file2", - "readUrl": "read_url2", - "datasourceUrl": "datasource_url2", - }, - { - "fileName": "file3", - "readUrl": "read_url3", - "datasourceUrl": "datasource_url3", - }, - ] - mocked_paginate.assert_has_calls( - [ - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.NAME, - ), - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.REDIRECTED_READ_URL, - ), - mocker.call( - mocked_api.export_tag_to_basic_filenames, - dataset_id=dataset_id, - tag_id="tag_id", - file_name_format=FileNameFormat.DATASOURCE_FULL, - ), - ] - ) - - -def test_export_filenames_by_tag_name(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tag_name = "some-tag" - tag = _get_tag(dataset_id=dataset_id, tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_tag = mocker.patch.object( - ApiWorkflowClient, "get_tag_by_name", return_value=tag - ) - mocked_export = mocker.patch.object(ApiWorkflowClient, "export_filenames_by_tag_id") - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client.export_filenames_by_tag_name(tag_name) - mocked_get_tag.assert_called_once_with(tag_name) - mocked_export.assert_called_once_with(tag.id) - - -def test_export_label_box_data_rows_by_tag_id(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_paginate = mocker.patch.object( - api_workflow_export.utils, "paginate_endpoint" - ) - mocked_api = mocker.MagicMock() - mocked_warning = mocker.patch("warnings.warn") - - client = ApiWorkflowClient() - client._dataset_id = utils.generate_id() - client._tags_api = mocked_api - client.export_label_box_data_rows_by_tag_id(tag_id="tag_id") - mocked_paginate.assert_called_once() - call_args = mocked_paginate.call_args[0] - assert call_args[0] == mocked_api.export_tag_to_label_box_data_rows - warning_text = str(mocked_warning.call_args[0][0]) - assert warning_text == ( - "This method exports data in the deprecated Labelbox v3 format and " - "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_id " - "to export data in the Labelbox v4 format instead." - ) - - -def test_export_label_box_data_rows_by_tag_name(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tag_name = "some-tag" - tag = _get_tag(dataset_id=dataset_id, tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_tag = mocker.patch.object( - ApiWorkflowClient, "get_tag_by_name", return_value=tag - ) - mocked_export = mocker.patch.object( - ApiWorkflowClient, "export_label_box_data_rows_by_tag_id" - ) - mocked_warning = mocker.patch("warnings.warn") - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client.export_label_box_data_rows_by_tag_name(tag_name) - mocked_get_tag.assert_called_once_with(tag_name) - mocked_export.assert_called_once_with(tag.id) - warning_text = str(mocked_warning.call_args[0][0]) - assert warning_text == ( - "This method exports data in the deprecated Labelbox v3 format and " - "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_name " - "to export data in the Labelbox v4 format instead." - ) - - -def test_export_label_box_v4_data_rows_by_tag_id(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_paginate = mocker.patch.object( - api_workflow_export.utils, "paginate_endpoint" - ) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = utils.generate_id() - client._tags_api = mocked_api - client.export_label_box_v4_data_rows_by_tag_id(tag_id="tag_id") - mocked_paginate.assert_called_once() - call_args = mocked_paginate.call_args[0] - assert call_args[0] == mocked_api.export_tag_to_label_box_v4_data_rows - - -def test_export_label_box_v4_data_rows_by_tag_name(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tag_name = "some-tag" - tag = _get_tag(dataset_id=dataset_id, tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_tag = mocker.patch.object( - ApiWorkflowClient, "get_tag_by_name", return_value=tag - ) - mocked_export = mocker.patch.object( - ApiWorkflowClient, "export_label_box_v4_data_rows_by_tag_id" - ) - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client.export_label_box_v4_data_rows_by_tag_name(tag_name) - mocked_get_tag.assert_called_once_with(tag_name) - mocked_export.assert_called_once_with(tag.id) - - -def test_export_label_studio_tasks_by_tag_name(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tag_name = "some-tag" - tag = _get_tag(dataset_id=dataset_id, tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_tag = mocker.patch.object( - ApiWorkflowClient, "get_tag_by_name", return_value=tag - ) - mocked_export = mocker.patch.object( - ApiWorkflowClient, "export_label_studio_tasks_by_tag_id" - ) - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client.export_label_studio_tasks_by_tag_name(tag_name) - mocked_get_tag.assert_called_once_with(tag_name) - mocked_export.assert_called_once_with(tag.id) diff --git a/tests/api_workflow/test_api_workflow_predictions.py b/tests/api_workflow/test_api_workflow_predictions.py deleted file mode 100644 index 82e6084c6..000000000 --- a/tests/api_workflow/test_api_workflow_predictions.py +++ /dev/null @@ -1,71 +0,0 @@ -from unittest.mock import MagicMock, call - -from lightly.api import ApiWorkflowClient -from lightly.openapi_generated.swagger_client.api import PredictionsApi -from lightly.openapi_generated.swagger_client.models import ( - PredictionSingletonClassification, - PredictionTaskSchema, - PredictionTaskSchemaCategory, - TaskType, -) - - -def test_create_or_update_prediction_task_schema() -> None: - mocked_client = MagicMock(spec=ApiWorkflowClient) - mocked_client.dataset_id = "some_dataset_id" - mocked_client._predictions_api = MagicMock(spec_set=PredictionsApi) - - schema = PredictionTaskSchema.from_dict( - { - "name": "my-object-detection", - "type": TaskType.OBJECT_DETECTION, - "categories": [ - PredictionTaskSchemaCategory(id=0, name="dog").to_dict(), - PredictionTaskSchemaCategory(id=1, name="cat").to_dict(), - ], - } - ) - timestamp = 1234 - ApiWorkflowClient.create_or_update_prediction_task_schema( - self=mocked_client, - schema=schema, - prediction_version_id=timestamp, - ) - - mocked_client._predictions_api.create_or_update_prediction_task_schema_by_dataset_id.assert_called_once_with( - prediction_task_schema=schema, - dataset_id=mocked_client.dataset_id, - prediction_uuid_timestamp=timestamp, - ) - - -def test_create_or_update_prediction() -> None: - mocked_client = MagicMock(spec=ApiWorkflowClient) - mocked_client.dataset_id = "some_dataset_id" - mocked_client._predictions_api = MagicMock(spec_set=PredictionsApi) - - prediction_singletons = [ - PredictionSingletonClassification( - type="CLASSIFICATION", - taskName="my-task", - categoryId=1, - score=0.9, - probabilities=[0.1, 0.2, 0.3, 0.4], - ) - ] - - sample_id = "some_sample_id" - timestamp = 1234 - ApiWorkflowClient.create_or_update_prediction( - self=mocked_client, - sample_id=sample_id, - prediction_singletons=prediction_singletons, - prediction_version_id=timestamp, - ) - - mocked_client._predictions_api.create_or_update_prediction_by_sample_id.assert_called_once_with( - prediction_singleton=prediction_singletons, - dataset_id=mocked_client.dataset_id, - sample_id=sample_id, - prediction_uuid_timestamp=timestamp, - ) diff --git a/tests/api_workflow/test_api_workflow_selection.py b/tests/api_workflow/test_api_workflow_selection.py deleted file mode 100644 index 73147fd03..000000000 --- a/tests/api_workflow/test_api_workflow_selection.py +++ /dev/null @@ -1,229 +0,0 @@ -from typing import List - -import pytest -from pytest_mock import MockerFixture - -from lightly.active_learning.config.selection_config import SelectionConfig -from lightly.api import ApiWorkflowClient, api_workflow_selection -from lightly.openapi_generated.swagger_client.models import ( - JobResultType, - JobState, - JobStatusData, - JobStatusDataResult, - SamplingCreateRequest, - SamplingMethod, - TagData, -) -from tests.api_workflow import utils - - -def _get_tags(dataset_id: str, tag_name: str = "just-a-tag") -> List[TagData]: - return [ - TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=None, - bit_mask_data="0x1", - name=tag_name, - tot_size=4, - created_at=1577836800, - changes=[], - ) - ] - - -def _get_sampling_create_request(tag_name: str = "new-tag") -> SamplingCreateRequest: - return SamplingCreateRequest( - new_tag_name=tag_name, - method=SamplingMethod.RANDOM, - config={}, - ) - - -def test_selection__tag_exists(mocker: MockerFixture) -> None: - tag_name = "some-tag" - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, - "get_all_tags", - return_value=_get_tags(dataset_id=utils.generate_id(), tag_name=tag_name), - ) - - client = ApiWorkflowClient() - with pytest.raises(RuntimeError) as exception: - client.selection(selection_config=SelectionConfig(name=tag_name)) - - assert ( - str(exception.value) == "There already exists a tag with tag_name some-tag" - ) - - -def test_selection__no_tags(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=[]) - - client = ApiWorkflowClient() - with pytest.raises(RuntimeError) as exception: - client.selection(selection_config=SelectionConfig(name="some-tag")) - - assert str(exception.value) == "There exists no initial-tag for this dataset." - - -def test_selection(mocker: MockerFixture) -> None: - tag_name = "some-tag" - dataset_id = utils.generate_id() - mocker.patch("time.sleep") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_all_tags", return_value=_get_tags(dataset_id=dataset_id) - ) - - mocker.patch.object( - ApiWorkflowClient, - "_create_selection_create_request", - return_value=_get_sampling_create_request(), - ) - - mocked_selection_api = mocker.MagicMock() - mocked_sampling_response = mocker.MagicMock() - mocked_sampling_response.job_id = utils.generate_id() - mocked_selection_api.trigger_sampling_by_id.return_value = mocked_sampling_response - - mocked_jobs_api = mocker.MagicMock() - mocked_get_job_status = mocker.MagicMock( - return_value=JobStatusData( - id=utils.generate_id(), - wait_time_till_next_poll=1, - created_at=0, - status=JobState.FINISHED, - result=JobStatusDataResult(type=JobResultType.SAMPLING, data="new-tag-id"), - ) - ) - mocked_jobs_api.get_job_status_by_id = mocked_get_job_status - - mocked_tags_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._selection_api = mocked_selection_api - client._jobs_api = mocked_jobs_api - client._tags_api = mocked_tags_api - client._dataset_id = dataset_id - client.embedding_id = "embedding-id" - client.selection(selection_config=SelectionConfig(name=tag_name)) - - mocked_get_job_status.assert_called_once() - mocked_tags_api.get_tag_by_tag_id.assert_called_once_with( - dataset_id=dataset_id, tag_id="new-tag-id" - ) - - -def test_selection__job_failed(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - job_id = "some-job-id" - mocker.patch("time.sleep") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_all_tags", return_value=_get_tags(dataset_id=dataset_id) - ) - - mocker.patch.object( - ApiWorkflowClient, - "_create_selection_create_request", - return_value=_get_sampling_create_request(), - ) - - mocked_selection_api = mocker.MagicMock() - mocked_sampling_response = mocker.MagicMock() - mocked_sampling_response.job_id = job_id - mocked_selection_api.trigger_sampling_by_id.return_value = mocked_sampling_response - - mocked_jobs_api = mocker.MagicMock() - mocked_get_job_status = mocker.MagicMock( - return_value=JobStatusData( - id=utils.generate_id(), - wait_time_till_next_poll=1, - created_at=0, - status=JobState.FAILED, - error="bad job", - ) - ) - mocked_jobs_api.get_job_status_by_id = mocked_get_job_status - - client = ApiWorkflowClient() - client._selection_api = mocked_selection_api - client._jobs_api = mocked_jobs_api - client._dataset_id = dataset_id - client.embedding_id = "embedding-id" - with pytest.raises(RuntimeError) as exception: - client.selection(selection_config=SelectionConfig(name="some-tag")) - assert str(exception.value) == ( - "Selection job with job_id some-job-id failed with error bad job" - ) - - -def test_selection__too_many_errors(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - job_id = "some-job-id" - mocker.patch("time.sleep") - mocked_print = mocker.patch("builtins.print") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, "get_all_tags", return_value=_get_tags(dataset_id=dataset_id) - ) - - mocker.patch.object( - ApiWorkflowClient, - "_create_selection_create_request", - return_value=_get_sampling_create_request(), - ) - - mocked_selection_api = mocker.MagicMock() - mocked_sampling_response = mocker.MagicMock() - mocked_sampling_response.job_id = job_id - mocked_selection_api.trigger_sampling_by_id.return_value = mocked_sampling_response - - mocked_jobs_api = mocker.MagicMock() - mocked_get_job_status = mocker.MagicMock( - side_effect=[Exception("surprise!") for _ in range(20)] - ) - mocked_jobs_api.get_job_status_by_id = mocked_get_job_status - - client = ApiWorkflowClient() - client._selection_api = mocked_selection_api - client._jobs_api = mocked_jobs_api - client._dataset_id = dataset_id - client.embedding_id = "embedding-id" - with pytest.raises(Exception) as exception: - client.selection(selection_config=SelectionConfig(name="some-tag")) - assert str(exception.value) == "surprise!" - mocked_print.assert_called_once_with( - "Selection job with job_id some-job-id could not be started " - "because of error: surprise!" - ) - - -def test_upload_scores(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tags = _get_tags(dataset_id=dataset_id, tag_name="initial-tag") - tag_id = tags[0].id - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object( - ApiWorkflowClient, - "get_all_tags", - return_value=tags, - ) - mocker.patch.object( - api_workflow_selection, "_parse_active_learning_scores", return_value=[1] - ) - mocked_api = mocker.MagicMock() - mocked_create_score = mocked_api.create_or_update_active_learning_score_by_tag_id - - client = ApiWorkflowClient() - client._scores_api = mocked_api - client._dataset_id = dataset_id - - mocked_create_score.reset_mock() - client.upload_scores(al_scores={"score_type": [1, 2, 3]}, query_tag_id=tag_id) - mocked_create_score.assert_called_once() - kwargs = mocked_create_score.call_args[1] - assert kwargs.get("tag_id") == tag_id diff --git a/tests/api_workflow/test_api_workflow_tags.py b/tests/api_workflow/test_api_workflow_tags.py deleted file mode 100644 index 3667355bd..000000000 --- a/tests/api_workflow/test_api_workflow_tags.py +++ /dev/null @@ -1,214 +0,0 @@ -from typing import List, Optional - -import pytest -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient -from lightly.api.api_workflow_tags import TagDoesNotExistError -from lightly.openapi_generated.swagger_client.models import TagCreator, TagData -from tests.api_workflow import utils - - -def _get_tags( - dataset_id: str, tag_name: str = "just-a-tag", prev_tag_id: Optional[str] = None -) -> List[TagData]: - return [ - TagData( - id=utils.generate_id(), - dataset_id=dataset_id, - prev_tag_id=prev_tag_id, - bit_mask_data="0x5", - name=tag_name, - tot_size=4, - created_at=1577836800, - changes=[], - ) - ] - - -def test_create_tag_from_filenames(mocker: MockerFixture) -> None: - dataset_id = utils.generate_id() - tags = _get_tags(dataset_id=dataset_id, tag_name="initial-tag") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=tags) - mocked_get_filenames = mocker.patch.object( - ApiWorkflowClient, "get_filenames", return_value=[f"file{i}" for i in range(3)] - ) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._tags_api = mocked_api - client._dataset_id = dataset_id - client._creator = TagCreator.UNKNOWN - client.create_tag_from_filenames(fnames_new_tag=["file2"], new_tag_name="some-tag") - mocked_get_filenames.assert_called_once() - mocked_api.create_tag_by_dataset_id.assert_called_once() - kwargs = mocked_api.create_tag_by_dataset_id.call_args[1] - # initial-tag is used as prev_tag_id when parent_tag_id is not given - assert kwargs["tag_create_request"].prev_tag_id == tags[0].id - assert kwargs["tag_create_request"].bit_mask_data == "0x4" - - -def test_create_tag_from_filenames__tag_exists(mocker: MockerFixture) -> None: - tag_name = "some-tag" - tags = _get_tags(dataset_id=utils.generate_id(), tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=tags) - - client = ApiWorkflowClient() - - with pytest.raises(RuntimeError) as exception: - client.create_tag_from_filenames(fnames_new_tag=["file"], new_tag_name=tag_name) - assert ( - str(exception.value) == "There already exists a tag with tag_name some-tag" - ) - - -def test_create_tag_from_filenames__no_tags(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=[]) - - client = ApiWorkflowClient() - - with pytest.raises(RuntimeError) as exception: - client.create_tag_from_filenames( - fnames_new_tag=["file"], new_tag_name="some-tag" - ) - assert str(exception.value) == "There exists no initial-tag for this dataset." - - -def test_create_tag_from_filenames__file_not_found(mocker: MockerFixture) -> None: - tags = _get_tags(dataset_id=utils.generate_id(), tag_name="initial-tag") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=tags) - mocked_get_filenames = mocker.patch.object( - ApiWorkflowClient, "get_filenames", return_value=[f"file{i}" for i in range(3)] - ) - - client = ApiWorkflowClient() - with pytest.raises(RuntimeError) as exception: - client.create_tag_from_filenames( - fnames_new_tag=["some-file"], new_tag_name="some-tag" - ) - assert str(exception.value) == ( - "An error occured when creating the new subset! " - "Out of the 1 filenames you provided " - "to create a new tag, only 0 have been found on the server. " - "Make sure you use the correct filenames. " - "Valid filename example from the dataset: file0" - ) - mocked_get_filenames.assert_called_once() - - -def test_get_filenames_in_tag(mocker: MockerFixture) -> None: - tag = _get_tags(dataset_id=utils.generate_id())[0] - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_filenames = mocker.patch.object( - ApiWorkflowClient, "get_filenames", return_value=[f"file{i}" for i in range(3)] - ) - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - result = client.get_filenames_in_tag(tag_data=tag) - assert result == ["file0", "file2"] - mocked_get_filenames.assert_called_once() - - -def test_get_filenames_in_tag__filenames_given(mocker: MockerFixture) -> None: - tag = _get_tags(dataset_id=utils.generate_id())[0] - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_filenames = mocker.patch.object(ApiWorkflowClient, "get_filenames") - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - result = client.get_filenames_in_tag( - tag_data=tag, filenames_on_server=[f"new-file-{i}" for i in range(3)] - ) - assert result == ["new-file-0", "new-file-2"] - mocked_get_filenames.assert_not_called() - - -def test_get_filenames_in_tag__exclude_parent_tag(mocker: MockerFixture) -> None: - prev_tag_id = utils.generate_id() - dataset_id = utils.generate_id() - tag = _get_tags(dataset_id=dataset_id, prev_tag_id=prev_tag_id)[0] - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_get_filenames = mocker.patch.object( - ApiWorkflowClient, "get_filenames", return_value=[f"file{i}" for i in range(3)] - ) - mocked_response = mocker.MagicMock() - mocked_response.bit_mask_data = "0x2" - mocked_tag_arithmetics = mocker.MagicMock(return_value=mocked_response) - mocked_api = mocker.MagicMock() - mocked_api.perform_tag_arithmetics_bitmask = mocked_tag_arithmetics - - client = ApiWorkflowClient() - client._dataset_id = dataset_id - client._tags_api = mocked_api - result = client.get_filenames_in_tag(tag_data=tag, exclude_parent_tag=True) - assert result == ["file1"] - mocked_get_filenames.assert_called_once() - mocked_tag_arithmetics.assert_called_once() - kwargs = mocked_tag_arithmetics.call_args[1] - assert kwargs["dataset_id"] == dataset_id - assert kwargs["tag_arithmetics_request"].tag_id2 == prev_tag_id - - -def test_get_all_tags(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._tags_api = mocked_api - client.get_all_tags() - mocked_api.get_tags_by_dataset_id.assert_called_once_with("dataset-id") - - -def test_get_tag_by_id(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._tags_api = mocked_api - client.get_tag_by_id("tag-id") - mocked_api.get_tag_by_tag_id.assert_called_once_with( - dataset_id="dataset-id", tag_id="tag-id" - ) - - -def test_get_tag_name(mocker: MockerFixture) -> None: - tag_name = "some-tag" - tags = _get_tags(dataset_id=utils.generate_id(), tag_name=tag_name) - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=tags) - mocked_get_tag = mocker.patch.object(ApiWorkflowClient, "get_tag_by_id") - - client = ApiWorkflowClient() - client.get_tag_by_name(tag_name=tag_name) - mocked_get_tag.assert_called_once_with(tags[0].id) - - -def test_get_tag_name__nonexisting(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocker.patch.object(ApiWorkflowClient, "get_all_tags", return_value=[]) - - client = ApiWorkflowClient() - - with pytest.raises(TagDoesNotExistError) as exception: - client.get_tag_by_name(tag_name="some-tag") - assert str(exception.value) == "Your tag_name does not exist: some-tag" - - -def test_delete_tag_by_id(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - mocked_api = mocker.MagicMock() - - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._tags_api = mocked_api - client.delete_tag_by_id("tag-id") - mocked_api.delete_tag_by_tag_id.assert_called_once_with( - dataset_id="dataset-id", tag_id="tag-id" - ) diff --git a/tests/api_workflow/test_api_workflow_upload_custom_metadata.py b/tests/api_workflow/test_api_workflow_upload_custom_metadata.py deleted file mode 100644 index 63f36de37..000000000 --- a/tests/api_workflow/test_api_workflow_upload_custom_metadata.py +++ /dev/null @@ -1,129 +0,0 @@ -from pytest_mock import MockerFixture - -from lightly.api import ApiWorkflowClient, api_workflow_upload_metadata -from lightly.openapi_generated.swagger_client.models import ( - SampleDataModes, - SamplePartialMode, - SampleUpdateRequest, -) -from lightly.utils.io import COCO_ANNOTATION_KEYS -from tests.api_workflow import utils - - -def test_index_custom_metadata_by_filename(mocker: MockerFixture) -> None: - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - custom_metadata = {} - custom_metadata[COCO_ANNOTATION_KEYS.images] = [ - { - COCO_ANNOTATION_KEYS.images_filename: "file0", - COCO_ANNOTATION_KEYS.images_id: "image-id0", - }, - { - COCO_ANNOTATION_KEYS.images_filename: "file1", - COCO_ANNOTATION_KEYS.images_id: "image-id1", - }, - ] - custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata] = [ - {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id2"}, - {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id0"}, - ] - - client = ApiWorkflowClient() - result = client.index_custom_metadata_by_filename(custom_metadata=custom_metadata) - assert result == { - "file0": {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id0"}, - "file1": None, - } - - -def test_upload_custom_metadata(mocker: MockerFixture) -> None: - mocker.patch("tqdm.tqdm") - mocker.patch.object(ApiWorkflowClient, "__init__", return_value=None) - # retry should be called twice: once for get_samples_partial_by_dataset_id - # and once for update_sample_by_id. get_samples_partial_by_dataset_id returns - # only one valid sample file `file1` - dummy_sample = SampleDataModes(id=utils.generate_id(), file_name="file1") - - mocked_paginate_endpoint = mocker.patch.object( - api_workflow_upload_metadata, - "paginate_endpoint", - side_effect=[ - [dummy_sample], - None, - ], - ) - mocked_retry = mocker.patch.object( - api_workflow_upload_metadata, - "retry", - side_effect=[ - [dummy_sample], - None, - ], - ) - mocked_print_warning = mocker.patch.object( - api_workflow_upload_metadata.hipify, "print_as_warning" - ) - mocked_executor = mocker.patch.object( - api_workflow_upload_metadata, "ThreadPoolExecutor" - ) - mocked_executor.return_value.__enter__.return_value.map = ( - lambda fn, iterables, **_: map(fn, iterables) - ) - mocked_samples_api = mocker.MagicMock() - - custom_metadata = {} - custom_metadata[COCO_ANNOTATION_KEYS.images] = [ - { - COCO_ANNOTATION_KEYS.images_filename: "file0", - COCO_ANNOTATION_KEYS.images_id: "image-id0", - }, - { - COCO_ANNOTATION_KEYS.images_filename: "file1", - COCO_ANNOTATION_KEYS.images_id: "image-id1", - }, - ] - custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata] = [ - {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id2"}, - {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id1"}, - {COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id0"}, - ] - client = ApiWorkflowClient() - client._dataset_id = "dataset-id" - client._samples_api = mocked_samples_api - client.upload_custom_metadata(custom_metadata=custom_metadata) - - # Only `file1` is a valid sample - assert mocked_print_warning.call_count == 2 - warning_text = [ - call_args[0][0] for call_args in mocked_print_warning.call_args_list - ] - assert warning_text == [ - ( - "No image found for custom metadata annotation with image_id image-id2. " - "This custom metadata annotation is skipped. " - ), - ( - "You tried to upload custom metadata for a sample with filename {file0}, " - "but a sample with this filename does not exist on the server. " - "This custom metadata annotation is skipped. " - ), - ] - - # First call: get_samples_partial_by_dataset_id - mocked_paginate_endpoint.assert_called_once_with( - mocked_samples_api.get_samples_partial_by_dataset_id, - dataset_id="dataset-id", - mode=SamplePartialMode.FILENAMES, - page_size=25000, - ) - # Second call: update_sample_by_id with the only valid sample - mocked_retry.assert_called_once_with( - mocked_samples_api.update_sample_by_id, - dataset_id="dataset-id", - sample_id=dummy_sample.id, - sample_update_request=SampleUpdateRequest( - custom_meta_data={ - COCO_ANNOTATION_KEYS.custom_metadata_image_id: "image-id1" - } - ), - ) diff --git a/tests/api_workflow/test_api_workflow_upload_embeddings.py b/tests/api_workflow/test_api_workflow_upload_embeddings.py deleted file mode 100644 index a3bb54c2b..000000000 --- a/tests/api_workflow/test_api_workflow_upload_embeddings.py +++ /dev/null @@ -1,183 +0,0 @@ -import os -import tempfile - -import numpy as np - -from lightly.utils import io as io_utils -from tests.api_workflow.mocked_api_workflow_client import MockedApiWorkflowSetup - - -class TestApiWorkflowUploadEmbeddings(MockedApiWorkflowSetup): - def create_fake_embeddings( - self, - n_data, - n_data_start: int = 0, - n_dims: int = 32, - special_name_first_sample: bool = False, - special_char_in_first_filename: str = None, - ): - # create fake embeddings - self.folder_path = tempfile.mkdtemp() - self.path_to_embeddings = os.path.join(self.folder_path, "embeddings.csv") - - self.sample_names = [ - f"img_{i}.jpg" for i in range(n_data_start, n_data_start + n_data) - ] - if special_name_first_sample: - self.sample_names[0] = "bliblablub" - if special_char_in_first_filename: - self.sample_names[0] = ( - f"_{special_char_in_first_filename}" f"{self.sample_names[0]}" - ) - labels = [0] * len(self.sample_names) - io_utils.save_embeddings( - self.path_to_embeddings, - np.random.randn(n_data, n_dims), - labels, - self.sample_names, - ) - - def t_ester_upload_embedding( - self, - n_data, - n_dims: int = 32, - special_name_first_sample: bool = False, - special_char_in_first_filename: str = None, - name: str = "embedding_xyz", - ): - self.create_fake_embeddings( - n_data, - n_dims=n_dims, - special_name_first_sample=special_name_first_sample, - special_char_in_first_filename=special_char_in_first_filename, - ) - - # perform the workflow to upload the embeddings - self.api_workflow_client.upload_embeddings( - path_to_embeddings_csv=self.path_to_embeddings, name=name - ) - self.api_workflow_client.n_dims_embeddings_on_server = n_dims - - def test_upload_success(self): - n_data = len(self.api_workflow_client._mappings_api.sample_names) - self.t_ester_upload_embedding(n_data=n_data) - filepath_embeddings_sorted = os.path.join( - self.folder_path, "embeddings_sorted.csv" - ) - self.assertFalse(os.path.isfile(filepath_embeddings_sorted)) - - def test_upload_wrong_length(self): - n_data = 42 + len(self.api_workflow_client._mappings_api.sample_names) - with self.assertRaises(ValueError): - self.t_ester_upload_embedding(n_data=n_data) - - def test_upload_wrong_filenames(self): - n_data = len(self.api_workflow_client._mappings_api.sample_names) - with self.assertRaises(ValueError): - self.t_ester_upload_embedding(n_data=n_data, special_name_first_sample=True) - - def test_set_embedding_id_default(self): - self.api_workflow_client.set_embedding_id_to_latest() - embeddings = ( - self.api_workflow_client._embeddings_api.get_embeddings_by_dataset_id( - dataset_id=self.api_workflow_client.dataset_id - ) - ) - self.assertEqual(self.api_workflow_client.embedding_id, embeddings[0].id) - - def test_set_embedding_id_no_embeddings(self): - self.api_workflow_client._embeddings_api.embeddings = [] - with self.assertRaises(RuntimeError): - self.api_workflow_client.set_embedding_id_to_latest() - - def test_upload_existing_embedding(self): - # first upload embeddings - n_data = len(self.api_workflow_client._mappings_api.sample_names) - self.t_ester_upload_embedding(n_data=n_data) - - # create a new set of embeddings - self.create_fake_embeddings(10) - - # mock the embeddings on the server - self.api_workflow_client.n_dims_embeddings_on_server = 32 - - self.api_workflow_client.append_embeddings( - self.path_to_embeddings, - "embedding_id_xyz_2", - ) - - def test_append_embeddings_with_overlap(self): - # mock the embeddings on the server - n_data_server = len(self.api_workflow_client._mappings_api.sample_names) - self.api_workflow_client.n_dims_embeddings_on_server = 32 - - # create new local embeddings overlapping with server embeddings - n_data_start_local = n_data_server // 3 - n_data_local = n_data_server * 2 - self.create_fake_embeddings( - n_data=n_data_local, n_data_start=n_data_start_local - ) - - """ - Assumptions: - n_data_server = 100 - n_data_start_local = 33 - n_data_local = 200 - - Server embeddings file: - filenames: 0 ... 99 - labels: 0 ... 99 - - Local embeddings file: - filenames: 33 ... 232 - labels: 0 ... 0 (all zero) - - Appended embedding file must thus be: - filenames: 0 ... 232 - labels: 0 ... 32 (from server) + 0 ... 0 (from local) - """ - - # append the local embeddings to the server embeddings - self.api_workflow_client.append_embeddings( - self.path_to_embeddings, - "embedding_id_xyz_2", - ) - - # load the new (appended) embeddings - _, labels_appended, filenames_appended = io_utils.load_embeddings( - self.path_to_embeddings - ) - - # define the expected filenames and labels - self.create_fake_embeddings(n_data=n_data_local + n_data_start_local) - _, _, filenames_expected = io_utils.load_embeddings(self.path_to_embeddings) - labels_expected = list(range(n_data_start_local)) + [0] * n_data_local - - # make sure the list of filenames and labels equal - self.assertListEqual(filenames_appended, filenames_expected) - self.assertListEqual(labels_appended, labels_expected) - - def test_append_embeddings_different_shape(self): - # first upload embeddings - n_data = len(self.api_workflow_client._mappings_api.sample_names) - self.t_ester_upload_embedding(n_data=n_data) - - # create a new set of embeddings - self.create_fake_embeddings(10, n_dims=16) # default is 32 - - self.api_workflow_client.n_dims_embeddings_on_server = 32 - - with self.assertRaises(RuntimeError): - self.api_workflow_client.append_embeddings( - self.path_to_embeddings, - "embedding_id_xyz_2", - ) - - def tearDown(self) -> None: - for filename in ["embeddings.csv", "embeddings_sorted.csv"]: - if hasattr(self, "folder_path"): - try: - filepath = os.path.join(self.folder_path, filename) - os.remove(filepath) - except FileNotFoundError: - pass diff --git a/tests/api_workflow/utils.py b/tests/api_workflow/utils.py deleted file mode 100644 index bae4a760d..000000000 --- a/tests/api_workflow/utils.py +++ /dev/null @@ -1,7 +0,0 @@ -import random - -_CHARACTER_SET = "abcdef0123456789" - - -def generate_id(length: int = 24) -> str: - return "".join([random.choice(_CHARACTER_SET) for i in range(length)]) diff --git a/tests/cli/test_cli_crop.py b/tests/cli/test_cli_crop.py deleted file mode 100644 index 9cb07fc4f..000000000 --- a/tests/cli/test_cli_crop.py +++ /dev/null @@ -1,154 +0,0 @@ -import os -import random -import re -import sys -import tempfile - -import hydra -import torchvision -import yaml -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -import lightly -from lightly.data import LightlyDataset -from lightly.utils.bounding_box import BoundingBox -from lightly.utils.cropping.crop_image_by_bounding_boxes import ( - crop_dataset_by_bounding_boxes_and_save, -) -from lightly.utils.cropping.read_yolo_label_file import read_yolo_label_file -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestCLICrop(MockedApiWorkflowSetup): - def setUp(self): - MockedApiWorkflowSetup.setUp(self) - self.create_fake_dataset() - self.create_fake_yolo_labels() - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose( - config_name="config", - overrides=[ - f"input_dir={self.folder_path}", - f"label_dir={self.folder_path_labels}", - f"output_dir={tempfile.mkdtemp()}", - f"label_names_file={self.label_names_file}", - ], - ) - - def create_fake_dataset(self): - n_data = len(self.api_workflow_client.get_filenames()) - self.dataset = torchvision.datasets.FakeData( - size=n_data, image_size=(3, 32, 32) - ) - - self.folder_path = tempfile.mkdtemp() - sample_names = [f"img_{i}.jpg" for i in range(n_data)] - self.sample_names = sample_names - for sample_idx in range(n_data): - data = self.dataset[sample_idx] - path = os.path.join(self.folder_path, sample_names[sample_idx]) - data[0].save(path) - - def create_fake_yolo_labels( - self, no_classes: int = 10, objects_per_image: int = 13 - ): - random.seed(42) - - n_data = len(self.api_workflow_client.get_filenames()) - - self.folder_path_labels = tempfile.mkdtemp() - label_names = [f"img_{i}.txt" for i in range(n_data)] - self.label_names = label_names - for filename_label in label_names: - path = os.path.join(self.folder_path_labels, filename_label) - with open(path, "a") as the_file: - for i in range(objects_per_image): - class_id = random.randint(0, no_classes - 1) - x = random.uniform(0.1, 0.9) - y = random.uniform(0.1, 0.9) - w = random.uniform(0.1, 1.0) - h = random.uniform(0.1, 1.0) - line = f"{class_id} {x} {y} {w} {h}\n" - the_file.write(line) - yaml_dict = {"names": [f"class{i}" for i in range(no_classes)]} - self.label_names_file = tempfile.mktemp( - ".yaml", "data", dir=self.folder_path_labels - ) - with open(self.label_names_file, "w") as file: - yaml.dump(yaml_dict, file) - - def parse_cli_string(self, cli_words: str): - cli_words = cli_words.replace("lightly-crop ", "") - cli_words = re.split("=| ", cli_words) - assert len(cli_words) % 2 == 0 - dict_keys = cli_words[0::2] - dict_values = cli_words[1::2] - for key, value in zip(dict_keys, dict_values): - value = value.strip('"') - value = value.strip("'") - self.cfg[key] = value - - def test_parse_cli_string(self): - cli_string = "lightly-crop label_dir=/blub" - self.parse_cli_string(cli_string) - self.assertEqual(self.cfg["label_dir"], "/blub") - - def test_read_yolo(self): - for f in os.listdir(self.cfg.label_dir): - if f.endswith(".txt"): - filepath = os.path.join(self.cfg.label_dir, f) - read_yolo_label_file(filepath, 0.1) - - def test_crop_dataset_by_bounding_boxes_and_save(self): - dataset = LightlyDataset(self.cfg.input_dir) - output_dir = self.cfg.output_dir - no_files = len(dataset.get_filenames()) - bounding_boxes_list_list = [[BoundingBox(0, 0, 1, 1)]] * no_files - class_indices_list_list = [[1]] * no_files - class_names = ["class_0", "class_1"] - with self.subTest("all_correct"): - crop_dataset_by_bounding_boxes_and_save( - dataset, - output_dir, - bounding_boxes_list_list, - class_indices_list_list, - class_names, - ) - with self.subTest("wrong length of bounding_boxes_list_list"): - with self.assertRaises(ValueError): - crop_dataset_by_bounding_boxes_and_save( - dataset, - output_dir, - bounding_boxes_list_list[:-1], - class_indices_list_list, - class_names, - ) - with self.subTest("wrong internal length of class_indices_list_list"): - with self.assertWarns(UserWarning): - class_indices_list_list[0] *= 2 - crop_dataset_by_bounding_boxes_and_save( - dataset, - output_dir, - bounding_boxes_list_list, - class_indices_list_list, - class_names, - ) - - def test_crop_with_class_names(self): - cli_string = "lightly-crop crop_padding=0.1" - self.parse_cli_string(cli_string) - lightly.cli.crop_cli(self.cfg) - - def test_crop_without_class_names(self): - cli_string = "lightly-crop crop_padding=0.1" - self.parse_cli_string(cli_string) - self.cfg["label_names_file"] = "" - lightly.cli.crop_cli(self.cfg) diff --git a/tests/cli/test_cli_download.py b/tests/cli/test_cli_download.py deleted file mode 100644 index 4e7224c3b..000000000 --- a/tests/cli/test_cli_download.py +++ /dev/null @@ -1,135 +0,0 @@ -import os -import sys -import tempfile -import warnings - -import hydra -import pytest -import torchvision -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -import lightly -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - -_DATASET_ID = "b2a40959eacd1c9a142ba57b" - - -class TestCLIDownload(MockedApiWorkflowSetup): - @classmethod - def setUpClass(cls) -> None: - sys.modules[ - "lightly.cli.download_cli" - ].ApiWorkflowClient = MockedApiWorkflowClient - - def setUp(self): - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose(config_name="config") - - def create_fake_dataset(self, n_data: int = 5): - self.dataset = torchvision.datasets.FakeData( - size=n_data, image_size=(3, 32, 32) - ) - - self.input_dir = tempfile.mkdtemp() - - sample_names = [f"img_{i}.jpg" for i in range(n_data)] - self.sample_names = sample_names - for sample_idx in range(n_data): - data = self.dataset[sample_idx] - path = os.path.join(self.input_dir, sample_names[sample_idx]) - data[0].save(path) - - self.output_dir = tempfile.mkdtemp() - - def parse_cli_string(self, cli_words: str): - cli_words = cli_words.replace("lightly-download ", "") - overrides = cli_words.split(" ") - with initialize(config_path="../../lightly/cli/config/"): - self.cfg = compose( - config_name="config", - overrides=overrides, - ) - - def test_parse_cli_string(self): - cli_string = "lightly-download token='123' dataset_id='XYZ'" - self.parse_cli_string(cli_string) - assert self.cfg["token"] == "123" - assert self.cfg["dataset_id"] == "XYZ" - - def test_download_base(self): - cli_string = f"lightly-download token='123' dataset_id='{_DATASET_ID}'" - self.parse_cli_string(cli_string) - lightly.cli.download_cli(self.cfg) - - def test_download_tag_name(self): - cli_string = f"lightly-download token='123' dataset_id='{_DATASET_ID}' tag_name='selected_tag_xyz'" - self.parse_cli_string(cli_string) - lightly.cli.download_cli(self.cfg) - - def test_download_tag_name_nonexisting(self): - cli_string = f"lightly-download token='123' dataset_id='{_DATASET_ID}' tag_name='nonexisting_xyz'" - self.parse_cli_string(cli_string) - with self.assertRaises(ValueError): - lightly.cli.download_cli(self.cfg) - - def test_download_tag_name_exclude_parent(self): - cli_string = f"lightly-download token='123' dataset_id='{_DATASET_ID}' tag_name='selected_tag_xyz' exclude_parent_tag=True" - self.parse_cli_string(cli_string) - lightly.cli.download_cli(self.cfg) - - def test_download_no_tag_name(self): - # defaults to initial-tag - cli_string = f"lightly-download token='123' dataset_id='{_DATASET_ID}'" - self.parse_cli_string(cli_string) - lightly.cli.download_cli(self.cfg) - - def test_download_no_token(self): - cli_string = ( - f"lightly-download dataset_id='{_DATASET_ID}' tag_name='selected_tag_xyz'" - ) - self.parse_cli_string(cli_string) - with self.assertWarns(UserWarning): - lightly.cli.download_cli(self.cfg) - - def test_download_no_dataset_id(self): - cli_string = "lightly-download token='123' tag_name='selected_tag_xyz'" - self.parse_cli_string(cli_string) - with self.assertWarns(UserWarning): - lightly.cli.download_cli(self.cfg) - - def test_download_copy_from_input_to_output_dir(self): - self.create_fake_dataset(n_data=100) - cli_string = ( - f"lightly-download token='123' dataset_id='{_DATASET_ID}' tag_name='selected_tag_xyz' " - f"input_dir={self.input_dir} output_dir={self.output_dir}" - ) - self.parse_cli_string(cli_string) - lightly.cli.download_cli(self.cfg) - - def test_download_from_tag_with_integer_name(self): - """Test to reproduce issue #575.""" - # use tag name "1000" - cli_string = ( - f"lightly-download token='123' dataset_id='{_DATASET_ID}' tag_name=1000" - ) - self.parse_cli_string(cli_string) - with warnings.catch_warnings(record=True) as record: - lightly.cli.download_cli(self.cfg) - # check if the warning "Tag with name 1000 does not exist" is raised - # if so, the cli string was not parsed correctly - # (i.e. as int instead of str) - self.assertEqual(len(record), 0) - - def tearDown(self) -> None: - try: - os.remove(f"{self.cfg['tag_name']}.txt") - except FileNotFoundError: - pass diff --git a/tests/cli/test_cli_embed.py b/tests/cli/test_cli_embed.py deleted file mode 100644 index 4bcced15e..000000000 --- a/tests/cli/test_cli_embed.py +++ /dev/null @@ -1,72 +0,0 @@ -import os -import re -import sys -import tempfile - -import hydra -import torchvision -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -import lightly -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestCLIEmbed(MockedApiWorkflowSetup): - @classmethod - def setUpClass(cls) -> None: - sys.modules["lightly.cli.embed_cli"].ApiWorkflowClient = MockedApiWorkflowClient - - def setUp(self): - MockedApiWorkflowSetup.setUp(self) - self.create_fake_dataset() - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose( - config_name="config", - overrides=[ - "token='123'", - f"input_dir={self.folder_path}", - "trainer.max_epochs=0", - ], - ) - - def create_fake_dataset(self): - n_data = 16 - self.dataset = torchvision.datasets.FakeData( - size=n_data, image_size=(3, 32, 32) - ) - - self.folder_path = tempfile.mkdtemp() - sample_names = [f"img_{i}.jpg" for i in range(n_data)] - self.sample_names = sample_names - for sample_idx in range(n_data): - data = self.dataset[sample_idx] - path = os.path.join(self.folder_path, sample_names[sample_idx]) - data[0].save(path) - - def test_embed(self): - lightly.cli.embed_cli(self.cfg) - self.assertGreater( - len( - os.getenv( - self.cfg["environment_variable_names"][ - "lightly_last_embedding_path" - ] - ) - ), - 0, - ) - - def tearDown(self) -> None: - for filename in ["embeddings.csv", "embeddings_sorted.csv"]: - try: - os.remove(filename) - except FileNotFoundError: - pass diff --git a/tests/cli/test_cli_get_lighty_config.py b/tests/cli/test_cli_get_lighty_config.py deleted file mode 100644 index e7aa38370..000000000 --- a/tests/cli/test_cli_get_lighty_config.py +++ /dev/null @@ -1,10 +0,0 @@ -from lightly.cli.config.get_config import get_lightly_config - - -def test_get_lightly_config() -> None: - conf = get_lightly_config() - # Assert some default values - assert conf.checkpoint == "" - assert conf.loader.batch_size == 16 - assert conf.trainer.weights_summary is None - assert conf.summary_callback.max_depth == 1 diff --git a/tests/cli/test_cli_magic.py b/tests/cli/test_cli_magic.py deleted file mode 100644 index 487866145..000000000 --- a/tests/cli/test_cli_magic.py +++ /dev/null @@ -1,91 +0,0 @@ -import os -import re -import sys -import tempfile - -import hydra -import torchvision -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -from lightly import cli -from tests.api_workflow.mocked_api_workflow_client import ( - N_FILES_ON_SERVER, - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestCLIMagic(MockedApiWorkflowSetup): - def setUp(self): - MockedApiWorkflowSetup.setUp(self) - self.create_fake_dataset() - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose( - config_name="config", - overrides=[ - f"input_dir={self.folder_path}", - "trainer.max_epochs=0", - ], - ) - - def create_fake_dataset(self, filename_appendix: str = ""): - n_data = len(self.api_workflow_client.get_filenames()) - self.dataset = torchvision.datasets.FakeData( - size=n_data, image_size=(3, 32, 32) - ) - - self.folder_path = tempfile.mkdtemp() - sample_names = [f"img_{i}{filename_appendix}.jpg" for i in range(n_data)] - self.sample_names = sample_names - for sample_idx in range(n_data): - data = self.dataset[sample_idx] - path = os.path.join(self.folder_path, sample_names[sample_idx]) - data[0].save(path) - - def parse_cli_string(self, cli_words: str): - cli_words = cli_words.replace("lightly-magic ", "") - cli_words = re.split("=| ", cli_words) - assert len(cli_words) % 2 == 0 - dict_keys = cli_words[0::2] - dict_values = cli_words[1::2] - for key, value in zip(dict_keys, dict_values): - value = value.strip('"') - value = value.strip("'") - try: - value = int(value) - except ValueError: - pass - - key_subparts = key.split(".") - if len(key_subparts) == 1: - self.cfg[key] = value - elif len(key_subparts) == 2: - self.cfg[key_subparts[0]][key_subparts[1]] = value - else: - raise ValueError( - f"Keys with more than 2 subparts are not supported," - f"but you entered {key}." - ) - - def test_parse_cli_string(self): - cli_string = "lightly-magic trainer.max_epochs=3" - self.parse_cli_string(cli_string) - self.assertEqual(self.cfg["trainer"]["max_epochs"], 3) - - def test_magic_with_trainer(self): - MockedApiWorkflowClient.n_dims_embeddings_on_server = 32 - cli_string = "lightly-magic trainer.max_epochs=1" - self.parse_cli_string(cli_string) - cli.lightly_cli(self.cfg) - - def tearDown(self) -> None: - for filename in ["embeddings.csv", "embeddings_sorted.csv"]: - try: - os.remove(filename) - except FileNotFoundError: - pass diff --git a/tests/cli/test_cli_train.py b/tests/cli/test_cli_train.py deleted file mode 100644 index 15cbc72a6..000000000 --- a/tests/cli/test_cli_train.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -import re -import sys -import tempfile - -import hydra -import torchvision -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -from lightly import cli -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestCLITrain(MockedApiWorkflowSetup): - def setUp(self): - MockedApiWorkflowSetup.setUp(self) - self.create_fake_dataset() - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose( - config_name="config", - overrides=[ - f"input_dir={self.folder_path}", - "trainer.max_epochs=1", - ], - ) - - def create_fake_dataset(self): - n_data = 5 - self.dataset = torchvision.datasets.FakeData( - size=n_data, image_size=(3, 32, 32) - ) - - self.folder_path = tempfile.mkdtemp() - sample_names = [f"img_{i}.jpg" for i in range(n_data)] - self.sample_names = sample_names - for sample_idx in range(n_data): - data = self.dataset[sample_idx] - path = os.path.join(self.folder_path, sample_names[sample_idx]) - data[0].save(path) - - def test_checkpoint_created(self): - cli.train_cli(self.cfg) - checkpoint_path = os.getenv( - self.cfg["environment_variable_names"]["lightly_last_checkpoint_path"] - ) - assert checkpoint_path.endswith(".ckpt") - assert os.path.isfile(checkpoint_path) - - def tearDown(self) -> None: - for filename in ["embeddings.csv", "embeddings_sorted.csv"]: - try: - os.remove(filename) - except FileNotFoundError: - pass diff --git a/tests/cli/test_cli_version.py b/tests/cli/test_cli_version.py deleted file mode 100644 index 0ef55dce7..000000000 --- a/tests/cli/test_cli_version.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import re -import sys -import tempfile - -import hydra -import pytest -from hydra.experimental import compose - -try: - from hydra import initialize -except ImportError: - from hydra.experimental import initialize - -from lightly.cli.version_cli import version_cli -from tests.api_workflow.mocked_api_workflow_client import ( - MockedApiWorkflowClient, - MockedApiWorkflowSetup, -) - - -class TestCLIVersion(MockedApiWorkflowSetup): - def setUp(self): - MockedApiWorkflowSetup.setUp(self) - with initialize(config_path="../../lightly/cli/config", job_name="test_app"): - self.cfg = compose(config_name="config") - - @pytest.fixture(autouse=True) - def capsys(self, capsys): - self.capsys = capsys - - def test_checkpoint_created(self): - version_cli(self.cfg) - out, err = self.capsys.readouterr() - assert out.startswith("lightly version") diff --git a/tests/conftest.py b/tests/conftest.py index 7133ba908..6b6c2507d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,6 +4,7 @@ from unittest import mock import pytest +import lightly_api def pytest_addoption(parser): @@ -62,11 +63,11 @@ def mock_get_latest_pip_version(current_version: str, **kwargs) -> str: # NOTE(guarin, 2/6/23): Cannot use pytest mocker fixture here because it has not # a "module" scope and it is not possible to use a fixture that has a tighter scope # inside a fixture with a wider scope. - with mock.patch( - "lightly.api._version_checking.VersioningApi.get_latest_pip_version", - new=mock_get_latest_pip_version, - ), mock.patch( - "lightly.api._version_checking.VersioningApi.get_minimum_compatible_pip_version", - return_value="1.0.0", - ): - yield + # with mock.patch( + # "lightly_api.api._version_checking.VersioningApi.get_latest_pip_version", + # new=mock_get_latest_pip_version, + # ), mock.patch( + # "lightly_api.api._version_checking.VersioningApi.get_minimum_compatible_pip_version", + # return_value="1.0.0", + # ): + # yield diff --git a/tests/utils/test_io.py b/tests/utils/test_io.py index 04086be5f..9fb422809 100644 --- a/tests/utils/test_io.py +++ b/tests/utils/test_io.py @@ -7,10 +7,9 @@ import numpy as np from lightly.utils import io -from tests.api_workflow.mocked_api_workflow_client import MockedApiWorkflowSetup -class TestCLICrop(MockedApiWorkflowSetup): # type: ignore[misc] +class TestCLICrop(): def test_save_metadata(self) -> None: metadata = [("filename.jpg", {"random_metadata": 42})] metadata_filepath = tempfile.mktemp(".json", "metadata")