Skip to content

task

openml._api.resources.task #

TaskV1API #

TaskV1API(http: HTTPClient, minio: MinIOClient)

Bases: ResourceV1API, TaskAPI

Source code in openml/_api/resources/base/base.py
def __init__(self, http: HTTPClient, minio: MinIOClient):
    self._http = http
    self._minio = minio

delete #

delete(resource_id: int) -> bool

Delete a resource using the V1 API.

PARAMETER DESCRIPTION
resource_id

Identifier of the resource to delete.

TYPE: int

RETURNS DESCRIPTION
bool

True if the server confirms successful deletion.

RAISES DESCRIPTION
ValueError

If the resource type is not supported for deletion.

OpenMLNotAuthorizedError

If the user is not permitted to delete the resource.

OpenMLServerError

If deletion fails for an unknown reason.

OpenMLServerException

For other server-side errors.

Source code in openml/_api/resources/base/versions.py
def delete(self, resource_id: int) -> bool:
    """
    Delete a resource using the V1 API.

    Parameters
    ----------
    resource_id : int
        Identifier of the resource to delete.

    Returns
    -------
    bool
        ``True`` if the server confirms successful deletion.

    Raises
    ------
    ValueError
        If the resource type is not supported for deletion.
    OpenMLNotAuthorizedError
        If the user is not permitted to delete the resource.
    OpenMLServerError
        If deletion fails for an unknown reason.
    OpenMLServerException
        For other server-side errors.
    """
    if self.resource_type not in _LEGAL_RESOURCES_DELETE:
        raise ValueError(f"Can't delete a {self.resource_type.value}")

    endpoint_name = self._get_endpoint_name()
    path = f"{endpoint_name}/{resource_id}"
    try:
        response = self._http.delete(path)
        try:
            parsed_response = xmltodict.parse(response.content)
        except xml.parsers.expat.ExpatError as e:
            msg = f"Unexpected response to {path}Could not parse: {response.content!r}"
            raise OpenMLServerError(msg) from e
        return f"oml:{endpoint_name}_delete" in parsed_response
    except OpenMLServerException as e:
        self._handle_delete_exception(endpoint_name, e)
        raise

download_split #

download_split(url: str, *, refresh_cache: bool = False) -> Path

Download a task's split file and return its path in the cache.

PARAMETER DESCRIPTION
url

URL of the split file.

TYPE: str

refresh_cache

Whether to replace the file if it is already cached.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Path
Source code in openml/_api/resources/task.py
def download_split(self, url: str, *, refresh_cache: bool = False) -> Path:
    """Download a task's split file and return its path in the cache.

    Parameters
    ----------
    url : str
        URL of the split file.
    refresh_cache : bool, optional
        Whether to replace the file if it is already cached.

    Returns
    -------
    Path
    """
    self._http.get(url, enable_cache=True, refresh_cache=refresh_cache)
    return self._http.cache_path_from_url(url)

get #

get(task_id: int) -> OpenMLTask

Download OpenML task for a given task ID.

Downloads the task representation.

PARAMETER DESCRIPTION
task_id

The OpenML task id of the task to download.

TYPE: int

RETURNS DESCRIPTION
task

TYPE: OpenMLTask

Source code in openml/_api/resources/task.py
def get(self, task_id: int) -> OpenMLTask:
    """Download OpenML task for a given task ID.

    Downloads the task representation.

    Parameters
    ----------
    task_id : int
        The OpenML task id of the task to download.

    Returns
    -------
    task: OpenMLTask
    """
    response = self._http.get(f"task/{task_id}", enable_cache=True)
    return self._create_task_from_xml(response.text)

list #

list(limit: int, offset: int, task_type: TaskType | int | None = None, *, estimation_procedures: list[dict[str, Any]], **kwargs: Any) -> DataFrame

Perform the api call to return a number of tasks having the given filters.

PARAMETER DESCRIPTION
Filter

it

type

limit

TYPE: int

offset

TYPE: int

task_type

Refers to the type of task.

TYPE: TaskType DEFAULT: None

