μ½˜ν…μΈ λ‘œ κ±΄λ„ˆλ›°κΈ°

μ°Έμ‘° hub_sdk/modules/models.py

μ°Έκ³ 

이 νŒŒμΌμ€ https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/models .pyμ—μ„œ 확인할 수 μžˆμŠ΅λ‹ˆλ‹€. 문제λ₯Ό λ°œκ²¬ν•˜λ©΄ ν’€ λ¦¬ν€˜μŠ€νŠΈ (πŸ› οΈ)λ₯Ό μ œμΆœν•˜μ—¬ 문제λ₯Ό ν•΄κ²°ν•˜λ„λ‘ λ„μ™€μ£Όμ„Έμš”. κ°μ‚¬ν•©λ‹ˆλ‹€ πŸ™!



hub_sdk.modules.models.Models

베이슀: CRUDClient

CRUD μž‘μ—…μ„ 톡해 λͺ¨λΈκ³Ό μƒν˜Έ μž‘μš©ν•˜κΈ° μœ„ν•œ ν΄λΌμ΄μ–ΈνŠΈλ₯Ό λ‚˜νƒ€λ‚΄λŠ” ν΄λž˜μŠ€μž…λ‹ˆλ‹€. 이 ν΄λž˜μŠ€λŠ” CRUDClient 클래슀λ₯Ό ν™•μž₯ν•˜κ³  λͺ¨λΈ μž‘μ—…μ„ μœ„ν•œ νŠΉμ • λ©”μ„œλ“œλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
base_endpoint str

API의 κΈ°λ³Έ μ—”λ“œν¬μΈνŠΈ URL둜, "models"둜 μ„€μ •ν•©λ‹ˆλ‹€.

hub_client ModelUpload

λͺ¨λΈ μ—…λ‘œλ“œμ™€ μƒν˜Έ μž‘μš©ν•˜λŠ” 데 μ‚¬μš©λ˜λŠ” ModelUpload의 μΈμŠ€ν„΄μŠ€μž…λ‹ˆλ‹€.

id (str, None)

λͺ¨λΈμ˜ 고유 μ‹λ³„μž(μ‚¬μš© κ°€λŠ₯ν•œ 경우)μž…λ‹ˆλ‹€.

data dict

λͺ¨λΈ 데이터λ₯Ό μ €μž₯ν•˜λŠ” μ‚¬μ „μž…λ‹ˆλ‹€.

metrics

λͺ¨λΈ λ©”νŠΈλ¦­μ„ μ €μž₯ν•˜κΈ° μœ„ν•œ 자리 ν‘œμ‹œμž(검색 ν›„ μ‚¬μš© κ°€λŠ₯ν•œ 경우)μž…λ‹ˆλ‹€.

μ°Έκ³ 

