API Endpoints
This section documents all available API endpoints for interacting with DataMint resources.
Projects API
- class datamint.api.endpoints.projects_api.ProjectsApi(config, client=None, resources_api=None)
Bases:
CRUDEntityApi[Project]API handler for project-related endpoints.
- Parameters:
config (
ApiConfig)client (
Client|None)resources_api (
ResourcesApi|None)
- add_resources(resources, project)
Add resources to a project.
- create(name, description, resources_ids=None, is_active_learning=False, two_up_display=False, segmentation_spec='single_label', *, return_entity=True, exists_ok=False)
- Overloads:
self, name (str), description (str), resources_ids (list[str] | None), is_active_learning (bool), two_up_display (bool), segmentation_spec (Literal[‘single_label’, ‘multi_label’]), return_entity (Literal[True]), exists_ok (bool) → Project
self, name (str), description (str), resources_ids (list[str] | None), is_active_learning (bool), two_up_display (bool), segmentation_spec (Literal[‘single_label’, ‘multi_label’]), return_entity (Literal[False]), exists_ok (bool) → str
Create a new project.
- Parameters:
name (
str) – The name of the project.description (
str) – The description of the project.resources_ids (
list[str] |None) – The list of resource ids to be included in the project.is_active_learning (
bool) – Whether the project is an active learning project or not.two_up_display (
bool) – Allow annotators to display multiple resources for annotation.return_entity (
bool) – Whether to return the created Project instance or just its ID.exists_ok (
bool) – IfTrue, do not raise an error when a project with the same name already exists. Instead, the existing project is returned when possible.segmentation_spec (
Literal['single_label','multi_label'])
- Returns:
The id of the created project.
- Return type:
str | Project
- download_annotations(project, output_path, format='csv', annotators=None, annotations=None, from_date=None, to_date=None, progress_bar=True)
Download annotation data as a CSV or Excel file.
- Parameters:
project (
str|Project) – The project ID or Project instance.output_path (
str|Path) – Local file path to save the downloaded data.format (
str) – Export format,'csv'(default) or'xlsx'.annotators (
list[str] |None) – Optional list of annotator emails to include.annotations (
list[str] |None) – Optional list of annotation identifiers to include.from_date (
str|None) – Optional start date filter (ISO string).to_date (
str|None) – Optional end date filter (ISO string).progress_bar (
bool) – Whether to display a progress bar.
- Return type:
None
- get_all(limit=None)
Get all projects.
- Parameters:
limit (
int|None) – The maximum number of projects to return. If None, return all projects.- Return type:
Sequence[Project]- Returns:
A list of project instances.
- get_annotation_statuses(project, status=None, user_id=None, resource_id=None)
Get per-resource annotation statuses for a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.status (
str|None) – Optional status filter.user_id (
str|None) – Optional user ID filter.resource_id (
str|None) – Optional resource ID filter.
- Return type:
list[dict]- Returns:
List of annotation status dicts.
- get_annotations_specs(project)
Get the annotations specs for a given project.
- Parameters:
project (
str|Project) – The project id or Project instance.- Return type:
Sequence[AnnotationSpec]- Returns:
A sequence of AnnotationSpec instances.
- get_annotations_stats(project)
Get aggregate annotation statistics (counts per type) for a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.- Return type:
dict- Returns:
Annotation statistics dict.
- get_annotator_status(project, email)
Get a specific annotator’s progress status in a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.email (
str) – The annotator’s email address.
- Return type:
dict- Returns:
Annotator status dict.
- get_annotators_stats(project, email=None)
Get per-annotator completion statistics for a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.email (
str|None) – Optional annotator email to filter results.
- Return type:
list[dict]- Returns:
List of per-annotator stat dicts.
- get_by_name(name, include_archived=True)
Get a project by its name.
- Parameters:
name (
str) – The name of the project.include_archived (
bool) – Whether to include archived projects in the search.
- Return type:
Project|None- Returns:
The project instance if found, otherwise None.
- get_files_matrix_stats(project)
Get a matrix of resource × annotator completion statistics.
- Parameters:
project (
str|Project) – The project ID or Project instance.- Return type:
dict- Returns:
Files-matrix statistics dict.
- get_members(project)
List all members of a project with their roles.
- Parameters:
project (
str|Project) – The project ID or Project instance.- Returns:
project_id,user_id,roles,expertise_level,status,firstname,lastname).- Return type:
list[dict]
- get_models(project)
List ML models associated with a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.- Return type:
list[dict]- Returns:
List of model dicts.
- get_project_resources(project)
Get resources associated with a specific project.
- get_review_messages(project, annotator=None, resource_id=None, statuses=None)
Get review feedback messages for a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.annotator (
str|None) – Optional annotator email filter.resource_id (
str|None) – Optional resource ID filter.statuses (
list[str] |None) – Optional list of status strings to filter by.
- Return type:
list[dict]- Returns:
List of review message dicts.
- get_worklist(project)
Get the annotation worklist object for a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.- Return type:
dict- Returns:
The worklist data dict.
- remove_member(project, user_id)
Remove a user from a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.user_id (
str) – The user’s UUID.
- Return type:
None
- reset_annotator_status(project, resource, annotator)
Reset annotation status for a specific annotator on a resource.
- set_member(project, user_id, roles)
Set (or update) a user’s roles in a project.
- Parameters:
project (
str|Project) – The project ID or Project instance.user_id (
str) – The user’s UUID.roles (
list[str]) – List of role strings, e.g.['PROJECT_ANNOTATOR'].
- Return type:
None
- set_work_status(project, resource, status)
Set the status of a resource.
Resources API
- datamint.api.endpoints.resources_api.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’]
- datamint.api.endpoints.resources_api.ResourceStatus
The available resource status. Possible values: ‘new’, ‘inbox’, ‘published’, ‘archived’.
- Type:
TypeAlias
alias of
Literal[‘new’, ‘inbox’, ‘published’, ‘archived’]
- class datamint.api.endpoints.resources_api.ResourcesApi(config, client=None, annotations_api=None, projects_api=None)
Bases:
CreatableEntityApi[Resource],DeletableEntityApi[Resource]API handler for resource-related endpoints.
- Parameters:
config (
ApiConfig)client (
Client|None)
- add_tags(resource, tags)
Add tags to a resource, IMPORTANT: This appends to existing tags. :type resource:
str|Resource|Sequence[str|Resource] :param resource: The resource unique id or Resource object. :type tags:Sequence[str] :param tags: The tags to add.
- bulk_delete(entities)
Delete multiple entities. Faster than deleting them one by one.
- Parameters:
entities (
Sequence[str|Resource]) – Sequence of unique identifiers for the entities to delete or the entity instances themselves.- Raises:
httpx.HTTPStatusError – If deletion fails or any entity not found
- Return type:
None
- bulk_publish(resources)
Publish multiple resources in a single request.
- Parameters:
resources (
Sequence[str|Resource]) – Sequence of resource IDs or Resource instances to publish.- Return type:
None
- cache_resources(resources, progress_bar=True)
Cache multiple resources in parallel, skipping already cached ones.
This method downloads and caches resource file data concurrently, significantly improving efficiency when working with large datasets. Only resources that are not already cached will be downloaded.
- Parameters:
resources (
Sequence[Resource]) – Sequence of Resource instances to cache.progress_bar (
bool) – Whether to show a progress bar. Default is True.
- Return type:
None
Example
>>> resources = api.resources.get_list(limit=100) >>> api.resources.cache_resources(resources) Caching resources: 100%|██████████| 85/85 [00:12<00:00, 6.8files/s]
- download_multiple_resources(resources, save_path, add_extension=False, overwrite=True)
Download multiple resources and save them to the specified paths. This is faster than downloading them one by one.
- Parameters:
resources (
Sequence[str] |Sequence[Resource]) – A list of resource unique ids.save_path (
Sequence[str] |str) – A list of paths to save the files or a directory path, of same length as resources. If a directory path is provided, files will be saved in that directory.add_extension (
bool) – Whether to add the appropriate file extension to the save_path based on the content type.overwrite (
bool)
- Returns:
A list of paths where the files were saved. Important if add_extension=True.
- Return type:
list[str]
- download_resource_file(resource, save_path=None, auto_convert=True, add_extension=False)
- Overloads:
self, resource (str | Resource), save_path (str | None), auto_convert (Literal[True]), add_extension (Literal[False]) → ImagingData
self, resource (str | Resource), save_path (str | None), auto_convert (Literal[True]), add_extension (Literal[True]) → tuple[ImagingData, str]
self, resource (str | Resource), save_path (str | None), auto_convert (Literal[False]), add_extension (Literal[False]) → bytes
self, resource (str | Resource), save_path (str | None), auto_convert (Literal[False]), add_extension (Literal[True]) → tuple[bytes, str]
Download a resource file.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource instance.save_path (
str|None) – 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.
- 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:
ItemNotFoundError – If the resource does not exists.
- Return type:
pydicom.dataset.Dataset | Image.Image | cv2.VideoCapture | nib_FileBasedImage | tuple[pydicom.dataset.Dataset | Image.Image | cv2.VideoCapture | nib_FileBasedImage, str] | tuple[bytes, str] | bytes
Example
resource = api.resources.get_list(filename='file.dcm')[0] resource_bytes = api.resources.download_resource_file(resource, auto_convert=False) dicom_obj = api.resources.download_resource_file(resource, auto_convert=True) api.resources.download_resource_file(resource, save_path='path/to/dicomfile.dcm')
- download_resource_frame(resource, frame_index)
Download a frame of a resource. This is faster than downloading the whole resource and then extracting the frame.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource object.frame_index (
int) – The index of the frame to download.
- Returns:
The frame as a PIL image.
- Return type:
Image- Raises:
ItemNotFoundError – If the resource does not exists.
DatamintException – If the resource is not a video or dicom.
- get_annotations(resource, annotation_type=None)
Get annotations for a specific resource.
- Parameters:
resource (
str|Resource) – The resource ID or Resource instance to fetch annotations for.annotation_type (
AnnotationType|str|None)
- Return type:
Sequence[Annotation]- Returns:
A sequence of Annotation objects associated with the specified resource.
- get_list(status=None, from_date=None, to_date=None, tags=None, modality=None, mimetype=None, source_filepath=None, order_field=None, order_ascending=None, channel=None, project_name=None, filename=None, limit=None)
Get resources with optional filtering.
- Parameters:
status (
Literal['new','inbox','published','archived'] |None) – The resource status. Possible values: ‘inbox’, ‘published’, ‘archived’ or None. If None, it will return all resources.from_date (
date|str|None) – The start date (inclusive).to_date (
date|str|None) – The end date (exclusive).tags (
Sequence[str] |None) – The tags to filter the resources.modality (
str|None) – The modality of the resources.mimetype (
str|None) – The mimetype of the resources.source_filepath (
str|Path|None) – Filter resources by source file path.order_field (
Literal['modality','created_by','published_by','published_on','filename','created_at'] |None) – The field to order the resources. SeeResourceFields.order_ascending (
bool|None) – Whether to order the resources in ascending order.project_name (
Project|str|list[str] |None) – The project name or a list of project names to filter resources by project. If multiple projects are provided, resources will be filtered to include only those belonging to ALL of the specified projects.channel (
str|None)filename (
str|None)limit (
int|None)
- Return type:
Sequence[Resource]
- get_not_annotated(limit=None, **kwargs)
Get resources that have no annotations.
- Parameters:
limit (
int|None) – Maximum number of resources to return.**kwargs – Additional query parameters forwarded to the endpoint.
- Return type:
list[Resource]- Returns:
List of Resource instances with no annotations.
- publish_resources(resources)
Publish resources, changing their status to ‘published’.
- Parameters:
resources (
str|Resource|Sequence[str|Resource]) – The resources to publish. Can be a Resource object (instead of a list)- Raises:
ItemNotFoundError – If the resource does not exists or the project does not exists.
- Return type:
None
- set_tags(resource, tags)
Set tags for a resource, IMPORTANT: This replaces all existing tags. :type resource:
str|Resource|Sequence[str|Resource] :param resource: The resource object or a list of resources. :type tags:Sequence[str] :param tags: The tags to set.
- upload_resource(file_path, mimetype=None, anonymize=False, anonymize_retain_codes=[], tags=None, mung_filename=None, channel=None, publish=False, publish_to=None, segmentation_files=None, transpose_segmentation=False, modality=None, metadata=None, discard_dicom_reports=True)
Upload a single resource.
This is a convenience method that wraps upload_resources for single file uploads. It provides a cleaner interface when uploading just one file.
- Parameters:
file_path (
str|IO|Dataset) – The path to the resource file or IO object.mimetype (
str|None) – The mimetype of the resource. If None, it will be guessed.anonymize (
bool) – Whether to anonymize the DICOM or not.anonymize_retain_codes (
Sequence[tuple]) – The tags to retain when anonymizing the DICOM.tags (
Sequence[str] |None) – The tags to add to the resource.mung_filename (
Sequence[int] |Literal['all'] |None) – The parts of the filepath to keep when renaming the resource file. ‘all’ keeps all parts.channel (
str|None) – The channel to upload the resource to. An arbitrary name to group the resources.publish (
bool) – Whether to directly publish the resource or not. It will have the ‘published’ status.publish_to (
Project|str|None) – The project name or id to publish the resource to. It will have the ‘published’ status and will be added to the project. If this is set, publish parameter is ignored.segmentation_files (
dict|None) – The segmentation files to upload. Should be a dict with: - ‘files’: A list of paths to the segmentation files. Example: [‘seg1.nii.gz’, ‘seg2.nii.gz’]. - ‘names’: A dict mapping pixel values to class names. Example: {1: ‘Brain’, 2: ‘Lung’}.transpose_segmentation (
bool) – Whether to transpose the segmentation files or not.modality (
str|None) – The modality of the resource.metadata (
dict|str|None) – JSON metadata to include with the resource. Can be a file path (str) or already loaded dictionary (dict).discard_dicom_reports (
bool) – Whether to discard DICOM reports or not.
- Returns:
The resource ID of the uploaded resource.
- Return type:
str- Raises:
ItemNotFoundError – If publish_to is supplied, and the project does not exist.
DatamintException – If the upload fails.
Example
# Simple upload api.resources.upload_resource('path/to/file.dcm') # Continue with the uploaded file through a Resource entity resource = api.resources.get_list(filename='file.dcm')[0] # Upload with metadata and segmentation api.resources.upload_resource( 'path/to/file.dcm', publish_to='Study Review', tags=['tutorial', 'case1'], channel='study_channel', segmentation_files={ 'files': ['path/to/segmentation.nii.gz'], 'names': {1: 'Brain', 2: 'Lung'} }, metadata={'patient_age': 45, 'modality': 'CT'} )
- upload_resources(files_path, mimetype=None, anonymize=False, anonymize_retain_codes=[], on_error='raise', tags=None, mung_filename=None, channel=None, publish=False, publish_to=None, segmentation_files=None, transpose_segmentation=False, ai_model=None, modality=None, assemble_dicoms=True, metadata=None, discard_dicom_reports=True, progress_bar=False)
Upload multiple resources.
Note: For uploading a single resource, use upload_resource() instead.
- Parameters:
files_path (
Sequence[str|IO|Dataset]) – A sequence of paths to resource files, IO objects, or pydicom.Dataset objects. Must contain at least 2 items. Supports mixed types within the sequence.mimetype (
str|None) – 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.tags (
Sequence[str] |None) – The tags to add to the resources.mung_filename (
Sequence[int] |Literal['all'] |None) – The parts of the filepath to keep when renaming the resource file. ‘’all’’ keeps all parts.channel (
str|None) – 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 (
Project|str|None) – The project to publish the resources to. Can be a Project object, project name, or project ID. They will have the ‘published’ status and will be added to the project. If this is set, publish parameter is ignored.segmentation_files (
Sequence[Sequence[str] |dict] |None) –The segmentation files to upload. If each element is a dict, it should have two keys: ‘files’ and ‘names’.
files: A list of paths to the segmentation files. Example: [‘seg1.nii.gz’, ‘seg2.nii.gz’].
names: Can be a list (same size of files) of labels for the segmentation files. Example: [‘Brain’, ‘Lung’].
transpose_segmentation (
bool) – Whether to transpose the segmentation files or not.ai_model (
str|None) – The name of the AI model to associate with uploaded segmentations. Must match an existing deployed model name on the server.modality (
str|None) – The modality of the resources.assemble_dicoms (
bool) – Whether to assemble the dicom files or not based on the SeriesInstanceUID and InstanceNumber attributes.metadata (
Sequence[str|dict|None] |None) – JSON metadata to include with each resource. Must have the same length as files_path. Can be file paths (str) or already loaded dictionaries (dict).discard_dicom_reports (
bool)progress_bar (
bool)
- Raises:
ValueError – If a single resource is provided instead of multiple resources.
ItemNotFoundError – If publish_to is supplied, and the project does not exists.
- Returns:
A list of resource IDs or errors.
- Return type:
Sequence[str|Exception]
Annotations API
- class datamint.api.endpoints.annotations_api.AnnotationsApi(config, client=None, models_api=None, resources_api=None)
Bases:
CreatableEntityApi[Annotation],DeletableEntityApi[Annotation]- Parameters:
config (
ApiConfig)client (
Client|None)models_api (
ModelsApi|None)resources_api (
ResourcesApi|None)
- add_box_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 box annotation to a resource.
- Parameters:
point1 (
tuple[int,int] |tuple[float,float,float])point2 (
tuple[int,int] |tuple[float,float,float])resource_id (
str)identifier (
str)frame_index (
int|None)dicom_metadata (
Dataset|str|Path|None)coords_system (
Literal['pixel','patient'])project (
str|None)worklist_id (
str|None)imported_from (
str|None)author_email (
str|None)model_id (
str|None)
- Return type:
str
- add_line_annotation(point1, point2, resource, identifier, frame_index=None, slice_plane=None, metadata=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 – 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|None) – (DEPRECATED) 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.
- Return type:
str
Example
resource = api.resources.get_list(project_name='Example Project')[0] api.annotations.add_line_annotation( [0, 0], (10, 30), resource_id=resource.id, identifier='Line1', frame_index=2, project='Example Project', )
- Parameters:
resource (
str|Resource)slice_plane (
Literal['axial','sagittal','coronal'] |None)metadata (
Dataset|Nifti1Image|None)
- approve(annotation)
Approve an annotation.
- Parameters:
annotation (
str|Annotation) – The annotation unique id or Annotation instance.- Return type:
None
- bulk_download_file(annotations, save_paths)
Alias for
download_multiple_files()- Parameters:
annotations (
Sequence[str|Annotation])save_paths (
Sequence[str|Path] |str)
- Return type:
list[dict[str,Any]]
- create(resource, annotation_dto)
Create one or more annotations for a resource.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource instance.annotation_dto (
CreateAnnotationDto|Annotation|dict[str,Any] |Sequence[CreateAnnotationDto|Annotation|dict[str,Any]]) – A create DTO, typed annotation entity, raw payload dictionary, or a sequence of those values.
- Return type:
Any- Returns:
The id of the created annotation if a single annotation was provided, or a list of ids if multiple annotations were created.
- create_image_classification(resource, identifier, value, imported_from=None, model_id=None)
Create an image-level classification annotation.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource instance.identifier (
str) – The annotation identifier/label.value (
str) – The classification value.imported_from (
str|None) – The imported from source value.model_id (
str|None) – The model unique id.
- Return type:
str- Returns:
The id of the created annotation.
- delete_batch(annotation_ids)
Delete multiple annotations in a single request.
- Parameters:
annotation_ids (
list[str|Annotation]) – List of annotation unique ids or Annotation instances.- Return type:
None
- download_file(annotation, fpath_out=None)
Download the segmentation file for a given resource and annotation.
- Parameters:
annotation (
str|Annotation) – The annotation unique id or an annotation object.fpath_out (
str|PathLike|None) – (Optional) The file path to save the downloaded segmentation file.
- Returns:
The content of the downloaded segmentation file in bytes format.
- Return type:
bytes
- download_multiple_files(annotations, save_paths)
Download multiple segmentation files and save them to the specified paths.
- Parameters:
annotations (
Sequence[str|Annotation]) – A list of annotation unique ids or annotation objects.save_paths (
Sequence[str|Path] |str) – A list of paths to save the files or a directory path.
- Return type:
list[dict[str,Any]]- Returns:
List of dictionaries with ‘success’, ‘annotation_id’, and optional ‘error’ keys.
Note
If any downloads fail, they will be logged but the process will continue. A summary of failed downloads will be logged at the end.
- get_list(resource=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, limit=None, group_by_resource=False, **kwargs)
- Overloads:
self, resource (str | Resource | Sequence[str | Resource] | None), annotation_type (AnnotationType | str | None), annotator_email (str | None), date_from (date | None), date_to (date | None), dataset_id (str | None), worklist_id (str | None), status (Literal[‘new’, ‘published’] | None), load_ai_segmentations (bool | None), limit (int | None), group_by_resource (Literal[False]) → Sequence[Annotation]
self, resource (str | Resource | Sequence[str | Resource] | None), annotation_type (AnnotationType | str | None), annotator_email (str | None), date_from (date | None), date_to (date | None), dataset_id (str | None), worklist_id (str | None), status (Literal[‘new’, ‘published’] | None), load_ai_segmentations (bool | None), limit (int | None), group_by_resource (Literal[True]) → Sequence[Sequence[Annotation]]
Retrieve a list of annotations with optional filtering.
- Parameters:
resource (
str|Resource|Sequence[str|Resource] |None) – The resource unique id(s) or Resource instance(s). Can be a single resource, a list of resources, or None to retrieve annotations from all resources.annotation_type (
AnnotationType|str|None) – Filter by annotation type (e.g., ‘segmentation’, ‘category’).annotator_email (
str|None) – Filter by annotator email address.date_from (
date|None) – Filter annotations created on or after this date.date_to (
date|None) – Filter annotations created on or before this date.dataset_id (
str|None) – Filter by dataset unique id.worklist_id (
str|None) – Filter by annotation worklist unique id.status (
Literal['new','published'] |None) – Filter by annotation status (‘new’ or ‘published’).load_ai_segmentations (
bool|None) – Whether to load AI-generated segmentations.limit (
int|None) – Maximum number of annotations to return.group_by_resource (
bool) – If True, return results grouped by resource. For instance, the first index of the returned list will contain all annotations for the first resource.
- Returns:
List of annotations, or list of lists if grouped by resource.
- Return type:
Sequence[Annotation] | Sequence[Sequence[Annotation]]
Example
resource = api.resources.get_list(project_name='Liver Review')[0] # Get all annotations for a single resource annotations = api.annotations.get_list(resource=resource) # Get annotations with filters published_segmentations = api.annotations.get_list( resource=resource, annotation_type='segmentation', status='published' ) # Get annotations for multiple resources resources = api.resources.get_list(project_name='Liver Review')[:3] annotations_by_resource = api.annotations.get_list( resource=resources, group_by_resource=True, )
- Parameters:
kwargs (
Any)
- patch(annotation, identifier=None, project_id=None)
Partially update an annotation’s metadata.
- Parameters:
annotation (
str|Annotation) – The annotation unique id or Annotation instance.identifier (
str|None) – Optional new identifier/label for the annotation.project_id (
str|None) – Optional project ID to associate with the annotation.
- Raises:
DatamintException – If the update fails.
- Return type:
None
- static standardize_segmentation_names(name)
Standardize segmentation names to a consistent format.
- Parameters:
name (
str|dict|None) – The name input in various formats.- Return type:
dict- Returns:
Standardized name dictionary.
- upload_annotation_file(resource, annotation_id, file, content_type=None, filename=None)
Upload a file for an existing annotation.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource instance.annotation_id (
str) – The annotation unique id.file (
str|IO) – Path to the file or a file-like object.content_type (
str|None) – The MIME type of the file.filename (
str|None) – Optional filename to use in the upload. If None and file is a path, the basename of the path will be used.
- Raises:
DatamintException – If the upload fails.
- async upload_annotation_file_async(resource, annotation_id, file, content_type=None, filename=None, session=None)
Upload a file for an existing annotation asynchronously.
- Parameters:
resource (
str|Resource) – The resource unique id or Resource instance.annotation_id (
str) – The annotation unique id.file (
str|IO) – Path to the file or a file-like object.content_type (
str|None) – The MIME type of the file.filename (
str|None) – Optional filename to use in the upload. If None and file is a path, the basename of the path will be used.session (
ClientSession|None)
- Raises:
DatamintException – If the upload fails.
- upload_segmentations(resource, file_path, name=None, frame_index=None, imported_from=None, author_email=None, discard_empty_segmentations=True, worklist_id=None, transpose_segmentation=False, ai_model_name=None)
Upload frame-by-frame segmentations to a resource.
For volume (3D) segmentations, use
upload_volume_segmentation()instead.- Parameters:
resource (
str|Resource) – The resource unique ID or Resource instance.file_path (
str|Path|ndarray) – The path to the segmentation file or a numpy array. Supported numpy array shapes: - (height, width) or (height, width, #frames) for grayscale segmentations - (3, height, width, #frames) for RGB segmentationsname (
str|dict[int,str] |dict[tuple,str] |None) – The name of the segmentation. Can be: - str: Single name for all segmentations - dict[int, str]: Mapping pixel values to names for grayscale segmentations - dict[tuple[int, int, int], str]: Mapping RGB tuples to names for RGB segmentations Use ‘default’ as a key for unnamed classes. Example: {(255, 0, 0): ‘Red_Region’, (0, 255, 0): ‘Green_Region’}frame_index (
int|list[int] |None) – 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, segmentations are assumed to be in sequential order starting from 0.imported_from (
str|None) – The imported from value.author_email (
str|None) – The author email.discard_empty_segmentations (
bool) – Whether to discard empty segmentations or not.worklist_id (
str|None) – The annotation worklist unique id.model_id – The model unique id.
transpose_segmentation (
bool) – Whether to transpose the segmentation or not.ai_model_name (
str|None) – Optional AI model name to associate with the segmentation.
- Return type:
list[str]- Returns:
List of segmentation unique ids.
- Raises:
ItemNotFoundError – If the item does not exist or the segmentation is invalid.
FileNotFoundError – If the file path does not exist.
ValueError – If a NIfTI file is provided (use
upload_volume_segmentationinstead).
Example
resource = api.resources.get_list(filename='frame.png')[0] # Grayscale segmentation api.annotations.upload_segmentations( resource, 'path/to/segmentation.png', 'SegmentationName' ) # RGB segmentation with numpy array seg_data = np.random.randint(0, 3, size=(3, 2140, 1760, 1), dtype=np.uint8) rgb_names = {(1, 0, 0): 'Red_Region', (0, 1, 0): 'Green_Region', (0, 0, 1): 'Blue_Region'} api.annotations.upload_segmentations(resource, seg_data, rgb_names)
- upload_volume_segmentation(resource, file_path, name=None, imported_from=None, author_email=None, worklist_id=None, ai_model_name=None, transpose_segmentation=False)
Upload a 3D volume segmentation to a resource.
Supports NIfTI files (.nii, .nii.gz) and 3D numpy arrays.
- Parameters:
resource (
str|Resource) – The resource unique ID or Resource instance.file_path (
str|Path|ndarray) – Path to a NIfTI segmentation file (.nii or .nii.gz), or a 3D numpy array of shape (X, Y, Z) with integer label values.name (
dict[int,str] |None) – Mapping of integer label values to segmentation names. Example: {1: ‘liver’, 2: ‘tumor’}imported_from (
str|None) – The imported from value.author_email (
str|None) – The author email.worklist_id (
str|None) – The annotation worklist unique id.ai_model_name (
str|None) – The AI model name.transpose_segmentation (
bool) – Whether to transpose the segmentation before uploading.
- Return type:
list[str]- Returns:
List of annotation unique ids created.
- Raises:
ItemNotFoundError – If the item does not exist.
FileNotFoundError – If the file path does not exist.
ValueError – If the file format is unsupported.
Example
resource = api.resources.get_list(filename='volume.nii.gz')[0] # From NIfTI file api.annotations.upload_volume_segmentation( resource, 'path/to/segmentation.nii.gz', {1: 'liver', 2: 'tumor'} ) # From numpy array vol = np.zeros((256, 256, 64), dtype=np.uint8) api.annotations.upload_volume_segmentation(resource, vol, {1: 'liver'})
Channels API
Channels API endpoint for managing channel resources.
This module provides functionality to interact with channels, which are collections of resources grouped together for batch processing or organization purposes.
- class datamint.api.endpoints.channels_api.ChannelsApi(config, client=None)
Bases:
EntityBaseApi[Channel]API client for channel-related operations.
- Parameters:
client (
Client|None)
Users API
- class datamint.api.endpoints.users_api.UsersApi(config, client=None)
Bases:
CreatableEntityApi[User]- Parameters:
config (
ApiConfig)client (
Client|None)
- create(email, password=None, firstname=None, lastname=None, roles=None, exists_ok=False)
Create a new user.
- Parameters:
email (
str) – The user’s email address.password (
str|None) – The user’s password. If None, a random password will be generated.firstname (
str|None) – The user’s first name.lastname (
str|None) – The user’s last name.roles (
list[str] |None) – List of roles to assign to the user.exists_ok (
bool) – IfTrue, do not raise an error when a user with the same email already exists. Instead, the existing user’s id is returned when possible.
- Return type:
str- Returns:
The id of the created user.
- delete_user(email)
Delete a user by email address.
- Parameters:
email (
str) – The user’s email address.- Return type:
None
- get_by_email(email)
Get a user by email address.
- Parameters:
email (
str) – The user’s email address.- Return type:
- Returns:
The User instance.
- get_invitations(project_id=None)
List pending user invitations.
- Parameters:
project_id (
str|None) – Optional project ID to filter invitations.- Return type:
list[dict]- Returns:
List of invitation dicts.
- invite(email, firstname=None, lastname=None, return_url=None, project_id=None, project_roles=None, annotation_worklist_id=None)
Send an invitation email to a new user.
- Parameters:
email (
str) – The invitee’s email address.firstname (
str|None) – The invitee’s first name.lastname (
str|None) – The invitee’s last name.return_url (
str|None) – URL the invite link should redirect to after acceptance.project_id (
str|None) – Optional project to add the invitee to.project_roles (
list[str] |None) – Roles to assign in the given project.annotation_worklist_id (
str|None) – Optional annotation worklist to associate.
- Return type:
dict- Returns:
The server response as a dict.
- revoke_invitation(email)
Revoke a pending invitation by the invitee’s email.
- Parameters:
email (
str) – The invitee’s email address.- Return type:
None
- update_user(email, **kwargs)
Partially update a user’s profile.
- Parameters:
email (
str) – The user’s email address.**kwargs – Fields to update (e.g.
firstname,lastname,roles).
- Return type:
None
Annotation Sets API
- class datamint.api.endpoints.annotationsets_api.AnnotationSetsApi(config, client=None)
Bases:
BaseApi- Parameters:
config (
ApiConfig)client (
Client|None)
- ENDPOINT_BASE = '/annotationsets'
- create(name, resource_ids, description=None, annotations=None, annotators=None, frame_labels=None, image_labels=None)
Create a new annotation worklist.
- Parameters:
name (
str) – Name of the annotation worklist.resource_ids (
list[str]) – List of resource IDs to include.description (
str|None) – Optional description.annotations (
list[dict] |None) – Optional list of annotation spec dicts.annotators (
list[str] |None) – Optional list of annotator email addresses.frame_labels (
list[str] |None) – Optional list of frame label names.image_labels (
list[str] |None) – Optional list of image label names.
- Return type:
str- Returns:
The ID of the created annotation set.
- get_annotations_specs(annotation_set)
Get the annotations specs for a given annotation set ID or Project.
- Parameters:
annotation_set (
str|Project)- Return type:
Sequence[AnnotationSpec]
- get_segmentation_group(annotation_set)
Get the segmentation group for a given annotation set ID or Project.
- Parameters:
annotation_set (
str|Project)- Return type:
dict
- update(annotation_set_id, **kwargs)
Partially update an annotation worklist.
- Parameters:
annotation_set_id (
str) – The annotation set ID to update.**kwargs – Fields to update (e.g.
name,annotators,resource_ids,status).
- Return type:
None
- update_segmentation_group(annotation_set, definitions, segmentation_value_type='single_label', renames=None)
Replace the segmentation-group definitions for an annotation set.
- Parameters:
annotation_set (
str|Project) – The annotation set ID or Project instance.definitions (
list[dict]) – List of definition dicts with keysidentifier,color, andindex.segmentation_value_type (
str) –'single_label'(default) or'multi_label'.renames (
list[str] |None) – Optional rename pairs (old→new identifier strings).
- Return type:
None
Models API
Deprecated: Use MLFlow API instead.
- class datamint.api.endpoints.models_api.ModelsApi(config, client=None)
Bases:
BaseApiAPI handler for project-related endpoints.
- Parameters:
config (
ApiConfig)client (
Client|None)
- create(name)
- Parameters:
name (
str)- Return type:
dict
- get_all()
- Return type:
Sequence[dict]
- get_by_name(name)
- Parameters:
name (
str)- Return type:
dict|None
Deploy Model API
- class datamint.api.endpoints.deploy_model_api.DeployModelApi(config, client=None)
Bases:
EntityBaseApi[DeployJob]API handler for model deployment endpoints.
- Parameters:
config (
ApiConfig)client (
Client|None)
- cancel(job)
Cancel a deployment job.
- Parameters:
job (
str|DeployJob)- Return type:
bool
- get_by_id(entity_id)
Get deployment job status by ID.
- Parameters:
entity_id (
str)- Return type:
DeployJob
- image_exists(model_name, tag='champion')
Check if a model image exists.
- Parameters:
model_name (
str)tag (
str)
- Return type:
bool
- list_active_jobs()
List active deployment jobs count.
- Return type:
dict
- list_images(model_name=None)
List deployed model images.
- Parameters:
model_name (
str|None)- Return type:
list[dict]
- remove_image(model_name, tag=None)
Remove a deployed model image.
- Parameters:
model_name (
str)tag (
str|None)
- Return type:
dict
- start(model_name, model_version=None, model_alias=None, image_name=None, with_gpu=False, convert_to_onnx=False, input_shape=None)
Start a new deployment job.
- Parameters:
model_name (
str)model_version (
int|None)model_alias (
str|None)image_name (
str|None)with_gpu (
bool)convert_to_onnx (
bool)input_shape (
list[int] |None)
- Return type:
DeployJob
Inference API
API handler for model inference endpoints (MLflow DataMint server).
- class datamint.api.endpoints.inference_api.InferenceApi(config, client=None)
Bases:
EntityBaseApi[InferenceJob]API handler for model inference endpoints.
Provides methods to submit inference jobs, poll their status, cancel running jobs, and use specialised prediction endpoints (image, frame, slice, volume).
- Parameters:
config (
ApiConfig)client (
Client|None)
- cancel(job)
Cancel a running inference job.
- Parameters:
job (
str|InferenceJob) – Job ID string orInferenceJobentity.- Return type:
bool- Returns:
Trueif the cancellation was acknowledged.
- get_by_id(entity_id)
Alias for
get_statusto satisfyEntityBaseApiinterface.- Parameters:
entity_id (
str)- Return type:
- get_status(job_id)
Get the current status of an inference job.
- Parameters:
job_id (
str) – The job identifier.- Return type:
- Returns:
An
InferenceJobpopulated with the latest status.
- predict(model_name, *, model_version=None, model_alias=None, resource_id=None, file_path=None, file_paths=None, save_results=False, params=None)
Submit an inference job for background processing.
- Parameters:
model_name (
str) – Name of the registered model.model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias (e.g.'champion').resource_id (
str|None) – Single resource ID from DataMint API.resource_ids – List of resource IDs.
file_path (
str|None) – Local file path.file_paths (
list[str] |None) – List of local file paths.save_results (
bool) – Whether to save results to the API.params (
dict[str,Any] |None) – Additional parameters forwarded to the model.
- Return type:
- Returns:
The created
InferenceJob(with initial status).
- predict_frame(model_name, frame_index, *, model_version=None, model_alias=None, resource_id=None, file_path=None, save_results=False, params=None)
Submit a frame-specific prediction job (for video resources).
- Parameters:
model_name (
str) – Name of the registered model.frame_index (
int) – Frame index to process.model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias.resource_id (
str|None) – Resource ID from DataMint API.file_path (
str|None) – Local file path.save_results (
bool) – Whether to save results.params (
dict[str,Any] |None) – Additional parameters.
- Return type:
- Returns:
The created
InferenceJob.
- predict_image(model_name, *, model_version=None, model_alias=None, resource_id=None, file_path=None, save_results=False, params=None)
Submit an image prediction job.
- Parameters:
model_name (
str) – Name of the registered model.model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias (e.g.'champion').resource_id (
str|None) – Resource ID from DataMint API.file_path (
str|None) – Local file path.save_results (
bool) – Whether to save results.params (
dict[str,Any] |None) – Additional parameters.
- Return type:
- Returns:
The created
InferenceJob.
- predict_slice(model_name, slice_index, axis, *, model_version=None, model_alias=None, resource_id=None, file_path=None, save_results=False, params=None)
Submit a slice-specific prediction job for 3D volumes.
- Parameters:
model_name (
str) – Name of the registered model.slice_index (
int) – Slice index to process.axis (
Literal['axial','sagittal','coronal']) – Anatomical axis ('axial','sagittal', or'coronal').model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias.resource_id (
str|None) – Resource ID from DataMint API.file_path (
str|None) – Local file path.save_results (
bool) – Whether to save results.params (
dict[str,Any] |None) – Additional parameters.
- Return type:
- Returns:
The created
InferenceJob.
- predict_volume(model_name, *, model_version=None, model_alias=None, resource_id=None, file_path=None, save_results=False, params=None)
Submit a volume prediction job.
- Parameters:
model_name (
str) – Name of the registered model.model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias.resource_id (
str|None) – Resource ID from DataMint API.file_path (
str|None) – Local file path.save_results (
bool) – Whether to save results.params (
dict[str,Any] |None) – Additional parameters.
- Return type:
- Returns:
The created
InferenceJob.
- stream_status(job_id)
Stream status updates for an inference job via Server-Sent Events.
Yields dictionaries parsed from SSE
data:lines until the stream is closed by the server.- Parameters:
job_id (
str) – The job identifier.- Yields:
Parsed JSON dictionaries for each SSE event.
- submit(model_name, *, model_version=None, model_alias=None, resource_id=None, file_path=None, file_paths=None, save_results=False, params=None)
Submit an inference job for background processing.
- Parameters:
model_name (
str) – Name of the registered model.model_version (
int|None) – Specific model version number.model_alias (
str|None) – Model alias (e.g.'champion').resource_id (
str|None) – Single resource ID from DataMint API.resource_ids – List of resource IDs.
file_path (
str|None) – Local file path.file_paths (
list[str] |None) – List of local file paths.save_results (
bool) – Whether to save results to the API.params (
dict[str,Any] |None) – Additional parameters forwarded to the model.
- Return type:
- Returns:
The created
InferenceJob(with initial status).
- wait(job, *, on_status=None, poll_interval=2.0, timeout=1800)
Block until an inference job reaches a terminal state.
First attempts to follow the SSE stream. If the stream is unavailable or drops early the method falls back to polling
get_statusat poll_interval seconds.- Parameters:
job (
str|InferenceJob) – Job ID string orInferenceJobentity. In-place updates to the providedInferenceJobare made on every status change.on_status (
Callable[[InferenceJob],None] |None) – Optional callback invoked with an updatedInferenceJobeach time a status update is received.poll_interval (
float) – Seconds between polls when falling back to polling mode. Default2.0.timeout (
float|None) – Maximum seconds to wait.Nonemeans wait indefinitely. RaisesTimeoutErroron expiry.
- Raises:
TimeoutError – If timeout is set and the job has not finished within that duration.
- Return type:
None