Saltar al contenido

Referencia para hub_sdk/modules/projects.py

Nota

Este archivo est谩 disponible en https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/projects .py. Si detectas alg煤n problema, por favor, ayuda a solucionarlo contribuyendo con una Pull Request 馃洜锔. 隆Gracias 馃檹!



hub_sdk.modules.projects.Projects

Bases: CRUDClient

Una clase que representa a un cliente para interactuar con Proyectos mediante operaciones CRUD. Esta clase extiende la clase CRUDClient y proporciona m茅todos espec铆ficos para trabajar con Proyectos.

Atributos:

Nombre Tipo Descripci贸n
hub_client ProjectUpload

Una instancia de ProjectUpload utilizada para interactuar con las subidas de modelos.

id (str, None)

El identificador 煤nico del proyecto, si est谩 disponible.

data dict

Un diccionario para almacenar los datos del proyecto.

Nota

El atributo "id" se establece durante la inicializaci贸n y puede utilizarse para identificar un proyecto de forma 煤nica. El atributo "datos" se utiliza para almacenar los datos del proyecto obtenidos de la API.

C贸digo fuente en 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)

Inicializa un objeto Proyectos para interactuar con los datos del proyecto mediante operaciones CRUD.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
project_id str

ID del proyecto para recuperar los datos.

None
headers dict

Un diccionario de cabeceras HTTP que deben incluirse en las peticiones de la API.

None
C贸digo fuente en 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)

Crea un nuevo proyecto con los datos proporcionados y establece el ID del proyecto para la instancia actual.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
project_data dict

Un diccionario que contiene los datos para crear el proyecto.

necesario

Devuelve:

Tipo Descripci贸n
None

El m茅todo no devuelve ning煤n valor.

C贸digo fuente en 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)

Elimina el recurso del proyecto representado por esta instancia.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
hard bool

Si es Verdadero, realiza un borrado duro (permanente).

False
Nota

El par谩metro "duro" determina si se realiza un borrado suave (por defecto) o un borrado duro. En un borrado suave, el proyecto puede marcarse como borrado pero conservarse en el sistema. En un borrado duro, el proyecto se elimina permanentemente del sistema.

Devuelve:

Tipo Descripci贸n
Optional[Response]

Objeto de respuesta de la petici贸n de borrado, o Ninguno si el borrado falla.

C贸digo fuente en 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()

Recupera los datos de la instancia actual del proyecto.

Si se ha establecido un ID de proyecto v谩lido, env铆a una petici贸n para obtener los datos del proyecto y los almacena en la instancia. Si no se ha establecido ning煤n ID de proyecto, registra un mensaje de error.

Devuelve:

Tipo Descripci贸n
None

El m茅todo no devuelve ning煤n valor.

C贸digo fuente en 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)

Actualiza el recurso del proyecto representado por esta instancia.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
data dict

Los datos actualizados del recurso del proyecto.

necesario

Devuelve:

Tipo Descripci贸n
Optional[Response]

Objeto de respuesta de la solicitud de actualizaci贸n, o Ninguno si la actualizaci贸n falla.

C贸digo fuente en 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)

Sube un archivo de imagen al hub asociado a este cliente.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
file str

La ruta del archivo o URL de la imagen que se va a subir.

necesario

Devuelve:

Tipo Descripci贸n
Optional[Response]

Objeto de respuesta de la solicitud de imagen subida, o Ninguno si la subida falla.

C贸digo fuente en 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

Bases: PaginatedList

C贸digo fuente en 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)

Inicializa una instancia de ListaDeProyectos.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
page_size int

El n煤mero de elementos a solicitar por p谩gina.

None
public bool

Si los art铆culos deben ser de acceso p煤blico.

None
headers dict

Cabeceras que deben incluirse en las peticiones a la API.

None
C贸digo fuente en 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)