'id' 속성은 μ΄ˆκΈ°ν™” 쀑에 μ„€μ •λ˜λ©° λͺ¨λΈμ„ κ³ μœ ν•˜κ²Œ μ‹λ³„ν•˜λŠ” 데 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€. '데이터' 속성은 APIμ—μ„œ κ°€μ Έμ˜¨ λͺ¨λΈ 데이터λ₯Ό μ €μž₯ν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
class Models(CRUDClient):
    """
    A class representing a client for interacting with Models through CRUD operations. This class extends the CRUDClient
    class and provides specific methods for working with Models.

    Attributes:
        base_endpoint (str): The base endpoint URL for the API, set to "models".
        hub_client (ModelUpload): An instance of ModelUpload used for interacting with model uploads.
        id (str, None): The unique identifier of the model, if available.
        data (dict): A dictionary to store model data.
        metrics: Placeholder for storing model metrics, if available after retrieval.

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

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

        Args:
            model_id (str, optional): The unique identifier of the model.
            headers (dict, optional): Headers to be included in API requests.
        """
        self.base_endpoint = "models"
        super().__init__(self.base_endpoint, "model", headers)
        self.hub_client = ModelUpload(headers)
        self.id = model_id
        self.data = {}
        self.metrics = None
        if model_id:
            self.get_data()

    @staticmethod
    def _reconstruct_data(data: dict) -> dict:
        """
        Reconstruct format of model data supported by ultralytics.

        Args:
            data: dict
        Returns:
            (dict): Reconstructed data format
        """
        if not data:
            return data

        data["config"] = {
            "batchSize": data.pop("batch_size", None),
            "epochs": data.pop("epochs", None),
            "imageSize": data.pop("imgsz", None),
            "patience": data.pop("patience", None),
            "device": data.pop("device", None),
            "cache": data.pop("cache", None),
        }

        return data

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

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

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

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

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

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

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

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

        Args:
            model_data (dict): A dictionary containing the data for creating the model.

        Returns:
            (None): The method does not return a value.
        """
        try:
            response = super().create(model_data)

            if response is None:
                self.logger.error("Received no response from the server while creating the model.")
                return

            # Ensuring the response object has the .json() method
            if not hasattr(response, "json"):
                self.logger.error("Invalid response object received while creating the model.")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error("No data received in the response while creating the model.")
                return

            self.id = resp_data.get("data", {}).get("id")

            # Check if the ID was successfully retrieved
            if not self.id:
                self.logger.error("Model ID not found in the response data.")
                return

            self.get_data()

        except Exception as e:
            self.logger.error(f"An error occurred while creating the model: {str(e)}")

    def is_resumable(self) -> bool:
        """
        Check if the model training can be resumed.

        Returns:
            (bool): True if resumable, False otherwise.
        """
        return self.data.get("has_last_weights", False)

    def has_best_weights(self) -> bool:
        """
        Check if the model has best weights saved.

        Returns:
            (bool): True if best weights available, False otherwise.
        """
        return self.data.get("has_best_weights", False)

    def is_pretrained(self) -> bool:
        """
        Check if the model is pretrained.

        Returns:
            (bool): True if pretrained, False otherwise.
        """
        return self.data.get("is_pretrained", False)

    def is_trained(self) -> bool:
        """
        Check if the model is trained.

        Returns:
            (bool): True if trained, False otherwise.
        """
        return self.data.get("status") == "trained"

    def is_custom(self) -> bool:
        """
        Check if the model is custom.

        Returns:
            (bool): True if custom, False otherwise.
        """
        return self.data.get("is_custom", False)

    def get_architecture(self) -> Optional[str]:
        """
        Get the architecture name of the model.

        Returns:
            (Optional[str]): The architecture name followed by '.yaml' or None if not available.
        """
        return self.data.get("cfg")

    def get_dataset_url(self) -> Optional[str]:
        """
        Get the dataset URL associated with the model.

        Returns:
            (Optional[str]): The URL of the dataset or None if not available.
        """
        return self.data.get("data")

    def get_weights_url(self, weight: str = "best") -> Optional[str]:
        """
        Get the URL of the model weights.

        Args:
            weight (str, optional): Type of weights to retrieve.

        Returns:
            (Optional[str]): The URL of the specified weights or None if not available.
        """
        if weight == "last":
            return self.data.get("resume")

        return self.data.get("weights")

    def delete(self, hard: bool = False) -> Optional[Response]:
        """
        Delete the model 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 model might be marked as deleted but retained in the system.
            In a hard delete, the model 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 model resource represented by this instance.

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

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

    def get_metrics(self) -> Optional[List[Dict[str, Any]]]:
        """
        Get metrics to of model.

        Returns:
            (list(dict), optional): The list of metrics objects, or None if it fails.
        """
        if self.metrics:
            return self.metrics

        endpoint = f"{HUB_API_ROOT}/v1/{self.base_endpoint}/{self.id}/metrics"
        try:
            results = self.get(endpoint)
            self.metrics = results.json().get("data")
            return self.metrics
        except Exception as e:
            self.logger.error(f"Model Metrics not found: {e}")

    def upload_model(
        self,
        epoch: int,
        weights: str,
        is_best: bool = False,
        map: float = 0.0,
        final: bool = False,
    ) -> Optional[Response]:
        """
        Upload a model checkpoint to Ultralytics HUB.

        Args:
            epoch (int): The current training epoch.
            weights (str): Path to the model weights file.
            is_best (bool): Indicates if the current model is the best one so far.
            map (float): Mean average precision of the model.
            final (bool): Indicates if the model is the final model after training.

        Returns:
            (Optional[Response]): Response object from the upload request, or None if upload fails.
        """
        return self.hub_client.upload_model(self.id, epoch, weights, is_best=is_best, map=map, final=final)

    def upload_metrics(self, metrics: dict) -> Optional[Response]:
        """
        Upload model metrics to Ultralytics HUB.

        Args:
            metrics (dict):

        Returns:
            (Optional[Response]): Response object from the upload metrics request, or None if it fails.
        """
        return self.hub_client.upload_metrics(self.id, metrics)  # response

    def start_heartbeat(self, interval: int = 60):
        """
        Starts sending heartbeat signals to a remote hub server.

        This method initiates the sending of heartbeat signals to a hub server
        in order to indicate the continued availability and health of the client.

        Args:
            interval (int): The time interval, in seconds, between consecutive heartbeats.

        Returns:
            (None): The method does not return a value.

        Note:
            Heartbeats are essential for maintaining a connection with the hub server
            and ensuring that the client remains active and responsive.
        """
        self.hub_client._register_signal_handlers()
        self.hub_client._start_heartbeats(self.id, interval)

    def stop_heartbeat(self) -> None:
        """
        Stops sending heartbeat signals to a remote hub server.

        This method terminates the sending of heartbeat signals to the hub server,
        effectively signaling that the client is no longer available or active.

        Returns:
            (None): The method does not return a value.

        Note:
            Stopping heartbeats should be done carefully, as it may result in the hub server
            considering the client as disconnected or unavailable.
        """
        self.hub_client._stop_heartbeats()

    def export(self, format: str) -> Optional[Response]:
        """
        Export to Ultralytics HUB.

        Args: format (str): Export format here. Here are supported export [formats](
        https://docs.ultralytics.com/modes/export/#export-formats)

        Returns:
            (Optional[Response]): Response object from the export request, or None if export fails.
        """
        return self.hub_client.export(self.id, format)  # response

    def predict(self, image: str, config: Dict[str, Any]) -> Optional[Response]:
        """
        Predict to Ultralytics HUB.

        Args:
            image (str): The path to the image file.
            config (dict): A configuration for the prediction (JSON).

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

__init__(model_id=None, headers=None)

λͺ¨λΈ μΈμŠ€ν„΄μŠ€λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
model_id str

λͺ¨λΈμ˜ 고유 μ‹λ³„μžμž…λ‹ˆλ‹€.

None
headers dict

API μš”μ²­μ— 포함할 ν—€λ”μž…λ‹ˆλ‹€.

None
의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def __init__(self, model_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
    """
    Initialize a Models instance.

    Args:
        model_id (str, optional): The unique identifier of the model.
        headers (dict, optional): Headers to be included in API requests.
    """
    self.base_endpoint = "models"
    super().__init__(self.base_endpoint, "model", headers)
    self.hub_client = ModelUpload(headers)
    self.id = model_id
    self.data = {}
    self.metrics = None
    if model_id:
        self.get_data()

create_model(model_data)

제곡된 λ°μ΄ν„°λ‘œ μƒˆ λͺ¨λΈμ„ μƒμ„±ν•˜κ³  ν˜„μž¬ μΈμŠ€ν„΄μŠ€μ— λŒ€ν•œ λͺ¨λΈ IDλ₯Ό μ„€μ •ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
model_data dict

λͺ¨λΈ 생성을 μœ„ν•œ 데이터가 ν¬ν•¨λœ μ‚¬μ „μž…λ‹ˆλ‹€.

ν•„μˆ˜

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
None

이 λ©”μ„œλ“œλŠ” 값을 λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def create_model(self, model_data: dict) -> None:
    """
    Creates a new model with the provided data and sets the model ID for the current instance.

    Args:
        model_data (dict): A dictionary containing the data for creating the model.

    Returns:
        (None): The method does not return a value.
    """
    try:
        response = super().create(model_data)

        if response is None:
            self.logger.error("Received no response from the server while creating the model.")
            return

        # Ensuring the response object has the .json() method
        if not hasattr(response, "json"):
            self.logger.error("Invalid response object received while creating the model.")
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error("No data received in the response while creating the model.")
            return

        self.id = resp_data.get("data", {}).get("id")

        # Check if the ID was successfully retrieved
        if not self.id:
            self.logger.error("Model ID not found in the response data.")
            return

        self.get_data()

    except Exception as e:
        self.logger.error(f"An error occurred while creating the model: {str(e)}")

delete(hard=False)

이 μΈμŠ€ν„΄μŠ€λ‘œ ν‘œμ‹œλ˜λŠ” λͺ¨λΈ λ¦¬μ†ŒμŠ€λ₯Ό μ‚­μ œν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
hard bool

True이면 ν•˜λ“œ(영ꡬ) μ‚­μ œλ₯Ό μˆ˜ν–‰ν•©λ‹ˆλ‹€.

False
μ°Έκ³ 

'hard' λ§€κ°œλ³€μˆ˜λŠ” μ†Œν”„νŠΈ μ‚­μ œ(κΈ°λ³Έκ°’)λ₯Ό μˆ˜ν–‰ν• μ§€ μ•„λ‹ˆλ©΄ ν•˜λ“œ μ‚­μ œλ₯Ό μˆ˜ν–‰ν• μ§€λ₯Ό κ²°μ •ν•©λ‹ˆλ‹€. μ†Œν”„νŠΈ μ‚­μ œμ˜ 경우 λͺ¨λΈμ€ μ‚­μ œλœ κ²ƒμœΌλ‘œ ν‘œμ‹œλ˜μ§€λ§Œ μ‹œμŠ€ν…œμ—λŠ” μœ μ§€λ  수 μžˆμŠ΅λ‹ˆλ‹€. ν•˜λ“œ μ‚­μ œμ—μ„œλŠ” λͺ¨λΈμ΄ μ‹œμŠ€ν…œμ—μ„œ 영ꡬ적으둜 μ œκ±°λ©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

μ‚­μ œ μš”μ²­μ˜ 응닡 객체, μ‚­μ œμ— μ‹€νŒ¨ν•œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def delete(self, hard: bool = False) -> Optional[Response]:
    """
    Delete the model 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 model might be marked as deleted but retained in the system.
        In a hard delete, the model 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)

