跳至内容

参考资料 hub_sdk/modules/projects.py

备注

该文件可在https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/projects.py 下找到。如果您发现问题,请通过提交 Pull Request🛠️ 帮助修复。谢谢🙏!



hub_sdk.modules.projects.Projects

垒球 CRUDClient

一个代表客户端的类,用于通过 CRUD 操作与项目进行交互。该类扩展了 CRUDClient 类,并提供与项目打交道的特定方法。

属性

名称 类型 说明
hub_client ProjectUpload

用于与模型上传交互的 ProjectUpload 实例。

id (str, None)

项目的唯一标识符(如果有)。

data dict

用于存储项目数据的字典。

备注

id "属性在初始化过程中设置,可用于唯一标识项目。 data "属性用于存储从应用程序接口获取的项目数据。

源代码 hub_sdk/modules/projects.py
class Projects(CRUDClient):
    """
    A class representing a client for interacting with Projects through CRUD operations. This class extends the
    CRUDClient class and provides specific methods for working with Projects.

    Attributes:
        hub_client (ProjectUpload): An instance of ProjectUpload used for interacting with model uploads.
        id (str, None): The unique identifier of the project, if available.
        data (dict): A dictionary to store project data.

    Note:
        The 'id' attribute is set during initialization and can be used to uniquely identify a project.
        The 'data' attribute is used to store project data fetched from the API.
    """

    def __init__(self, project_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
        """
        Initialize a Projects object for interacting with project data via CRUD operations.

        Args:
            project_id (str, optional): Project ID for retrieving data.
            headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
        """
        super().__init__("projects", "project", headers)
        self.hub_client = ProjectUpload(headers)
        self.id = project_id
        self.data = {}
        if project_id:
            self.get_data()

    def get_data(self) -> None:
        """
        Retrieves data for the current project instance.

        If a valid project ID has been set, it sends a request to fetch the project data and stores it in the instance.
        If no project ID has been set, it logs an error message.

        Returns:
            (None): The method does not return a value.
        """
        if not self.id:
            self.logger.error("No project id has been set. Update the project id or create a project.")
            return

        try:
            response = super().read(self.id)

            if response is None:
                self.logger.error(f"Received no response from the server for project ID: {self.id}")
                return

            # Check if the response has a .json() method (it should if it's a response object)
            if not hasattr(response, "json"):
                self.logger.error(f"Invalid response object received for project ID: {self.id}")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error(f"No data received in the response for project ID: {self.id}")
                return

            self.data = resp_data.get("data", {})
            self.logger.debug(f"Project data retrieved for id ID: {self.id}")

        except Exception as e:
            self.logger.error(f"An error occurred while retrieving data for project ID: {self.id}, {e}")

    def create_project(self, project_data: dict) -> None:
        """
        Creates a new project with the provided data and sets the project ID for the current instance.

        Args:
            project_data (dict): A dictionary containing the data for creating the project.

        Returns:
            (None): The method does not return a value.
        """
        resp = super().create(project_data).json()
        self.id = resp.get("data", {}).get("id")
        self.get_data()

    def delete(self, hard: Optional[bool] = False) -> Optional[Response]:
        """
        Delete the project resource represented by this instance.

        Args:
            hard (bool, optional): If True, perform a hard (permanent) delete.

        Note:
            The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
            In a soft delete, the project might be marked as deleted but retained in the system.
            In a hard delete, the project is permanently removed from the system.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails.
        """
        return super().delete(self.id, hard)

    def update(self, data: dict) -> Optional[Response]:
        """
        Update the project resource represented by this instance.

        Args:
            data (dict): The updated data for the project resource.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails.
        """
        return super().update(self.id, data)

    def upload_image(self, file: str) -> Optional[Response]:
        """
        Uploads an image file to the hub associated with this client.

        Args:
            file (str): The file path or URL of the image to be uploaded.

        Returns:
            (Optional[Response]): Response object from the uploaded image request, or None if upload fails.
        """
        return self.hub_client.upload_image(self.id, file)  # response

__init__(project_id=None, headers=None)

初始化项目对象,以便通过 CRUD 操作与项目数据交互。

参数

名称 类型 说明 默认值
project_id str

用于检索数据的项目 ID。

None
headers dict

将包含在 API 请求中的 HTTP 标头字典。

None
源代码 hub_sdk/modules/projects.py
def __init__(self, project_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
    """
    Initialize a Projects object for interacting with project data via CRUD operations.

    Args:
        project_id (str, optional): Project ID for retrieving data.
        headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
    """
    super().__init__("projects", "project", headers)
    self.hub_client = ProjectUpload(headers)
    self.id = project_id
    self.data = {}
    if project_id:
        self.get_data()

create_project(project_data)

使用提供的数据创建新项目,并为当前实例设置项目 ID。

参数

名称 类型 说明 默认值
project_data dict

包含用于创建项目的数据的字典。

所需

返回:

类型 说明
None

该方法不返回值。

源代码 hub_sdk/modules/projects.py
def create_project(self, project_data: dict) -> None:
    """
    Creates a new project with the provided data and sets the project ID for the current instance.

    Args:
        project_data (dict): A dictionary containing the data for creating the project.

    Returns:
        (None): The method does not return a value.
    """
    resp = super().create(project_data).json()
    self.id = resp.get("data", {}).get("id")
    self.get_data()

delete(hard=False)

删除该实例所代表的项目资源。

参数

名称 类型 说明 默认值
hard bool

如果为 True,则执行硬(永久)删除。

False
备注

硬 "参数决定执行软删除(默认)还是硬删除。 在软删除中,项目可能被标记为已删除,但仍保留在系统中。 在硬删除中,项目将从系统中永久删除。

返回:

类型 说明
Optional[Response]

删除请求的响应对象;如果删除失败,则为 "无"。

源代码 hub_sdk/modules/projects.py
def delete(self, hard: Optional[bool] = False) -> Optional[Response]:
    """
    Delete the project resource represented by this instance.

    Args:
        hard (bool, optional): If True, perform a hard (permanent) delete.

    Note:
        The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
        In a soft delete, the project might be marked as deleted but retained in the system.
        In a hard delete, the project is permanently removed from the system.

    Returns:
        (Optional[Response]): Response object from the delete request, or None if delete fails.
    """
    return super().delete(self.id, hard)

get_data()

读取当前项目实例的数据。

如果设置了有效的项目 ID,它就会发送请求获取项目数据并将其存储到实例中。 如果没有设置项目 ID,则会记录一条错误信息。

返回:

类型 说明
None

该方法不返回值。

源代码 hub_sdk/modules/projects.py
def get_data(self) -> None:
    """
    Retrieves data for the current project instance.

    If a valid project ID has been set, it sends a request to fetch the project data and stores it in the instance.
    If no project ID has been set, it logs an error message.

    Returns:
        (None): The method does not return a value.
    """
    if not self.id:
        self.logger.error("No project id has been set. Update the project id or create a project.")
        return

    try:
        response = super().read(self.id)

        if response is None:
            self.logger.error(f"Received no response from the server for project ID: {self.id}")
            return

        # Check if the response has a .json() method (it should if it's a response object)
        if not hasattr(response, "json"):
            self.logger.error(f"Invalid response object received for project ID: {self.id}")
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error(f"No data received in the response for project ID: {self.id}")
            return

        self.data = resp_data.get("data", {})
        self.logger.debug(f"Project data retrieved for id ID: {self.id}")

    except Exception as e:
        self.logger.error(f"An error occurred while retrieving data for project ID: {self.id}, {e}")

update(data)

更新该实例所代表的项目资源。

参数

名称 类型 说明 默认值
data dict

项目资源的最新数据。

所需

返回:

类型 说明
Optional[Response]

更新请求的响应对象;如果更新失败,则为 "无"。

源代码 hub_sdk/modules/projects.py
def update(self, data: dict) -> Optional[Response]:
    """
    Update the project resource represented by this instance.

    Args:
        data (dict): The updated data for the project resource.

    Returns:
        (Optional[Response]): Response object from the update request, or None if update fails.
    """
    return super().update(self.id, data)

upload_image(file)

将图像文件上传到与该客户端关联的集线器。

参数

名称 类型 说明 默认值
file str

要上传图片的文件路径或 URL。

所需

返回:

类型 说明
Optional[Response]

上传图片请求的响应对象;如果上传失败,则为 "无"。

源代码 hub_sdk/modules/projects.py
def upload_image(self, file: str) -> Optional[Response]:
    """
    Uploads an image file to the hub associated with this client.

    Args:
        file (str): The file path or URL of the image to be uploaded.

    Returns:
        (Optional[Response]): Response object from the uploaded image request, or None if upload fails.
    """
    return self.hub_client.upload_image(self.id, file)  # response



hub_sdk.modules.projects.ProjectList

垒球 PaginatedList

源代码 hub_sdk/modules/projects.py
class ProjectList(PaginatedList):
    def __init__(self, page_size: int = None, public: bool = None, headers: dict = None):
        """
        Initialize a ProjectList instance.

        Args:
            page_size (int, optional): The number of items to request per page.
            public (bool, optional): Whether the items should be publicly accessible.
            headers (dict, optional): Headers to be included in API requests.
        """
        base_endpoint = "projects"
        super().__init__(base_endpoint, "project", page_size, public, headers)

__init__(page_size=None, public=None, headers=None)

初始化一个 ProjectList 实例。

参数

名称 类型 说明 默认值
page_size int

每页要申请的项目数。

None
public bool

项目是否应向公众开放。

None
headers dict

应包含在 API 请求中的标头。

None
源代码 hub_sdk/modules/projects.py
def __init__(self, page_size: int = None, public: bool = None, headers: dict = None):
    """
    Initialize a ProjectList instance.

    Args:
        page_size (int, optional): The number of items to request per page.
        public (bool, optional): Whether the items should be publicly accessible.
        headers (dict, optional): Headers to be included in API requests.
    """
    base_endpoint = "projects"
    super().__init__(base_endpoint, "project", page_size, public, headers)