Saltar al contenido

Referencia para hub_sdk/modules/teams.py

Nota

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



hub_sdk.modules.teams.Teams

Bases: CRUDClient

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

Atributos:

Nombre Tipo Descripci贸n
id (str, None)

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

data dict

Un diccionario para almacenar los datos del equipo.

Nota

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

C贸digo fuente en hub_sdk/modules/teams.py
class Teams(CRUDClient):
    """
    A class representing a client for interacting with Teams through CRUD operations. This class extends the CRUDClient
    class and provides specific methods for working with Teams.

    Attributes:
        id (str, None): The unique identifier of the team, if available.
        data (dict): A dictionary to store team data.

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

    def __init__(self, team_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
        """
        Initialize a Teams instance.

        Args:
            team_id (str, optional): The unique identifier of the team.
            headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
        """
        super().__init__("teams", "team", headers)
        self.id = team_id
        self.data = {}
        if team_id:
            self.get_data()

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

        If a valid team ID has been set, it sends a request to fetch the team data and stores it in the instance.
        If no team 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 team id has been set. Update the team id or create a team.")
            return

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

            if response is None:
                self.logger.error(f"Received no response from the server for team 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 team ID: {self.id}")
                return

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

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

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

    def create_team(self, team_data) -> None:
        """
        Creates a new team with the provided data and sets the team ID for the current instance.

        Args:
            team_data (dict): A dictionary containing the data for creating the team.

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

    def delete(self, hard=False) -> Optional[Response]:
        """
        Delete the team 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 team might be marked as deleted but retained in the system.
            In a hard delete, the team is permanently removed from the system.

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

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

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

        Returns:
            (Optional[Response]): The response from the update request, or Noe if it fails.
        """
        return super().update(self.id, data)

__init__(team_id=None, headers=None)

Inicializa una instancia de Equipos.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
team_id str

El identificador 煤nico del equipo.

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/teams.py
def __init__(self, team_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
    """
    Initialize a Teams instance.

    Args:
        team_id (str, optional): The unique identifier of the team.
        headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
    """
    super().__init__("teams", "team", headers)
    self.id = team_id
    self.data = {}
    if team_id:
        self.get_data()

create_team(team_data)

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

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
team_data dict

Un diccionario que contiene los datos para crear el equipo.

necesario

Devuelve:

Tipo Descripci贸n
None

El m茅todo no devuelve ning煤n valor.

C贸digo fuente en hub_sdk/modules/teams.py
def create_team(self, team_data) -> None:
    """
    Creates a new team with the provided data and sets the team ID for the current instance.

    Args:
        team_data (dict): A dictionary containing the data for creating the team.

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

delete(hard=False)

Elimina el recurso de equipo 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 equipo puede marcarse como borrado pero conservarse en el sistema. En un borrado duro, el equipo se elimina permanentemente del sistema.

Devuelve:

Tipo Descripci贸n
Optional[Response]

La respuesta de la solicitud de eliminaci贸n, o Ninguna si falla.

C贸digo fuente en hub_sdk/modules/teams.py
def delete(self, hard=False) -> Optional[Response]:
    """
    Delete the team 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 team might be marked as deleted but retained in the system.
        In a hard delete, the team is permanently removed from the system.

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

get_data()

Recupera los datos de la instancia actual del equipo.

Si se ha establecido un ID de equipo v谩lido, env铆a una petici贸n para obtener los datos del equipo y los almacena en la instancia. Si no se ha establecido ning煤n ID de equipo, 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/teams.py
def get_data(self) -> None:
    """
    Retrieves data for the current team instance.

    If a valid team ID has been set, it sends a request to fetch the team data and stores it in the instance.
    If no team 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 team id has been set. Update the team id or create a team.")
        return

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

        if response is None:
            self.logger.error(f"Received no response from the server for team 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 team ID: {self.id}")
            return

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

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

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

update(data)

Actualiza el recurso de equipo representado por esta instancia.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
data dict

Los datos actualizados del recurso equipo.

necesario

Devuelve:

Tipo Descripci贸n
Optional[Response]

La respuesta de la solicitud de actualizaci贸n, o Noe si falla.

C贸digo fuente en hub_sdk/modules/teams.py
def update(self, data) -> Optional[Response]:
    """
    Update the team resource represented by this instance.

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

    Returns:
        (Optional[Response]): The response from the update request, or Noe if it fails.
    """
    return super().update(self.id, data)



hub_sdk.modules.teams.TeamList

Bases: PaginatedList

C贸digo fuente en hub_sdk/modules/teams.py
class TeamList(PaginatedList):
    def __init__(self, page_size=None, public=None, headers=None):
        """
        Initialize a TeamList 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 = "datasets"
        if public:
            base_endpoint = f"public/{base_endpoint}"
        super().__init__(base_endpoint, "team", page_size, headers)

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

Inicializa una instancia de TeamList.

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/teams.py
def __init__(self, page_size=None, public=None, headers=None):
    """
    Initialize a TeamList 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 = "datasets"
    if public:
        base_endpoint = f"public/{base_endpoint}"
    super().__init__(base_endpoint, "team", page_size, headers)