export(format)

Ultralytics HUB둜 내보내기.

인수: ν˜•μ‹(λ¬Έμžμ—΄): 내보내기 ν˜•μ‹μ„ 여기에 μž…λ ₯ν•©λ‹ˆλ‹€. μ§€μ›λ˜λŠ” 내보내기 ν˜•μ‹μ€ λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

내보내기 μš”μ²­μ˜ 응닡 개체, 내보내기가 μ‹€νŒ¨ν•œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def export(self, format: str) -> Optional[Response]:
    """
    Export to Ultralytics HUB.

    Args: format (str): Export format here. Here are supported export [formats](
    https://docs.ultralytics.com/modes/export/#export-formats)

    Returns:
        (Optional[Response]): Response object from the export request, or None if export fails.
    """
    return self.hub_client.export(self.id, format)  # response

get_architecture()

λͺ¨λΈμ˜ μ•„ν‚€ν…μ²˜ 이름을 κ°€μ Έμ˜΅λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[str]

μ•„ν‚€ν…μ²˜ 이름 뒀에 '.yaml'이 μ˜€κ±°λ‚˜ μ‚¬μš©ν•  수 μ—†λŠ” 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def get_architecture(self) -> Optional[str]:
    """
    Get the architecture name of the model.

    Returns:
        (Optional[str]): The architecture name followed by '.yaml' or None if not available.
    """
    return self.data.get("cfg")

