lightly.api

The lightly.api module provides access to the Lightly web-app.

.api_workflow_client

class lightly.api.api_workflow_client.ApiWorkflowClient(token: str, dataset_id: str = None, embedding_id: str = None)

Provides a uniform interface to communicate with the api

The APIWorkflowClient is used to communicaate 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.

Parameters
  • token – the token of the user, provided in webapp

  • dataset_id – the id of the dataset, provided in webapp. 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

append_embeddings(path_to_embeddings_csv: str, embedding_id: str)

Concatenates the embeddings from the server to the local ones.

Loads the embedding csv file belonging to the embedding_id, and appends all of its rows to the local embeddings file located at ‘path_to_embeddings_csv’.

Parameters
  • 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 server.

Raises

RuntimeError – If the number of columns in the local and the remote embeddings file mismatch.

create_dataset(dataset_name: str)

Creates a dataset on the webplatform

If a dataset with that name already exists, instead the dataset_id is set.

Parameters

dataset_name – The name of the dataset to be created.

create_new_dataset_with_unique_name(dataset_basename: str)

Creates a new dataset on the web platform

If a dataset with the specified name already exists, a counter is added to the name to be able to still create it.

Parameters

dataset_basename – The name of the dataset to be created.

property dataset_id

The current dataset_id.

If the dataset_id is set, it is returned. If it is not set, then the dataset_id of the last modified dataset is selected.

property dataset_type

Returns the dataset type of the current dataset.

delete_dataset_by_id(dataset_id: str)

Deletes a dataset on the web platform

Parameters

dataset_id – The id of the dataset to be deleted.

download_dataset(output_dir: str, tag_name: str = 'initial-tag', verbose: bool = True)

Downloads images from the web-app and stores them in output_dir.

Parameters
  • output_dir – Where to store the downloaded images.

  • tag_name – Name of the tag which should be downloaded.

  • 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.

download_new_raw_samples() → 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.

Returns

A list of (filename, url) tuples, where each tuple represents a sample

download_raw_samples(from_: int = 0, to: int = None) → List[Tuple[str, str]]

Downloads all filenames and read urls from the datasource between from_ and to.

Samples which have timestamp == from_ or timestamp == to will also be included.

Parameters
  • from_ – Unix timestamp from which on samples are downloaded.

  • to – Unix timestamp up to and including which samples are downloaded.

Returns

A list of (filename, url) tuples, where each tuple represents a sample

get_all_tags() → List[lightly.openapi_generated.swagger_client.models.tag_data.TagData]

Gets all tags on the server

Returns

one TagData entry for each tag on the server

get_datasource()

Calls the api to return the datasource of the current dataset.

Returns

Datasource data of the datasource of the current dataset.

Raises

ApiException if no datasource was configured.

get_embedding_by_name(name: str, ignore_suffix: bool = True) → lightly.openapi_generated.swagger_client.models.dataset_embedding_data.DatasetEmbeddingData

Gets an embedding form the server by name.

Parameters
  • name – The name of the embedding to get.

  • ignore_suffix – If true, a suffix of the embedding name on the server is ignored.

Returns

The embedding data.

Raises

EmbeddingDoesNotExistError – If the name does not match the name of an embedding on the server.

get_filenames() → List[str]

Downloads the list of filenames from the server.

This is an expensive operation, especially for large datasets.

get_filenames_in_tag(tag_data: lightly.openapi_generated.swagger_client.models.tag_data.TagData, filenames_on_server: List[str] = None, exclude_parent_tag: bool = False) → List[str]

Gets the filenames of a tag

Parameters
  • tag_data – The data of the tag.

  • filenames_on_server – List of all filenames on the server. If they are not given, they need to be downloaded, which is quite expensive.

  • exclude_parent_tag – Excludes the parent tag in the returned filenames.

Returns

filenames_tag – The filenames of all samples in the tag.

get_processed_until_timestamp() → int

Returns the timestamp until which samples have been processed.

Returns

Unix timestamp of last processed sample

index_custom_metadata_by_filename(filenames: List[str], custom_metadata: Dict)

Creates an index to lookup custom metadata by filename.

Parameters
  • filenames – List of filenames.

  • custom_metadata – Dictionary of custom metadata, see upload_custom_metadata for the required format.

Returns

A dictionary containing custom metdata indexed by filename.

sampling(sampler_config: lightly.active_learning.config.sampler_config.SamplerConfig, preselected_tag_id: str = None, query_tag_id: str = None) → lightly.openapi_generated.swagger_client.models.tag_data.TagData

Performs a sampling given the arguments.

Parameters
  • sampler_config – The configuration of the sampler.

  • al_scores – The active learning scores for the sampler.

  • preselected_tag_id – The tag defining the already chosen samples (e.g. already labelled ones), default: None.

  • query_tag_id – The tag defining where to sample from, default: None resolves to the initial-tag.

Returns

The newly created tag of the sampling.

Raises
  • ApiException

  • ValueError

  • RuntimeError

set_dataset_id_by_name(dataset_name: str)

Sets the dataset id given the name of the dataset

Parameters

dataset_name – The name of the dataset for which the dataset_id should be set as attribute

Raises: ValueError

set_embedding_id_to_latest()

Sets the self.embedding_id to the one of the latest on the server.

update_processed_until_timestamp(timestamp: int) → None

Sets the timestamp until which samples have been processed.

Parameters

timestamp – Unix timestamp of last processed sample

upload_custom_metadata(custom_metadata: Dict, verbose: bool = False, max_workers: int = 8)

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 a image_id to match it to the image.

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
>>>             }
>>>         }
>>>     ]
>>> }
Parameters
  • 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.

upload_dataset(input: Union[str, lightly.data.dataset.LightlyDataset], max_workers: int = 8, mode: str = 'thumbnails', verbose: bool = True, custom_metadata: Optional[Dict] = None)

Uploads a dataset to to the Lightly cloud solution.

Parameters
  • input – Either the path to the dataset, e.g. “path/to/dataset”, or the dataset in form of a LightlyDataset

  • max_workers – Maximum number of workers uploading images in parallel.

  • max_requests – Maximum number of requests a single worker can do before he has to wait for the others.

  • mode – One of [full, thumbnails, metadata]. Whether to upload thumbnails, full images, or metadata only.

Raises
  • ValueError – If dataset is too large or input has the wrong type

  • RuntimeError – If the connection to the server failed.

upload_embeddings(path_to_embeddings_csv: str, name: str)

Uploads embeddings to the server.

First checks that the specified embedding name is not on ther server. If it is, the upload is aborted. Then creates a new csv with the embeddings in the order specified on the server. Next it uploads it to the server. The received embedding_id is saved as a property of self.

Parameters
  • 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.

upload_file_with_signed_url(file: io.IOBase, signed_write_url: str, headers: Dict = None) → requests.models.Response

Uploads a file to a url via a put request.

Parameters
  • file – The file to upload.

  • 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.

Returns

The response of the put request, usually a 200 for the success case.

verify_custom_metadata_format(custom_metadata: Dict)

Verifies that the custom metadata is in the correct format.

Parameters

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.

Upload Dataset Mixin

exception lightly.api.api_workflow_upload_embeddings.EmbeddingDoesNotExistError