datamint.APIHandler

class datamint.apihandler.api_handler.APIHandler(root_url=None, api_key=None, check_connection=True, **kwargs)

Import using this code:

from datamint import APIHandler
api = APIHandler()
Parameters:
  • root_url (str | None)

  • api_key (str | None)

  • check_connection (bool)

add_annotations(resource_id, identifier, frame_index=None, value=None, worklist_id=None, imported_from=None, author_email=None, model_id=None, project=None)

Add annotations to a resource.

Parameters:
  • resource_id (str) – The resource unique id.

  • identifier (str) – The annotation identifier.

  • frame_index (int | tuple[int, int] | None) – The frame index or a tuple with the range of frame indexes. If a tuple is provided, the annotation will be added to all frames in the range (Inclusive on both ends).

  • value (str | None) – The annotation value.

  • worklist_id (str | None) – The annotation worklist unique id.

  • imported_from (str | None) – The imported from value.

  • author_email (str | None) – The author email. If None, use the customer of the api key. Requires admin permissions to set a different customer.

  • model_id (str | None) – The model unique id.

  • project (str | None) – The project unique id or name. Only this or worklist_id can be provided at the same time.

add_frame_category_annotation(resource_id, frame_index, identifier, value, worklist_id=None, imported_from=None, author_email=None)

Add a category annotation to a frame.

Parameters:
  • resource_id (str) – The resource unique id.

  • frame_index (Union[int, Tuple[int, int]]) – The frame index or a tuple with the range of frame indexes. If a tuple is provided, the annotation will be added to all frames in the range (Inclusive on both ends).

  • identifier (str) – The annotation identifier.

  • value (str) – The annotation value.

  • worklist_id (Optional[str]) – The annotation worklist unique id.

  • author_email (Optional[str]) – The author email. If None, use the customer of the api key. Requires admin permissions to set a different customer.

  • imported_from (str | None)

add_image_category_annotation(resource_id, identifier, value, imported_from=None, author_email=None, worklist_id=None, project=None)

Add a category annotation to an image.

Parameters:
  • resource_id (str) – The resource unique id.

  • identifier (str) – The annotation identifier. For example: ‘fracture’.

  • value (str) – The annotation value.

  • imported_from (Optional[str]) – The imported from value.

  • author_email (Optional[str]) – The author email. If None, use the customer of the api key.

  • wokklist_id (Optional[str]) – The annotation worklist unique id.

  • project (Optional[str]) – The project unique id or name. Only this or worklist_id can be provided at the same time.

  • worklist_id (str | None)

add_line_annotation(point1, point2, resource_id, identifier, frame_index=None, dicom_metadata=None, coords_system='pixel', project=None, worklist_id=None, imported_from=None, author_email=None, model_id=None)

Add a line annotation to a resource.

Parameters:
  • point1 (tuple[int, int] | tuple[float, float, float]) – The first point of the line. Can be a 2d or 3d point. If coords_system is ‘pixel’, it must be a 2d point and it represents the pixel coordinates of the image. If coords_system is ‘patient’, it must be a 3d point and it represents the patient coordinates of the image, relative to the DICOM metadata.

  • 'patient' (If coords_system is)

  • point. (it must be a 3d)

  • point2 (tuple[int, int] | tuple[float, float, float]) – The second point of the line. See point1 for more details.

  • resource_id (str) – The resource unique id.

  • identifier (str) – The annotation identifier, also as known as the annotation’s label.

  • frame_index (int | None) – The frame index of the annotation.

  • dicom_metadata (Dataset | str | None) – The DICOM metadata of the image. If provided, the coordinates will be converted to the correct coordinates automatically using the DICOM metadata.

  • coords_system (Literal['pixel', 'patient']) – The coordinate system of the points. Can be ‘pixel’, or ‘patient’. If ‘pixel’, the points are in pixel coordinates. If ‘patient’, the points are in patient coordinates (see DICOM patient coordinates).

  • project (str | None) – The project unique id or name.

  • worklist_id (str | None) – The annotation worklist unique id. Optional.

  • imported_from (str | None) – The imported from source value.

  • author_email (str | None) – The email to consider as the author of the annotation. If None, use the customer of the api key.

  • model_id (str | None) – The model unique id. Optional.

Example

res_id = 'aa93813c-cef0-4edd-a45c-85d4a8f1ad0d'
api.add_line_annotation([0, 0], (10, 30),
                        resource_id=res_id,
                        identifier='Line1',
                        frame_index=2,
                        project='Example Project')
create_project(name, description, resources_ids, is_active_learning=False)

Create a new project.

Parameters:
  • name (str) – The name of the project.

  • description (str)

  • resources_ids (list[str])

  • is_active_learning (bool)