get_data()

ν˜„μž¬ λͺ¨λΈ μΈμŠ€ν„΄μŠ€μ— λŒ€ν•œ 데이터λ₯Ό κ²€μƒ‰ν•©λ‹ˆλ‹€.

μœ νš¨ν•œ λͺ¨λΈ IDκ°€ μ„€μ •λ˜μ–΄ 있으면 λͺ¨λΈ 데이터 κ°€μ Έμ˜€κΈ° μš”μ²­μ„ μ „μ†‘ν•˜μ—¬ μΈμŠ€ν„΄μŠ€μ— μ €μž₯ν•©λ‹ˆλ‹€. λͺ¨λΈ IDκ°€ μ„€μ •λ˜μ§€ μ•Šμ€ 경우 였λ₯˜ λ©”μ‹œμ§€λ₯Ό κΈ°λ‘ν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
None

이 λ©”μ„œλ“œλŠ” 값을 λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def get_data(self) -> None:
    """
    Retrieves data for the current model instance.

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

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

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

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

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

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

get_dataset_url()

λͺ¨λΈκ³Ό μ—°κ²°λœ 데이터 집합 URL을 κ°€μ Έμ˜΅λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[str]

데이터 μ§‘ν•©μ˜ URL λ˜λŠ” μ‚¬μš©ν•  수 μ—†λŠ” 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def get_dataset_url(self) -> Optional[str]:
    """
    Get the dataset URL associated with the model.

    Returns:
        (Optional[str]): The URL of the dataset or None if not available.
    """
    return self.data.get("data")

get_metrics()

λͺ¨λΈμ— λŒ€ν•œ λ©”νŠΈλ¦­μ„ κ°€μ Έμ˜΅λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
(list(dict), optional)

λ©”νŠΈλ¦­ 객체 λͺ©λ‘, μ‹€νŒ¨ν•˜λ©΄ μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def get_metrics(self) -> Optional[List[Dict[str, Any]]]:
    """
    Get metrics to of model.

    Returns:
        (list(dict), optional): The list of metrics objects, or None if it fails.
    """
    if self.metrics:
        return self.metrics

    endpoint = f"{HUB_API_ROOT}/v1/{self.base_endpoint}/{self.id}/metrics"
    try:
        results = self.get(endpoint)
        self.metrics = results.json().get("data")
        return self.metrics
    except Exception as e:
        self.logger.error(f"Model Metrics not found: {e}")

get_weights_url(weight='best')

λͺ¨λΈ κ°€μ€‘μΉ˜μ˜ URL을 κ°€μ Έμ˜΅λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
weight str

검색할 κ°€μ€‘μΉ˜ μœ ν˜•μž…λ‹ˆλ‹€.

'best'

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[str]

μ§€μ •λœ κ°€μ€‘μΉ˜μ˜ URL λ˜λŠ” μ‚¬μš©ν•  수 μ—†λŠ” 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def get_weights_url(self, weight: str = "best") -> Optional[str]:
    """
    Get the URL of the model weights.

    Args:
        weight (str, optional): Type of weights to retrieve.

    Returns:
        (Optional[str]): The URL of the specified weights or None if not available.
    """
    if weight == "last":
        return self.data.get("resume")

    return self.data.get("weights")

has_best_weights()

λͺ¨λΈμ— 졜적의 κ°€μ€‘μΉ˜κ°€ μ €μž₯λ˜μ–΄ μžˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
bool

μ΅œμƒμ˜ κ°€μ€‘μΉ˜λ₯Ό μ‚¬μš©ν•  수 있으면 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def has_best_weights(self) -> bool:
    """
    Check if the model has best weights saved.

    Returns:
        (bool): True if best weights available, False otherwise.
    """
    return self.data.get("has_best_weights", False)

is_custom()

λͺ¨λΈμ΄ μ‚¬μš©μž 지정 λͺ¨λΈμΈμ§€ ν™•μΈν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
bool

μ‚¬μš©μž 지정인 경우 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def is_custom(self) -> bool:
    """
    Check if the model is custom.

    Returns:
        (bool): True if custom, False otherwise.
    """
    return self.data.get("is_custom", False)

is_pretrained()

λͺ¨λΈμ΄ 사전 ν•™μŠ΅λ˜μ—ˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
bool

사전 ν•™μŠ΅λœ 경우 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def is_pretrained(self) -> bool:
    """
    Check if the model is pretrained.

    Returns:
        (bool): True if pretrained, False otherwise.
    """
    return self.data.get("is_pretrained", False)

is_resumable()

λͺ¨λΈ νŠΈλ ˆμ΄λ‹μ„ μž¬κ°œν•  수 μžˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
bool

μž¬κ°œν•  수 있으면 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def is_resumable(self) -> bool:
    """
    Check if the model training can be resumed.

    Returns:
        (bool): True if resumable, False otherwise.
    """
    return self.data.get("has_last_weights", False)

is_trained()

λͺ¨λΈμ΄ ν•™μŠ΅λ˜μ—ˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
bool

ν›ˆλ ¨λœ 경우 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def is_trained(self) -> bool:
    """
    Check if the model is trained.

    Returns:
        (bool): True if trained, False otherwise.
    """
    return self.data.get("status") == "trained"

predict(image, config)

Ultralytics HUB둜 μ˜ˆμΈ‘ν•˜μ„Έμš”.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
image str

이미지 파일의 κ²½λ‘œμž…λ‹ˆλ‹€.

ν•„μˆ˜
config dict

μ˜ˆμΈ‘μ— λŒ€ν•œ ꡬ성(JSON).

ν•„μˆ˜

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

예츑 μš”μ²­μ˜ 응닡 객체, μ—…λ‘œλ“œμ— μ‹€νŒ¨ν•˜λ©΄ μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def predict(self, image: str, config: Dict[str, Any]) -> Optional[Response]:
    """
    Predict to Ultralytics HUB.

    Args:
        image (str): The path to the image file.
        config (dict): A configuration for the prediction (JSON).

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