estimation_procedures

All estimation procedures on OpenML, used to resolve the procedure ids returned by the listing into names.

TYPE: list of dict

kwargs

Legal filter operators: tag, task_id (list), data_tag, status, limit, offset, data_id, data_name, number_instances, number_features, number_classes, number_missing_values.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
dataframe
Source code in openml/_api/resources/task.py
def list(
    self,
    limit: int,
    offset: int,
    task_type: TaskType | int | None = None,
    *,
    estimation_procedures: builtins.list[dict[str, Any]],
    **kwargs: Any,
) -> pd.DataFrame:
    """
    Perform the api call to return a number of tasks having the given filters.

    Parameters
    ----------
    Filter task_type is separated from the other filters because
    it is used as task_type in the task description, but it is named
    type when used as a filter in list tasks call.
    limit: int
    offset: int
    task_type : TaskType, optional
        Refers to the type of task.
    estimation_procedures : list of dict
        All estimation procedures on OpenML, used to resolve the procedure
        ids returned by the listing into names.
    kwargs: dict, optional
        Legal filter operators: tag, task_id (list), data_tag, status, limit,
        offset, data_id, data_name, number_instances, number_features,
        number_classes, number_missing_values.

    Returns
    -------
    dataframe
    """
    api_call = self._build_url(limit, offset, task_type, kwargs)
    return self._parse_list_xml(api_call, estimation_procedures)

publish #

publish(path: str, files: Mapping[str, Any] | None) -> int

Publish a new resource using the V1 API.

PARAMETER DESCRIPTION
path

API endpoint path for the upload.

TYPE: str

files

Files to upload as part of the request payload.

TYPE: Mapping of str to Any or None

RETURNS DESCRIPTION
int

Identifier of the newly created resource.

RAISES DESCRIPTION
ValueError

If the server response does not contain a valid resource ID.

OpenMLServerException

If the server returns an error during upload.

Source code in openml/_api/resources/base/versions.py
def publish(self, path: str, files: Mapping[str, Any] | None) -> int:
    """
    Publish a new resource using the V1 API.

    Parameters
    ----------
    path : str
        API endpoint path for the upload.
    files : Mapping of str to Any or None
        Files to upload as part of the request payload.

    Returns
    -------
    int
        Identifier of the newly created resource.

    Raises
    ------
    ValueError
        If the server response does not contain a valid resource ID.
    OpenMLServerException
        If the server returns an error during upload.
    """
    response = self._http.post(path, files=files)
    try:
        parsed_response = xmltodict.parse(response.content)
    except xml.parsers.expat.ExpatError as e:
        msg = f"Unexpected response to {path}Could not parse: {response.content!r}"
        raise OpenMLServerError(msg) from e
    return self._extract_id_from_upload(parsed_response)

tag #

tag(resource_id: int, tag: str) -> list[str]

Add a tag to a resource using the V1 API.

PARAMETER DESCRIPTION
resource_id

Identifier of the resource to tag.

TYPE: int

tag

Tag to associate with the resource.

TYPE: str

RETURNS DESCRIPTION
list of str

Updated list of tags assigned to the resource.

RAISES DESCRIPTION
ValueError

If the resource type does not support tagging.

OpenMLServerException

If the server returns an error.

Source code in openml/_api/resources/base/versions.py
def tag(self, resource_id: int, tag: str) -> list[str]:
    """
    Add a tag to a resource using the V1 API.

    Parameters
    ----------
    resource_id : int
        Identifier of the resource to tag.
    tag : str
        Tag to associate with the resource.

    Returns
    -------
    list of str
        Updated list of tags assigned to the resource.

    Raises
    ------
    ValueError
        If the resource type does not support tagging.
    OpenMLServerException
        If the server returns an error.
    """
    if self.resource_type not in _LEGAL_RESOURCES_TAG:
        raise ValueError(f"Can't tag a {self.resource_type.value}")

    endpoint_name = self._get_endpoint_name()
    path = f"{endpoint_name}/tag"
    data = {f"{endpoint_name}_id": resource_id, "tag": tag}
    response = self._http.post(path, data=data)

    try:
        parsed_response = xmltodict.parse(response.content, force_list={"oml:tag"})
    except xml.parsers.expat.ExpatError as e:
        msg = f"Unexpected response to {path}Could not parse: {response.content!r}"
        raise OpenMLServerError(msg) from e
    result = parsed_response[f"oml:{endpoint_name}_tag"]
    tags: list[str] = result.get("oml:tag", [])

    return tags