Returns:

The created project.

Return type:

dict

Raises:

DatamintException – If the project could not be created.

create_user(email, password=None, firstname=None, lastname=None, roles=None)

Create a user.

Parameters:
  • email (str) – The user email.

  • password (Optional[str]) – The user password.

  • firstname (Optional[str]) – The user first name.

  • lastname (Optional[str]) – The user last name.

  • roles (list[str] | None)

Returns:

The user information.

Return type:

dict

delete_project(project_id)

Delete a project by its id.

Parameters:

project_id (str) – The project id.

Raises:

ResourceNotFoundError – If the project does not exists.

Return type:

None

delete_resources(resource_ids)

Delete resources by their unique ids.

Parameters:

resource_ids (Sequence[str] | str) – The resource unique id or a list of resource unique ids.

Raises:

ResourceNotFoundError – If the resource does not exists.

Return type:

None

Example

>>> api_handler.delete_resources('e8b78358-656d-481f-8c98-d13b9ba6be1b')
>>> api_handler.delete_resources(['e8b78358-656d-481f-8c98-d13b9ba6be1b', '6f8b506c-6ea1-4e85-8e67-254767f95a7b'])
download_project(project_id, outpath, all_annotations=False, include_unannotated=False)

Download a project by its id.

Parameters:
  • project_id (str) – The project id.

  • outpath (str) – The path to save the project zip file.

Return type:

None

Example

>>> api_handler.download_project('project_id', 'path/to/project.zip')
Parameters:
  • all_annotations (bool)

  • include_unannotated (bool)

download_resource_file(resource_id, save_path=None, auto_convert=True, add_extension=False)

Download a resource file.

Parameters:
  • resource_id (str) – The resource unique id.

  • save_path (Optional[str]) – The path to save the file.

  • auto_convert (bool) – Whether to convert the file to a known format or not.

  • add_extension (bool) – Whether to add the appropriate file extension to the save_path based on the content type.

Return type:

bytes | Dataset | Image | VideoCapture | FileBasedImage | tuple[Any, str]

Returns:

The resource content in bytes (if auto_convert=False) or the resource object (if auto_convert=True). if add_extension=True, the function will return a tuple of (resource_data, save_path).

Raises:

ResourceNotFoundError – If the resource does not exists.

Example

>>> api_handler.download_resource_file('resource_id', auto_convert=False)
    returns the resource content in bytes.
>>> api_handler.download_resource_file('resource_id', auto_convert=True)
    Assuming this resource is a dicom file, it will return a pydicom.dataset.Dataset object.
>>> api_handler.download_resource_file('resource_id', save_path='path/to/dicomfile.dcm')
    saves the file in the specified path.
download_resource_frame(resource_id, frame_index)

Download a frame of a resource. This is faster than downloading the whole resource and then extracting the frame.

Parameters:
  • resource_id (str) – The resource unique id.

  • frame_index (int) – The index of the frame to download.

Returns:

The frame as a PIL image.

Return type:

Image.Image

Raises:
get_annotation_worklist(status=None)

Get the annotation worklist.

Parameters:

status (Literal['new', 'updating','active', 'completed']) – The status of the annotations.

Returns:

A generator of dictionaries with the annotations information.

Return type:

Generator[dict, None, None]

get_annotation_worklist_by_id(id)

Get the annotation worklist.

Parameters:

id (str) – The annotation worklist unique id.

Returns:

A dictionary with the annotations information.

Return type:

Dict

get_annotations(resource_id=None, annotation_type=None, annotator_email=None, date_from=None, date_to=None, dataset_id=None, worklist_id=None, status=None, load_ai_segmentations=None)

Get annotations for a resource.

Parameters:
  • resource_id (Optional[str]) – The resource unique id.

  • annotation_type (Optional[str]) – The annotation type. See AnnotationType.

  • annotator_email (Optional[str]) – The annotator email.

  • date_from (Optional[date]) – The start date.

  • date_to (Optional[date]) – The end date.

  • dataset_id (Optional[str]) – The dataset unique id.

  • worklist_id (Optional[str]) – The annotation worklist unique id.

  • status (Optional[Literal['new', 'published']]) – The status of the annotations.

  • load_ai_segmentations (bool) – Whether to load the AI segmentations or not. Default is False.

Returns:

A generator of dictionaries with the annotations information.

Return type:

Generator[dict, None, None]

get_channels()

Iterates over the channels with the specified filters.

Returns:

A generator of dictionaries with the channels information.

Return type:

Generator[dict, None, None]

Example