start_heartbeat(interval=60)

원격 ν—ˆλΈŒ μ„œλ²„λ‘œ ν•˜νŠΈλΉ„νŠΈ μ‹ ν˜Έλ₯Ό μ „μ†‘ν•˜κΈ° μ‹œμž‘ν•©λ‹ˆλ‹€.

이 방법은 ν—ˆλΈŒ μ„œλ²„λ‘œ ν•˜νŠΈλΉ„νŠΈ μ‹ ν˜Έ 전솑을 μ‹œμž‘ν•˜μ—¬ 둜 ν•˜νŠΈλΉ„νŠΈ μ‹ ν˜Έλ₯Ό μ „μ†‘ν•˜μ—¬ ν΄λΌμ΄μ–ΈνŠΈμ˜ 지속적인 κ°€μš©μ„±κ³Ό μƒνƒœλ₯Ό ν‘œμ‹œν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
interval int

연속적인 심μž₯ 박동 μ‚¬μ΄μ˜ μ‹œκ°„ 간격(초)μž…λ‹ˆλ‹€.

60

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
None

이 λ©”μ„œλ“œλŠ” 값을 λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

μ°Έκ³ 

ν•˜νŠΈλΉ„νŠΈλŠ” ν—ˆλΈŒ μ„œλ²„μ™€μ˜ μ—°κ²° μƒνƒœλ₯Ό μœ μ§€ν•˜κ³  ν—ˆλΈŒ μ„œλ²„μ™€μ˜ 연결을 μœ μ§€ν•˜κ³  ν΄λΌμ΄μ–ΈνŠΈμ˜ ν™œμ„± μƒνƒœμ™€ 응닡성을 μœ μ§€ν•˜λŠ” 데 ν•„μˆ˜μ μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def start_heartbeat(self, interval: int = 60):
    """
    Starts sending heartbeat signals to a remote hub server.

    This method initiates the sending of heartbeat signals to a hub server
    in order to indicate the continued availability and health of the client.

    Args:
        interval (int): The time interval, in seconds, between consecutive heartbeats.

    Returns:
        (None): The method does not return a value.

    Note:
        Heartbeats are essential for maintaining a connection with the hub server
        and ensuring that the client remains active and responsive.
    """
    self.hub_client._register_signal_handlers()
    self.hub_client._start_heartbeats(self.id, interval)