untag #

untag(resource_id: int, tag: str) -> list[str]

Remove a tag from a resource using the V1 API.

PARAMETER DESCRIPTION
resource_id

Identifier of the resource to untag.

TYPE: int

tag

Tag to remove from the resource.

TYPE: str

RETURNS DESCRIPTION
list of str

Updated list of tags assigned to the resource.

RAISES DESCRIPTION
ValueError

If the resource type does not support tagging.

OpenMLServerException

If the server returns an error.

Source code in openml/_api/resources/base/versions.py
def untag(self, resource_id: int, tag: str) -> list[str]:
    """
    Remove a tag from a resource using the V1 API.

    Parameters
    ----------
    resource_id : int
        Identifier of the resource to untag.
    tag : str
        Tag to remove from the resource.

    Returns
    -------
    list of str
        Updated list of tags assigned to the resource.

    Raises
    ------
    ValueError
        If the resource type does not support tagging.
    OpenMLServerException
        If the server returns an error.
    """
    if self.resource_type not in _LEGAL_RESOURCES_TAG:
        raise ValueError(f"Can't untag a {self.resource_type.value}")

    endpoint_name = self._get_endpoint_name()
    path = f"{endpoint_name}/untag"
    data = {f"{endpoint_name}_id": resource_id, "tag": tag}
    response = self._http.post(path, data=data)

    try:
        parsed_response = xmltodict.parse(response.content, force_list={"oml:tag"})
    except xml.parsers.expat.ExpatError as e:
        msg = f"Unexpected response to {path}Could not parse: {response.content!r}"
        raise OpenMLServerError(msg) from e
    result = parsed_response[f"oml:{endpoint_name}_untag"]
    tags: list[str] = result.get("oml:tag", [])

    return tags

TaskV2API #

TaskV2API(http: HTTPClient, minio: MinIOClient)

Bases: ResourceV2API, TaskAPI

Source code in openml/_api/resources/base/base.py
def __init__(self, http: HTTPClient, minio: MinIOClient):
    self._http = http
    self._minio = minio

download_split #

download_split(url: str, *, refresh_cache: bool = False) -> Path

Download a task's split file and return its path in the cache.

PARAMETER DESCRIPTION
url

URL of the split file.

TYPE: str

refresh_cache

Whether to replace the file if it is already cached.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Path
Source code in openml/_api/resources/task.py
def download_split(self, url: str, *, refresh_cache: bool = False) -> Path:
    """Download a task's split file and return its path in the cache.

    Parameters
    ----------
    url : str
        URL of the split file.
    refresh_cache : bool, optional
        Whether to replace the file if it is already cached.

    Returns
    -------
    Path
    """
    self._http.get(url, enable_cache=True, refresh_cache=refresh_cache)
    return self._http.cache_path_from_url(url)

get #

get(task_id: int) -> OpenMLTask

Download OpenML task for a given task ID.

Downloads the task representation.

PARAMETER DESCRIPTION
task_id

The OpenML task id of the task to download.

TYPE: int

RETURNS DESCRIPTION
task

TYPE: OpenMLTask

Source code in openml/_api/resources/task.py
def get(self, task_id: int) -> OpenMLTask:
    """Download OpenML task for a given task ID.

    Downloads the task representation.

    Parameters
    ----------
    task_id : int
        The OpenML task id of the task to download.

    Returns
    -------
    task: OpenMLTask
    """
    response = self._http.get(f"tasks/{task_id}", enable_cache=True)
    return self._create_task_from_json(response.json())