>>> list(api_handler.get_channels()) # Gets all channels
[{'channel_name': 'test_channel',
    'resource_data': [{'created_by': 'datamint-dev@mail.com',
                        'customer_id': '79113ed1-0535-4f53-9359-7fe3fa9f28a8',
                        'resource_id': 'a05fe46d-2f66-46fc-b7ef-666464ad3a28',
                        'resource_file_name': 'image.png',
                        'resource_mimetype': 'image/png'}],
    'deleted': False,
    'created_at': '2024-06-04T12:38:12.976Z',
    'updated_at': '2024-06-04T12:38:12.976Z',
    'resource_count': '1'}]
get_datasets()

Get all datasets.

Returns:

A list of dictionaries with the datasets information.

Return type:

list[dict]

get_experiment_by_name(name, project)

Get the experiment by name of the project.

Parameters:
  • name (str) – Name of the experiment.

  • project (Dict) – The project to search for the experiment.

Returns:

The experiment if found, otherwise None.

Return type:

Optional[Dict]

get_project_by_id(project_id)

Get a project by its id.

Parameters:

project_id (str) – The project id.

Returns:

The project information.

Return type:

dict

Raises:

ResourceNotFoundError – If the project does not exists.

get_project_by_name(project_name)

Get a project by its name.

Parameters:

project_name (str) – The project name.

Returns:

The project information.

Return type:

dict

Raises:

ResourceNotFoundError – If the project does not exists.

get_projects()

Get the list of projects.

Returns:

The list of projects.

Return type:

list[dict]

Example

>>> api_handler.get_projects()
get_resource_annotations(resource_id, annotation_type=None, annotator_email=None, date_from=None, date_to=None)

Deprecated since version 0.12.1: Use get_annotations() instead with resource_id parameter.

Parameters:
  • resource_id (str)

  • annotation_type (str | None)

  • annotator_email (str | None)

  • date_from (date | None)

  • date_to (date | None)

Return type:

Generator[dict, None, None]

get_resources(status=None, from_date=None, to_date=None, labels=None, tags=None, modality=None, mimetype=None, return_ids_only=False, order_field=None, order_ascending=None, channel=None, project_id=None, project_name=None, filename=None)

Iterates over resources with the specified filters. Filters can be combined to narrow down the search. It returns full information of the resources by default, but it can be configured to return only the ids with parameter return_ids_only.

Parameters:
  • status (ResourceStatus) – The resource status. Possible values: ‘inbox’, ‘published’, ‘archived’ or None. If None, it will return all resources.

  • from_date (Optional[date]) – The start date.

  • to_date (Optional[date]) – The end date.

  • labels

    Deprecated since version 0.11.0: Use tags instead.

  • tags (Optional[list[str]]) – The tags to filter the resources.

  • modality (Optional[str]) – The modality of the resources.

  • mimetype (Optional[str]) – The mimetype of the resources.

  • return_ids_only (bool) – Whether to return only the ids of the resources.

  • order_field (Optional[ResourceFields]) – The field to order the resources. See ResourceFields.

  • order_ascending (Optional[bool]) – Whether to order the resources in ascending order.

Returns:

A generator of dictionaries with the resources information.

Return type:

Generator[dict, None, None]

Example

>>> for resource in api_handler.get_resources(status='inbox'):
>>>     print(resource)
Parameters:
  • channel (str | None)

  • project_id (str | None)

  • project_name (str | None)

  • filename (str | None)

get_resources_by_ids(ids)

Get resources by their unique ids.

Parameters:

ids (str | Sequence[str]) – The resource unique id or a list of resource unique ids.

Returns:

The resource information or a list of resource information.

Return type:

dict | Sequence[dict]

Raises:

ResourceNotFoundError – If the resource does not exists.

Example

>>> api_handler.get_resources_by_ids('resource_id')
>>> api_handler.get_resources_by_ids(['resource_id1', 'resource_id2'])
get_resources_by_project(project_id)

Get the resources by project.

Parameters:

project_id (str) – The project id.

Returns:

The list of resources.

Return type:

list[dict]

Example

>>> api_handler.get_resources_by_project('project_id')

Deprecated since version 0.12.0: Use get_resources() with project_id parameter instead.

get_users()

Get all users.

Returns:

A list of dictionaries with the users information.

Return type:

list[dict]

Example

>>> api_handler.get_users()
publish_resources(resource_ids, project_name=None)

Publish a resource, chaging its status to ‘published’.

Parameters:
  • resource_ids (str|Sequence[str]) – The resource unique id or a list of resource unique ids.

  • project_name (str) – The project name or id to publish the resource to.

Raises:

ResourceNotFoundError – If the resource does not exists or the project does not exists.

Return type:

None

update_annotation_worklist(worklist_id, frame_labels=None, image_labels=None, annotations=None, status=None, name=None)