stop_heartbeat()

원격 ν—ˆλΈŒ μ„œλ²„λ‘œ ν•˜νŠΈλΉ„νŠΈ μ‹ ν˜Έ 전솑을 μ€‘μ§€ν•©λ‹ˆλ‹€.

이 λ©”μ„œλ“œλŠ” ν—ˆλΈŒ μ„œλ²„λ‘œμ˜ ν•˜νŠΈλΉ„νŠΈ μ‹ ν˜Έ 전솑을 μ’…λ£Œν•©λ‹ˆλ‹€, ν΄λΌμ΄μ–ΈνŠΈκ°€ 더 이상 μ‚¬μš©ν•  수 μ—†κ±°λ‚˜ ν™œμ„±ν™”λ˜μ§€ μ•Šμ•˜μŒμ„ 효과적으둜 μ•Œλ¦½λ‹ˆλ‹€.

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
None

이 λ©”μ„œλ“œλŠ” 값을 λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

μ°Έκ³ 

ν•˜νŠΈλΉ„νŠΈ μ€‘μ§€λŠ” ν—ˆλΈŒ μ„œλ²„κ°€ ν΄λΌμ΄μ–ΈνŠΈκ°€ μ—°κ²°λ˜μ§€ μ•Šμ•˜κ±°λ‚˜ μ‚¬μš©ν•  수 μ—†λŠ” κ²ƒμœΌλ‘œ κ°„μ£Όν•  수 μžˆμœΌλ―€λ‘œ μ‹ μ€‘ν•˜κ²Œ μˆ˜ν–‰ν•΄μ•Ό ν•©λ‹ˆλ‹€. ν΄λΌμ΄μ–ΈνŠΈκ°€ 연결이 λŠμ–΄μ‘Œκ±°λ‚˜ μ‚¬μš©ν•  수 μ—†λŠ” κ²ƒμœΌλ‘œ κ°„μ£Όν•  수 μžˆμœΌλ―€λ‘œ μ‹ μ€‘ν•˜κ²Œ μˆ˜ν–‰ν•΄μ•Ό ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def stop_heartbeat(self) -> None:
    """
    Stops sending heartbeat signals to a remote hub server.

    This method terminates the sending of heartbeat signals to the hub server,
    effectively signaling that the client is no longer available or active.

    Returns:
        (None): The method does not return a value.

    Note:
        Stopping heartbeats should be done carefully, as it may result in the hub server
        considering the client as disconnected or unavailable.
    """
    self.hub_client._stop_heartbeats()