Update the status of an annotation worklist.

Parameters:
  • worklist_id (str) – The annotation worklist unique id.

  • frame_labels (List[str]) – The frame labels.

  • image_labels (List[str]) – The image labels.

  • annotations (List[Dict]) – The annotations.

  • status (Literal['new', 'updating','active', 'completed']) – The status of the annotations.

  • name (str)

upload_resources(files_path, mimetype=None, anonymize=False, anonymize_retain_codes=[], on_error='raise', labels=None, tags=None, mung_filename=None, channel=None, publish=False, publish_to=None, segmentation_files=None, transpose_segmentation=False, modality=None, assemble_dicoms=True)

Upload resources.

Parameters:
  • files_path (str | IO | Sequence[str | IO]) – The path to the resource file or a list of paths to resources files.

  • mimetype (str) – The mimetype of the resources. If None, it will be guessed.

  • anonymize (bool) – Whether to anonymize the dicoms or not.

  • anonymize_retain_codes (Sequence[tuple]) – The tags to retain when anonymizing the dicoms.

  • on_error (Literal['raise', 'skip']) – Whether to raise an exception when an error occurs or to skip the error.

  • labels

    Deprecated since version 0.11.0: Use tags instead.

  • tags (Optional[Sequence[str]]) – The tags to add to the resources.

  • mung_filename (Sequence[int] | Literal['all']) – The parts of the filepath to keep when renaming the resource file. ‘’all’’ keeps all parts.

  • channel (Optional[str]) – The channel to upload the resources to. An arbitrary name to group the resources.

  • publish (bool) – Whether to directly publish the resources or not. They will have the ‘published’ status.

  • publish_to (Optional[str]) – The project name or id to publish the resources to. They will have the ‘published’ status and will be added to the project. If this is set, publish parameter is ignored.

  • segmentation_files (Optional[list[Union[list[str], dict]]]) – The segmentation files to upload.

  • transpose_segmentation (bool) – Whether to transpose the segmentation files or not.

  • modality (Optional[str]) – The modality of the resources.

  • assemble_dicoms (bool) – Whether to assemble the dicom files or not based on the SOPInstanceUID and InstanceNumber attributes.

Raises:

ResourceNotFoundError – If publish_to is supplied, and the project does not exists.

Returns:

The list of new created dicom_ids.

Return type:

list[str]

upload_segmentations(resource_id, file_path, name=None, frame_index=None, imported_from=None, author_email=None, discard_empty_segmentations=True, worklist_id=None, model_id=None, transpose_segmentation=False)

Upload segmentations to a resource.

Parameters:
  • resource_id (str) – The resource unique id.

  • file_path (str|np.ndarray) – The path to the segmentation file or a numpy array. If a numpy array is provided, it must have the shape (height, width, #frames) or (height, width).

  • name (Optional[Union[str, Dict[int, str]]]) – The name of the segmentation or a dictionary mapping pixel values to names. example: {1: ‘Femur’, 2: ‘Tibia’}.

  • frame_index (int | list[int]) – The frame index of the segmentation. If a list, it must have the same length as the number of frames in the segmentation. If None, it is assumed that the segmentations are in sequential order starting from 0.

  • discard_empty_segmentations (bool) – Whether to discard empty segmentations or not.

Returns:

The segmentation unique id.

Return type:

str

Raises:

ResourceNotFoundError – If the resource does not exists or the segmentation is invalid.

Example

>>> api_handler.upload_segmentation(resource_id, 'path/to/segmentation.png', 'SegmentationName')
Parameters:
  • imported_from (str | None)

  • author_email (str | None)

  • worklist_id (str | None)

  • model_id (str | None)

  • transpose_segmentation (bool)

exception datamint.apihandler.base_api_handler.DatamintException

Base class for exceptions in this module.

datamint.apihandler.base_api_handler.ResourceFields

The available fields to order resources. Possible values: ‘modality’, ‘created_by’, ‘published_by’, ‘published_on’, ‘filename’, ‘created_at’ (default).

Type:

TypeAlias

alias of Literal[‘modality’, ‘created_by’, ‘published_by’, ‘published_on’, ‘filename’, ‘created_at’]

exception datamint.apihandler.base_api_handler.ResourceNotFoundError(resource_type, params)

Exception raised when a resource is not found. For instance, when trying to get a resource by a non-existing id.

Parameters:
  • resource_type (str)

  • params (dict)

datamint.apihandler.base_api_handler.ResourceStatus

The available resource status. Possible values: ‘new’, ‘inbox’, ‘published’, ‘archived’.

Type:

TypeAlias

alias of Literal[‘new’, ‘inbox’, ‘published’, ‘archived’]