update(data)

이 μΈμŠ€ν„΄μŠ€κ°€ λ‚˜νƒ€λ‚΄λŠ” λͺ¨λΈ λ¦¬μ†ŒμŠ€λ₯Ό μ—…λ°μ΄νŠΈν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
data dict

λͺ¨λΈ λ¦¬μ†ŒμŠ€μ— λŒ€ν•œ μ—…λ°μ΄νŠΈλœ λ°μ΄ν„°μž…λ‹ˆλ‹€.

ν•„μˆ˜

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

μ—…λ°μ΄νŠΈ μš”μ²­μ˜ 응닡 객체, λ˜λŠ” μ—…λ°μ΄νŠΈμ— μ‹€νŒ¨ν•œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def update(self, data: dict) -> Optional[Response]:
    """
    Update the model resource represented by this instance.

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

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

upload_metrics(metrics)

λͺ¨λΈ λ©”νŠΈλ¦­μ„ Ultralytics HUB에 μ—…λ‘œλ“œν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
metrics dict
ν•„μˆ˜

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

μ—…λ‘œλ“œ λ©”νŠΈλ¦­ μš”μ²­μ˜ 응닡 개체, μ‹€νŒ¨ν•˜λ©΄ μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def upload_metrics(self, metrics: dict) -> Optional[Response]:
    """
    Upload model metrics to Ultralytics HUB.

    Args:
        metrics (dict):

    Returns:
        (Optional[Response]): Response object from the upload metrics request, or None if it fails.
    """
    return self.hub_client.upload_metrics(self.id, metrics)  # response

upload_model(epoch, weights, is_best=False, map=0.0, final=False)

λͺ¨λΈ 체크포인트λ₯Ό Ultralytics ν—ˆλΈŒμ— μ—…λ‘œλ“œν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
epoch int

ν˜„μž¬ ꡐ윑 μ‹œλŒ€μž…λ‹ˆλ‹€.

ν•„μˆ˜
weights str

λͺ¨λΈ κ°€μ€‘μΉ˜ 파일의 κ²½λ‘œμž…λ‹ˆλ‹€.

ν•„μˆ˜
is_best bool

ν˜„μž¬ λͺ¨λΈμ΄ μ§€κΈˆκΉŒμ§€ κ°€μž₯ 쒋은 λͺ¨λΈμΈμ§€ ν‘œμ‹œν•©λ‹ˆλ‹€.

False
map float

λͺ¨λΈμ˜ 평균 평균 μ •λ°€λ„μž…λ‹ˆλ‹€.

0.0
final bool

λͺ¨λΈμ΄ ν•™μŠ΅ ν›„ μ΅œμ’… λͺ¨λΈμΈμ§€ μ—¬λΆ€λ₯Ό λ‚˜νƒ€λƒ…λ‹ˆλ‹€.

False

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
Optional[Response]

μ—…λ‘œλ“œ μš”μ²­μ˜ 응닡 객체, μ—…λ‘œλ“œμ— μ‹€νŒ¨ν•œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def upload_model(
    self,
    epoch: int,
    weights: str,
    is_best: bool = False,
    map: float = 0.0,
    final: bool = False,
) -> Optional[Response]:
    """
    Upload a model checkpoint to Ultralytics HUB.

    Args:
        epoch (int): The current training epoch.
        weights (str): Path to the model weights file.
        is_best (bool): Indicates if the current model is the best one so far.
        map (float): Mean average precision of the model.
        final (bool): Indicates if the model is the final model after training.

    Returns:
        (Optional[Response]): Response object from the upload request, or None if upload fails.
    """
    return self.hub_client.upload_model(self.id, epoch, weights, is_best=is_best, map=map, final=final)



hub_sdk.modules.models.ModelList

베이슀: PaginatedList

의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
class ModelList(PaginatedList):
    def __init__(self, page_size=None, public=None, headers=None):
        """
        Initialize a ModelList 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 = "models"
        super().__init__(base_endpoint, "model", page_size, public, headers)

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

ModelList μΈμŠ€ν„΄μŠ€λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
page_size int

νŽ˜μ΄μ§€λ‹Ή μš”μ²­ν•  ν•­λͺ© μˆ˜μž…λ‹ˆλ‹€.

None
public bool

ν•­λͺ©μ΄ 곡개적으둜 μ•‘μ„ΈμŠ€ν•  수 μžˆλŠ”μ§€ μ—¬λΆ€μž…λ‹ˆλ‹€.

None
headers dict

API μš”μ²­μ— 포함할 ν—€λ”μž…λ‹ˆλ‹€.

None
의 μ†ŒμŠ€ μ½”λ“œ hub_sdk/modules/models.py
def __init__(self, page_size=None, public=None, headers=None):
    """
    Initialize a ModelList 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 = "models"
    super().__init__(base_endpoint, "model", page_size, public, headers)