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

μ°Έμ‘° ultralytics/utils/__init__.py

μ°Έκ³ 

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



ultralytics.utils.TQDM

기지: tqdm

κΈ°λ³Έ μΈμˆ˜κ°€ λ‹€λ₯Έ μ‚¬μš©μž 지정 Ultralytics tqdm 클래슀.

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

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
*args list

μœ„μΉ˜ μΈμˆ˜κ°€ 원본 tqdm으둜 μ „λ‹¬λ©λ‹ˆλ‹€.

()
**kwargs dict

μ‚¬μš©μž 지정 기본값이 적용된 ν‚€μ›Œλ“œ μΈμˆ˜μž…λ‹ˆλ‹€.

{}
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class TQDM(tqdm_original):
    """
    Custom Ultralytics tqdm class with different default arguments.

    Args:
        *args (list): Positional arguments passed to original tqdm.
        **kwargs (dict): Keyword arguments, with custom defaults applied.
    """

    def __init__(self, *args, **kwargs):
        """
        Initialize custom Ultralytics tqdm class with different default arguments.

        Note these can still be overridden when calling TQDM.
        """
        kwargs["disable"] = not VERBOSE or kwargs.get("disable", False)  # logical 'and' with default value if passed
        kwargs.setdefault("bar_format", TQDM_BAR_FORMAT)  # override default value if passed
        super().__init__(*args, **kwargs)

__init__(*args, **kwargs)

λ‹€λ₯Έ κΈ°λ³Έ 인수λ₯Ό μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž 지정 Ultralytics tqdm 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

TQDM을 ν˜ΈμΆœν•  λ•Œ 이 섀정을 μž¬μ •μ˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __init__(self, *args, **kwargs):
    """
    Initialize custom Ultralytics tqdm class with different default arguments.

    Note these can still be overridden when calling TQDM.
    """
    kwargs["disable"] = not VERBOSE or kwargs.get("disable", False)  # logical 'and' with default value if passed
    kwargs.setdefault("bar_format", TQDM_BAR_FORMAT)  # override default value if passed
    super().__init__(*args, **kwargs)



ultralytics.utils.SimpleClass

Ultralytics SimpleClassλŠ” μœ μš©ν•œ λ¬Έμžμ—΄ ν‘œν˜„, 였λ₯˜ 보고 및 속성 μ•‘μ„ΈμŠ€ λ©”μ„œλ“œλ₯Ό μ œκ³΅ν•˜μ—¬ 디버깅과 μ‚¬μš©μ„ μš©μ΄ν•˜κ²Œ ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class SimpleClass:
    """Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute
    access methods for easier debugging and usage.
    """

    def __str__(self):
        """Return a human-readable string representation of the object."""
        attr = []
        for a in dir(self):
            v = getattr(self, a)
            if not callable(v) and not a.startswith("_"):
                if isinstance(v, SimpleClass):
                    # Display only the module and class name for subclasses
                    s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
                else:
                    s = f"{a}: {repr(v)}"
                attr.append(s)
        return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)

    def __repr__(self):
        """Return a machine-readable string representation of the object."""
        return self.__str__()

    def __getattr__(self, attr):
        """Custom attribute access error message with helpful information."""
        name = self.__class__.__name__
        raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")

__getattr__(attr)

μœ μš©ν•œ 정보가 ν¬ν•¨λœ μ‚¬μš©μž 지정 속성 μ•‘μ„ΈμŠ€ 였λ₯˜ λ©”μ‹œμ§€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __getattr__(self, attr):
    """Custom attribute access error message with helpful information."""
    name = self.__class__.__name__
    raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")

__repr__()

객체의 기계 νŒλ… κ°€λŠ₯ν•œ λ¬Έμžμ—΄ ν‘œν˜„μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __repr__(self):
    """Return a machine-readable string representation of the object."""
    return self.__str__()

__str__()

μ‚¬λžŒμ΄ 읽을 수 μžˆλŠ” 객체의 λ¬Έμžμ—΄ ν‘œν˜„μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __str__(self):
    """Return a human-readable string representation of the object."""
    attr = []
    for a in dir(self):
        v = getattr(self, a)
        if not callable(v) and not a.startswith("_"):
            if isinstance(v, SimpleClass):
                # Display only the module and class name for subclasses
                s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
            else:
                s = f"{a}: {repr(v)}"
            attr.append(s)
    return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)



ultralytics.utils.IterableSimpleNamespace

기지: SimpleNamespace

Ultralytics IterableSimpleNamespaceλŠ” λ‹¨μˆœ 이름 κ³΅κ°„μ˜ ν™•μž₯ 클래슀둜, μ΄ν„°λŸ¬λΈ” κΈ°λŠ₯을 μΆ”κ°€ν•˜κ³  λ”•μ…”λ„ˆλ¦¬() 및 루프에 μ‚¬μš©ν•  수 μžˆλ„λ‘ ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class IterableSimpleNamespace(SimpleNamespace):
    """Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and
    enables usage with dict() and for loops.
    """

    def __iter__(self):
        """Return an iterator of key-value pairs from the namespace's attributes."""
        return iter(vars(self).items())

    def __str__(self):
        """Return a human-readable string representation of the object."""
        return "\n".join(f"{k}={v}" for k, v in vars(self).items())

    def __getattr__(self, attr):
        """Custom attribute access error message with helpful information."""
        name = self.__class__.__name__
        raise AttributeError(
            f"""
            '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
            'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
            {DEFAULT_CFG_PATH} with the latest version from
            https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
            """
        )

    def get(self, key, default=None):
        """Return the value of the specified key if it exists; otherwise, return the default value."""
        return getattr(self, key, default)

__getattr__(attr)

μœ μš©ν•œ 정보가 ν¬ν•¨λœ μ‚¬μš©μž 지정 속성 μ•‘μ„ΈμŠ€ 였λ₯˜ λ©”μ‹œμ§€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __getattr__(self, attr):
    """Custom attribute access error message with helpful information."""
    name = self.__class__.__name__
    raise AttributeError(
        f"""
        '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
        'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
        {DEFAULT_CFG_PATH} with the latest version from
        https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
        """
    )

__iter__()

λ„€μž„μŠ€νŽ˜μ΄μŠ€μ˜ μ†μ„±μ—μ„œ ν‚€-κ°’ 쌍의 μ΄ν„°λ ˆμ΄ν„°λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __iter__(self):
    """Return an iterator of key-value pairs from the namespace's attributes."""
    return iter(vars(self).items())

__str__()

μ‚¬λžŒμ΄ 읽을 수 μžˆλŠ” 객체의 λ¬Έμžμ—΄ ν‘œν˜„μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __str__(self):
    """Return a human-readable string representation of the object."""
    return "\n".join(f"{k}={v}" for k, v in vars(self).items())

get(key, default=None)

μ§€μ •λœ ν‚€κ°€ 있으면 ν•΄λ‹Ή 값을 λ°˜ν™˜ν•˜κ³ , 그렇지 μ•ŠμœΌλ©΄ 기본값을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get(self, key, default=None):
    """Return the value of the specified key if it exists; otherwise, return the default value."""
    return getattr(self, key, default)



ultralytics.utils.ThreadingLocked

ν•¨μˆ˜λ‚˜ λ©”μ„œλ“œμ˜ μŠ€λ ˆλ“œ μ•ˆμ „ 싀행을 보μž₯ν•˜κΈ° μœ„ν•œ λ°μ½”λ ˆμ΄ν„° ν΄λž˜μŠ€μž…λ‹ˆλ‹€. 이 ν΄λž˜μŠ€λŠ” λ°μ½”λ ˆμ΄ν„°λ‘œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€. 와 ν•¨κ»˜ μ‚¬μš©ν•˜λ©΄ μ—¬λŸ¬ μŠ€λ ˆλ“œμ—μ„œ λ°μ½”λ ˆμ΄ν„° ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ ν•œ λ²ˆμ— ν•˜λ‚˜μ˜ μŠ€λ ˆλ“œλ§Œ ν•¨μˆ˜λ₯Ό μ‹€ν–‰ν•  수 μžˆλ„λ‘ ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
lock Lock

μž₯μ‹λœ ν•¨μˆ˜μ— λŒ€ν•œ μ•‘μ„ΈμŠ€λ₯Ό κ΄€λ¦¬ν•˜λŠ” 데 μ‚¬μš©λ˜λŠ” 잠금 κ°μ²΄μž…λ‹ˆλ‹€.

예제
from ultralytics.utils import ThreadingLocked

@ThreadingLocked()
def my_function():
    # Your code here
    pass
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class ThreadingLocked:
    """
    A decorator class for ensuring thread-safe execution of a function or method. This class can be used as a decorator
    to make sure that if the decorated function is called from multiple threads, only one thread at a time will be able
    to execute the function.

    Attributes:
        lock (threading.Lock): A lock object used to manage access to the decorated function.

    Example:
        ```python
        from ultralytics.utils import ThreadingLocked

        @ThreadingLocked()
        def my_function():
            # Your code here
            pass
        ```
    """

    def __init__(self):
        """Initializes the decorator class for thread-safe execution of a function or method."""
        self.lock = threading.Lock()

    def __call__(self, f):
        """Run thread-safe execution of function or method."""
        from functools import wraps

        @wraps(f)
        def decorated(*args, **kwargs):
            """Applies thread-safety to the decorated function or method."""
            with self.lock:
                return f(*args, **kwargs)

        return decorated

__call__(f)

ν•¨μˆ˜ λ˜λŠ” λ©”μ„œλ“œμ˜ μŠ€λ ˆλ“œ μ•ˆμ „ 싀행을 μ‹€ν–‰ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __call__(self, f):
    """Run thread-safe execution of function or method."""
    from functools import wraps

    @wraps(f)
    def decorated(*args, **kwargs):
        """Applies thread-safety to the decorated function or method."""
        with self.lock:
            return f(*args, **kwargs)

    return decorated

__init__()

ν•¨μˆ˜λ‚˜ λ©”μ„œλ“œμ˜ μŠ€λ ˆλ“œ μ•ˆμ „ 싀행을 μœ„ν•΄ λ°μ½”λ ˆμ΄ν„° 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __init__(self):
    """Initializes the decorator class for thread-safe execution of a function or method."""
    self.lock = threading.Lock()



ultralytics.utils.TryExcept

기지: ContextDecorator

Ultralytics TryExcept 클래슀. TryExcept() λ°μ½”λ ˆμ΄ν„° λ˜λŠ” 'with TryExcept():' μ»¨ν…μŠ€νŠΈ κ΄€λ¦¬μžλ‘œ μ‚¬μš©ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ:

λ°μ½”λ ˆμ΄ν„°λ‘œμ„œ:

>>> @TryExcept(msg="Error occurred in func", verbose=True)
>>> def func():
>>>    # Function logic here
>>>     pass

μ»¨ν…μŠ€νŠΈ κ΄€λ¦¬μžλ‘œμ„œ:

>>> with TryExcept(msg="Error occurred in block", verbose=True):
>>>     # Code block here
>>>     pass
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class TryExcept(contextlib.ContextDecorator):
    """
    Ultralytics TryExcept class. Use as @TryExcept() decorator or 'with TryExcept():' context manager.

    Examples:
        As a decorator:
        >>> @TryExcept(msg="Error occurred in func", verbose=True)
        >>> def func():
        >>>    # Function logic here
        >>>     pass

        As a context manager:
        >>> with TryExcept(msg="Error occurred in block", verbose=True):
        >>>     # Code block here
        >>>     pass
    """

    def __init__(self, msg="", verbose=True):
        """Initialize TryExcept class with optional message and verbosity settings."""
        self.msg = msg
        self.verbose = verbose

    def __enter__(self):
        """Executes when entering TryExcept context, initializes instance."""
        pass

    def __exit__(self, exc_type, value, traceback):
        """Defines behavior when exiting a 'with' block, prints error message if necessary."""
        if self.verbose and value:
            print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
        return True

__enter__()

TryExcept μ»¨ν…μŠ€νŠΈμ— λ“€μ–΄κ°ˆ λ•Œ μ‹€ν–‰λ˜λ©° μΈμŠ€ν„΄μŠ€λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __enter__(self):
    """Executes when entering TryExcept context, initializes instance."""
    pass

__exit__(exc_type, value, traceback)

'with' 블둝을 μ’…λ£Œν•  λ•Œ λ™μž‘μ„ μ •μ˜ν•˜κ³  ν•„μš”ν•œ 경우 였λ₯˜ λ©”μ‹œμ§€λ₯Ό μΈμ‡„ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __exit__(self, exc_type, value, traceback):
    """Defines behavior when exiting a 'with' block, prints error message if necessary."""
    if self.verbose and value:
        print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
    return True

__init__(msg='', verbose=True)

선택적 λ©”μ‹œμ§€ 및 상세도 μ„€μ •μœΌλ‘œ TryExcept 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __init__(self, msg="", verbose=True):
    """Initialize TryExcept class with optional message and verbosity settings."""
    self.msg = msg
    self.verbose = verbose



ultralytics.utils.Retry

기지: ContextDecorator

μ§€μˆ˜ λ°±μ˜€ν”„κ°€ μžˆλŠ” ν•¨μˆ˜ 싀행을 μœ„ν•œ μž¬μ‹œλ„ ν΄λž˜μŠ€μž…λ‹ˆλ‹€.

λ°μ½”λ ˆμ΄ν„° λ˜λŠ” μ»¨ν…μŠ€νŠΈ κ΄€λ¦¬μžλ‘œ μ‚¬μš©ν•˜μ—¬ μ˜ˆμ™Έμ— λŒ€ν•΄ ν•¨μˆ˜ λ˜λŠ” μ½”λ“œ 블둝을 μž¬μ‹œλ„ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ§€μ •λœ νšŸμˆ˜κΉŒμ§€ μž¬μ‹œλ„ν•  수 있으며 μž¬μ‹œλ„ κ°„ 지연 μ‹œκ°„μ΄ κΈ°ν•˜κΈ‰μˆ˜μ μœΌλ‘œ μ¦κ°€ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ:

λ°μ½”λ ˆμ΄ν„°λ‘œ μ‚¬μš©ν•˜λŠ” μ˜ˆμ‹œμž…λ‹ˆλ‹€:

>>> @Retry(times=3, delay=2)
>>> def test_func():
>>>     # Replace with function logic that may raise exceptions
>>>     return True

μ»¨ν…μŠ€νŠΈ κ΄€λ¦¬μžλ‘œμ„œμ˜ μ‚¬μš© μ˜ˆμ‹œ:

>>> with Retry(times=3, delay=2):
>>>     # Replace with code block that may raise exceptions
>>>     pass
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class Retry(contextlib.ContextDecorator):
    """
    Retry class for function execution with exponential backoff.

    Can be used as a decorator or a context manager to retry a function or block of code on exceptions, up to a
    specified number of times with an exponentially increasing delay between retries.

    Examples:
        Example usage as a decorator:
        >>> @Retry(times=3, delay=2)
        >>> def test_func():
        >>>     # Replace with function logic that may raise exceptions
        >>>     return True

        Example usage as a context manager:
        >>> with Retry(times=3, delay=2):
        >>>     # Replace with code block that may raise exceptions
        >>>     pass
    """

    def __init__(self, times=3, delay=2):
        """Initialize Retry class with specified number of retries and delay."""
        self.times = times
        self.delay = delay
        self._attempts = 0

    def __call__(self, func):
        """Decorator implementation for Retry with exponential backoff."""

        def wrapped_func(*args, **kwargs):
            """Applies retries to the decorated function or method."""
            self._attempts = 0
            while self._attempts < self.times:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    self._attempts += 1
                    print(f"Retry {self._attempts}/{self.times} failed: {e}")
                    if self._attempts >= self.times:
                        raise e
                    time.sleep(self.delay * (2**self._attempts))  # exponential backoff delay

        return wrapped_func

    def __enter__(self):
        """Enter the runtime context related to this object."""
        self._attempts = 0

    def __exit__(self, exc_type, exc_value, traceback):
        """Exit the runtime context related to this object with exponential backoff."""
        if exc_type is not None:
            self._attempts += 1
            if self._attempts < self.times:
                print(f"Retry {self._attempts}/{self.times} failed: {exc_value}")
                time.sleep(self.delay * (2**self._attempts))  # exponential backoff delay
                return True  # Suppresses the exception and retries
        return False  # Re-raises the exception if retries are exhausted

__call__(func)

μ§€μˆ˜ λ°±μ˜€ν”„λ₯Ό μ‚¬μš©ν•œ μž¬μ‹œλ„λ₯Ό μœ„ν•œ λ°μ½”λ ˆμ΄ν„° κ΅¬ν˜„.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __call__(self, func):
    """Decorator implementation for Retry with exponential backoff."""

    def wrapped_func(*args, **kwargs):
        """Applies retries to the decorated function or method."""
        self._attempts = 0
        while self._attempts < self.times:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                self._attempts += 1
                print(f"Retry {self._attempts}/{self.times} failed: {e}")
                if self._attempts >= self.times:
                    raise e
                time.sleep(self.delay * (2**self._attempts))  # exponential backoff delay

    return wrapped_func

__enter__()

이 객체와 κ΄€λ ¨λœ λŸ°νƒ€μž„ μ»¨ν…μŠ€νŠΈλ₯Ό μž…λ ₯ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __enter__(self):
    """Enter the runtime context related to this object."""
    self._attempts = 0

__exit__(exc_type, exc_value, traceback)

μ§€μˆ˜ λ°±μ˜€ν”„λ₯Ό μ‚¬μš©ν•˜μ—¬ 이 객체와 κ΄€λ ¨λœ λŸ°νƒ€μž„ μ»¨ν…μŠ€νŠΈλ₯Ό μ’…λ£Œν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __exit__(self, exc_type, exc_value, traceback):
    """Exit the runtime context related to this object with exponential backoff."""
    if exc_type is not None:
        self._attempts += 1
        if self._attempts < self.times:
            print(f"Retry {self._attempts}/{self.times} failed: {exc_value}")
            time.sleep(self.delay * (2**self._attempts))  # exponential backoff delay
            return True  # Suppresses the exception and retries
    return False  # Re-raises the exception if retries are exhausted

__init__(times=3, delay=2)

μ§€μ •λœ μž¬μ‹œλ„ 횟수 및 μ§€μ—°μœΌλ‘œ μž¬μ‹œλ„ 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __init__(self, times=3, delay=2):
    """Initialize Retry class with specified number of retries and delay."""
    self.times = times
    self.delay = delay
    self._attempts = 0



ultralytics.utils.SettingsManager

기지: dict

YAML νŒŒμΌμ— μ €μž₯된 Ultralytics 섀정을 κ΄€λ¦¬ν•©λ‹ˆλ‹€.

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

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

Ultralytics settings YAML 파일의 κ²½λ‘œμž…λ‹ˆλ‹€. 기본값은 USER_CONFIG_DIR / 'settings.yaml'μž…λ‹ˆλ‹€.

SETTINGS_YAML
version str

μ„€μ • 버전. 둜컬 버전이 μΌμΉ˜ν•˜μ§€ μ•ŠλŠ” 경우 μƒˆ κΈ°λ³Έ 섀정이 μ €μž₯λ©λ‹ˆλ‹€.

'0.0.4'
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
class SettingsManager(dict):
    """
    Manages Ultralytics settings stored in a YAML file.

    Args:
        file (str | Path): Path to the Ultralytics settings YAML file. Default is USER_CONFIG_DIR / 'settings.yaml'.
        version (str): Settings version. In case of local version mismatch, new default settings will be saved.
    """

    def __init__(self, file=SETTINGS_YAML, version="0.0.4"):
        """Initialize the SettingsManager with default settings, load and validate current settings from the YAML
        file.
        """
        import copy
        import hashlib

        from ultralytics.utils.checks import check_version
        from ultralytics.utils.torch_utils import torch_distributed_zero_first

        git_dir = get_git_dir()
        root = git_dir or Path()
        datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()

        self.file = Path(file)
        self.version = version
        self.defaults = {
            "settings_version": version,
            "datasets_dir": str(datasets_root / "datasets"),
            "weights_dir": str(root / "weights"),
            "runs_dir": str(root / "runs"),
            "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),
            "sync": True,
            "api_key": "",
            "openai_api_key": "",
            "clearml": True,  # integrations
            "comet": True,
            "dvc": True,
            "hub": True,
            "mlflow": True,
            "neptune": True,
            "raytune": True,
            "tensorboard": True,
            "wandb": True,
        }

        super().__init__(copy.deepcopy(self.defaults))

        with torch_distributed_zero_first(RANK):
            if not self.file.exists():
                self.save()

            self.load()
            correct_keys = self.keys() == self.defaults.keys()
            correct_types = all(type(a) is type(b) for a, b in zip(self.values(), self.defaults.values()))
            correct_version = check_version(self["settings_version"], self.version)
            if not (correct_keys and correct_types and correct_version):
                LOGGER.warning(
                    "WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem "
                    "with your settings or a recent ultralytics package update. "
                    f"\nView settings with 'yolo settings' or at '{self.file}'"
                    "\nUpdate settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'."
                )
                self.reset()

    def load(self):
        """Loads settings from the YAML file."""
        super().update(yaml_load(self.file))

    def save(self):
        """Saves the current settings to the YAML file."""
        yaml_save(self.file, dict(self))

    def update(self, *args, **kwargs):
        """Updates a setting value in the current settings."""
        super().update(*args, **kwargs)
        self.save()

    def reset(self):
        """Resets the settings to default and saves them."""
        self.clear()
        self.update(self.defaults)
        self.save()

__init__(file=SETTINGS_YAML, version='0.0.4')

κΈ°λ³Έ μ„€μ •μœΌλ‘œ μ„€μ • κ΄€λ¦¬μžλ₯Ό μ΄ˆκΈ°ν™”ν•˜κ³ , YAML νŒŒμΌμ—μ„œ ν˜„μž¬ 섀정을 λ‘œλ“œν•˜κ³  μœ νš¨μ„±μ„ κ²€μ‚¬ν•©λ‹ˆλ‹€. νŒŒμΌμ—μ„œ ν˜„μž¬ μ„ΈνŒ…μ„ λ‘œλ“œν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def __init__(self, file=SETTINGS_YAML, version="0.0.4"):
    """Initialize the SettingsManager with default settings, load and validate current settings from the YAML
    file.
    """
    import copy
    import hashlib

    from ultralytics.utils.checks import check_version
    from ultralytics.utils.torch_utils import torch_distributed_zero_first

    git_dir = get_git_dir()
    root = git_dir or Path()
    datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()

    self.file = Path(file)
    self.version = version
    self.defaults = {
        "settings_version": version,
        "datasets_dir": str(datasets_root / "datasets"),
        "weights_dir": str(root / "weights"),
        "runs_dir": str(root / "runs"),
        "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),
        "sync": True,
        "api_key": "",
        "openai_api_key": "",
        "clearml": True,  # integrations
        "comet": True,
        "dvc": True,
        "hub": True,
        "mlflow": True,
        "neptune": True,
        "raytune": True,
        "tensorboard": True,
        "wandb": True,
    }

    super().__init__(copy.deepcopy(self.defaults))

    with torch_distributed_zero_first(RANK):
        if not self.file.exists():
            self.save()

        self.load()
        correct_keys = self.keys() == self.defaults.keys()
        correct_types = all(type(a) is type(b) for a, b in zip(self.values(), self.defaults.values()))
        correct_version = check_version(self["settings_version"], self.version)
        if not (correct_keys and correct_types and correct_version):
            LOGGER.warning(
                "WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem "
                "with your settings or a recent ultralytics package update. "
                f"\nView settings with 'yolo settings' or at '{self.file}'"
                "\nUpdate settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'."
            )
            self.reset()

load()

YAML νŒŒμΌμ—μ„œ 섀정을 λ‘œλ“œν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def load(self):
    """Loads settings from the YAML file."""
    super().update(yaml_load(self.file))

reset()

섀정을 κΈ°λ³Έκ°’μœΌλ‘œ μž¬μ„€μ •ν•˜κ³  μ €μž₯ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def reset(self):
    """Resets the settings to default and saves them."""
    self.clear()
    self.update(self.defaults)
    self.save()

save()

ν˜„μž¬ 섀정을 YAML νŒŒμΌμ— μ €μž₯ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def save(self):
    """Saves the current settings to the YAML file."""
    yaml_save(self.file, dict(self))

update(*args, **kwargs)

ν˜„μž¬ μ„€μ •μ˜ μ„€μ • 값을 μ—…λ°μ΄νŠΈν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def update(self, *args, **kwargs):
    """Updates a setting value in the current settings."""
    super().update(*args, **kwargs)
    self.save()



ultralytics.utils.plt_settings(rcparams=None, backend='Agg')

λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ μž„μ‹œλ‘œ rc λ§€κ°œλ³€μˆ˜μ™€ ν”Œλ‘œνŒ… ν•¨μˆ˜λ₯Ό μœ„ν•œ λ°±μ—”λ“œλ₯Ό μ„€μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

예제

decorator: @plt_settings({"font.size": 12}) context manager: with plt_settings({"font.size": 12}):

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

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

μ„€μ •ν•  rc λ§€κ°œλ³€μˆ˜ 사전.

None
backend str

μ‚¬μš©ν•  λ°±μ—”λ“œμ˜ μ΄λ¦„μž…λ‹ˆλ‹€. 기본값은 'Agg'μž…λ‹ˆλ‹€.

'Agg'

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

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

μž„μ‹œλ‘œ μ„€μ •λœ rc λ§€κ°œλ³€μˆ˜μ™€ λ°±μ—”λ“œκ°€ μžˆλŠ” λ°μ½”λ ˆμ΄μ…˜ ν•¨μˆ˜μž…λ‹ˆλ‹€. 이 λ°μ½”λ ˆμ΄ν„°λŠ” λŠ” 싀행을 μœ„ν•΄ νŠΉμ • matplotlib rc λ§€κ°œλ³€μˆ˜μ™€ λ°±μ—”λ“œκ°€ ν•„μš”ν•œ λͺ¨λ“  ν•¨μˆ˜μ— μ μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def plt_settings(rcparams=None, backend="Agg"):
    """
    Decorator to temporarily set rc parameters and the backend for a plotting function.

    Example:
        decorator: @plt_settings({"font.size": 12})
        context manager: with plt_settings({"font.size": 12}):

    Args:
        rcparams (dict): Dictionary of rc parameters to set.
        backend (str, optional): Name of the backend to use. Defaults to 'Agg'.

    Returns:
        (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be
            applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.
    """

    if rcparams is None:
        rcparams = {"font.size": 11}

    def decorator(func):
        """Decorator to apply temporary rc parameters and backend to a function."""

        def wrapper(*args, **kwargs):
            """Sets rc parameters and backend, calls the original function, and restores the settings."""
            original_backend = plt.get_backend()
            if backend.lower() != original_backend.lower():
                plt.close("all")  # auto-close()ing of figures upon backend switching is deprecated since 3.8
                plt.switch_backend(backend)

            with plt.rc_context(rcparams):
                result = func(*args, **kwargs)

            if backend != original_backend:
                plt.close("all")
                plt.switch_backend(original_backend)
            return result

        return wrapper

    return decorator



ultralytics.utils.set_logging(name=LOGGING_NAME, verbose=True)

UTF-8 인코딩을 μ§€μ›ν•˜μ—¬ μ§€μ •λœ 이름에 λŒ€ν•œ λ‘œκΉ…μ„ μ„€μ •ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def set_logging(name=LOGGING_NAME, verbose=True):
    """Sets up logging for the given name with UTF-8 encoding support."""
    level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR  # rank in world for Multi-GPU trainings

    # Configure the console (stdout) encoding to UTF-8
    formatter = logging.Formatter("%(message)s")  # Default formatter
    if WINDOWS and sys.stdout.encoding != "utf-8":
        try:
            if hasattr(sys.stdout, "reconfigure"):
                sys.stdout.reconfigure(encoding="utf-8")
            elif hasattr(sys.stdout, "buffer"):
                import io

                sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
            else:
                sys.stdout.encoding = "utf-8"
        except Exception as e:
            print(f"Creating custom formatter for non UTF-8 environments due to {e}")

            class CustomFormatter(logging.Formatter):
                def format(self, record):
                    """Sets up logging with UTF-8 encoding and configurable verbosity."""
                    return emojis(super().format(record))

            formatter = CustomFormatter("%(message)s")  # Use CustomFormatter to eliminate UTF-8 output as last recourse

    # Create and configure the StreamHandler
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(level)

    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(stream_handler)
    logger.propagate = False
    return logger



ultralytics.utils.emojis(string='')

ν”Œλž«νΌμ— 따라 이λͺ¨ν‹°μ½˜μ— μ•ˆμ „ν•œ λ²„μ „μ˜ λ¬Έμžμ—΄μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def emojis(string=""):
    """Return platform-dependent emoji-safe version of string."""
    return string.encode().decode("ascii", "ignore") if WINDOWS else string



ultralytics.utils.yaml_save(file='data.yaml', data=None, header='')

YAML 데이터λ₯Ό νŒŒμΌμ— μ €μž₯ν•©λ‹ˆλ‹€.

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

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

파일 이름. 기본값은 'data.yaml'μž…λ‹ˆλ‹€.

'data.yaml'
data dict

YAML ν˜•μ‹μœΌλ‘œ μ €μž₯ν•  데이터.

None
header str

YAML 헀더λ₯Ό μΆ”κ°€ν•©λ‹ˆλ‹€.

''

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

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

데이터가 μ§€μ •λœ νŒŒμΌμ— μ €μž₯λ©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def yaml_save(file="data.yaml", data=None, header=""):
    """
    Save YAML data to a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        data (dict): Data to save in YAML format.
        header (str, optional): YAML header to add.

    Returns:
        (None): Data is saved to the specified file.
    """
    if data is None:
        data = {}
    file = Path(file)
    if not file.parent.exists():
        # Create parent directories if they don't exist
        file.parent.mkdir(parents=True, exist_ok=True)

    # Convert Path objects to strings
    valid_types = int, float, str, bool, list, tuple, dict, type(None)
    for k, v in data.items():
        if not isinstance(v, valid_types):
            data[k] = str(v)

    # Dump data to file in YAML format
    with open(file, "w", errors="ignore", encoding="utf-8") as f:
        if header:
            f.write(header)
        yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)



ultralytics.utils.yaml_load(file='data.yaml', append_filename=False)

νŒŒμΌμ—μ„œ YAML 데이터λ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.

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

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

파일 이름. 기본값은 'data.yaml'μž…λ‹ˆλ‹€.

'data.yaml'
append_filename bool

YAML 파일λͺ…을 YAML 사전에 μΆ”κ°€ν•©λ‹ˆλ‹€. 기본값은 Falseμž…λ‹ˆλ‹€.

False

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

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

YAML 데이터 및 파일 이름.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def yaml_load(file="data.yaml", append_filename=False):
    """
    Load YAML data from a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.

    Returns:
        (dict): YAML data and file name.
    """
    assert Path(file).suffix in (".yaml", ".yml"), f"Attempting to load non-YAML file {file} with yaml_load()"
    with open(file, errors="ignore", encoding="utf-8") as f:
        s = f.read()  # string

        # Remove special characters
        if not s.isprintable():
            s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)

        # Add YAML filename to dict and return
        data = yaml.safe_load(s) or {}  # always return a dict (yaml.safe_load() may return None for empty files)
        if append_filename:
            data["yaml_file"] = str(file)
        return data



ultralytics.utils.yaml_print(yaml_file)

YAML 파일 λ˜λŠ” YAML ν˜•μ‹μ˜ 사전을 예쁘게 μΈμ‡„ν•©λ‹ˆλ‹€.

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

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
yaml_file Union[str, Path, dict]

YAML 파일의 파일 경둜 λ˜λŠ” YAML ν˜•μ‹μ˜ μ‚¬μ „μž…λ‹ˆλ‹€.

ν•„μˆ˜

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

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

(μ—†μŒ)

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def yaml_print(yaml_file: Union[str, Path, dict]) -> None:
    """
    Pretty prints a YAML file or a YAML-formatted dictionary.

    Args:
        yaml_file: The file path of the YAML file or a YAML-formatted dictionary.

    Returns:
        (None)
    """
    yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
    dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True)
    LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")



ultralytics.utils.is_ubuntu()

OSκ°€ μš°λΆ„νˆ¬μΈμ§€ ν™•μΈν•©λ‹ˆλ‹€.

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

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

OSκ°€ μš°λΆ„νˆ¬μΈ 경우 참이고, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_ubuntu() -> bool:
    """
    Check if the OS is Ubuntu.

    Returns:
        (bool): True if OS is Ubuntu, False otherwise.
    """
    with contextlib.suppress(FileNotFoundError):
        with open("/etc/os-release") as f:
            return "ID=ubuntu" in f.read()
    return False



ultralytics.utils.is_colab()

ν˜„μž¬ μŠ€ν¬λ¦½νŠΈκ°€ Google Colab λ…ΈνŠΈλΆ λ‚΄μ—μ„œ μ‹€ν–‰ 쀑인지 ν™•μΈν•©λ‹ˆλ‹€.

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

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

Colab λ…ΈνŠΈλΆ λ‚΄μ—μ„œ μ‹€ν–‰ 쀑이면 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_colab():
    """
    Check if the current script is running inside a Google Colab notebook.

    Returns:
        (bool): True if running inside a Colab notebook, False otherwise.
    """
    return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ



ultralytics.utils.is_kaggle()

ν˜„μž¬ μŠ€ν¬λ¦½νŠΈκ°€ Kaggle 컀널 λ‚΄μ—μ„œ μ‹€ν–‰λ˜κ³  μžˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

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

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

Kaggle 컀널 λ‚΄λΆ€μ—μ„œ μ‹€ν–‰λ˜λŠ” 경우 True, 그렇지 μ•ŠμœΌλ©΄ Falseμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_kaggle():
    """
    Check if the current script is running inside a Kaggle kernel.

    Returns:
        (bool): True if running inside a Kaggle kernel, False otherwise.
    """
    return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"



ultralytics.utils.is_jupyter()

ν˜„μž¬ μŠ€ν¬λ¦½νŠΈκ°€ μ£Όν”Όν„° λ…ΈνŠΈλΆ λ‚΄μ—μ„œ μ‹€ν–‰λ˜κ³  μžˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€. Colab, Jupyterlab, Kaggle, Paperspace μ—μ„œ ν™•μΈλ˜μ—ˆμŠ΅λ‹ˆλ‹€.

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

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

μ£Όν”Όν„° λ…ΈνŠΈλΆ λ‚΄λΆ€μ—μ„œ μ‹€ν–‰ 쀑이면 μ°Έ, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_jupyter():
    """
    Check if the current script is running inside a Jupyter Notebook. Verified on Colab, Jupyterlab, Kaggle, Paperspace.

    Returns:
        (bool): True if running inside a Jupyter Notebook, False otherwise.
    """
    with contextlib.suppress(Exception):
        from IPython import get_ipython

        return get_ipython() is not None
    return False



ultralytics.utils.is_docker()

μŠ€ν¬λ¦½νŠΈκ°€ Docker μ»¨ν…Œμ΄λ„ˆ λ‚΄μ—μ„œ μ‹€ν–‰λ˜κ³  μžˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€.

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

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

μŠ€ν¬λ¦½νŠΈκ°€ Docker μ»¨ν…Œμ΄λ„ˆ λ‚΄μ—μ„œ μ‹€ν–‰ 쀑이면 True, 그렇지 μ•ŠμœΌλ©΄ Falseμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_docker() -> bool:
    """
    Determine if the script is running inside a Docker container.

    Returns:
        (bool): True if the script is running inside a Docker container, False otherwise.
    """
    file = Path("/proc/self/cgroup")
    if file.exists():
        with open(file) as f:
            return "docker" in f.read()
    else:
        return False



ultralytics.utils.is_online()

μ•Œλ €μ§„ 온라인 ν˜ΈμŠ€νŠΈμ— 연결을 μ‹œλ„ν•˜μ—¬ 인터넷 연결을 ν™•μΈν•©λ‹ˆλ‹€.

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

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

연결에 μ„±κ³΅ν•˜λ©΄ 참이고, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_online() -> bool:
    """
    Check internet connectivity by attempting to connect to a known online host.

    Returns:
        (bool): True if connection is successful, False otherwise.
    """
    import socket

    for host in "1.1.1.1", "8.8.8.8", "223.5.5.5":  # Cloudflare, Google, AliDNS:
        try:
            test_connection = socket.create_connection(address=(host, 53), timeout=2)
        except (socket.timeout, socket.gaierror, OSError):
            continue
        else:
            # If the connection was successful, close it to avoid a ResourceWarning
            test_connection.close()
            return True
    return False



ultralytics.utils.is_pip_package(filepath=__name__)

μ§€μ •λœ 파일 κ²½λ‘œμ— μžˆλŠ” 파일이 pip νŒ¨ν‚€μ§€μ˜ 일뢀인지 ν™•μΈν•©λ‹ˆλ‹€.

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

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

확인할 파일 κ²½λ‘œμž…λ‹ˆλ‹€.

__name__

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

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

파일이 pip νŒ¨ν‚€μ§€μ˜ 일뢀인 경우 참이고, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_pip_package(filepath: str = __name__) -> bool:
    """
    Determines if the file at the given filepath is part of a pip package.

    Args:
        filepath (str): The filepath to check.

    Returns:
        (bool): True if the file is part of a pip package, False otherwise.
    """
    import importlib.util

    # Get the spec for the module
    spec = importlib.util.find_spec(filepath)

    # Return whether the spec is not None and the origin is not None (indicating it is a package)
    return spec is not None and spec.origin is not None



ultralytics.utils.is_dir_writeable(dir_path)

디렉터리에 μ“°κΈ° κ°€λŠ₯ν•œμ§€ ν™•μΈν•©λ‹ˆλ‹€.

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

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

디렉터리 κ²½λ‘œμž…λ‹ˆλ‹€.

ν•„μˆ˜

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

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

디렉터리에 μ“°κΈ° κ°€λŠ₯ν•˜λ©΄ True, 그렇지 μ•ŠμœΌλ©΄ Falseμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
    """
    Check if a directory is writeable.

    Args:
        dir_path (str | Path): The path to the directory.

    Returns:
        (bool): True if the directory is writeable, False otherwise.
    """
    return os.access(str(dir_path), os.W_OK)



ultralytics.utils.is_pytest_running()

pytestκ°€ ν˜„μž¬ μ‹€ν–‰ 쀑인지 μ—¬λΆ€λ₯Ό κ²°μ •ν•©λ‹ˆλ‹€.

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

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

pytestκ°€ μ‹€ν–‰ 쀑이면 참이고, 그렇지 μ•ŠμœΌλ©΄ κ±°μ§“μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_pytest_running():
    """
    Determines whether pytest is currently running or not.

    Returns:
        (bool): True if pytest is running, False otherwise.
    """
    return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(sys.argv[0]).stem)



ultralytics.utils.is_github_action_running()

ν˜„μž¬ ν™˜κ²½μ΄ GitHub μž‘μ—… 싀행기인지 ν™•μΈν•©λ‹ˆλ‹€.

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

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

ν˜„μž¬ ν™˜κ²½μ΄ GitHub μž‘μ—… 싀행기인 경우 True, 그렇지 μ•ŠμœΌλ©΄ Falseμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_github_action_running() -> bool:
    """
    Determine if the current environment is a GitHub Actions runner.

    Returns:
        (bool): True if the current environment is a GitHub Actions runner, False otherwise.
    """
    return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ



ultralytics.utils.is_git_dir()

ν˜„μž¬ 파일이 git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 일뢀인지 μ—¬λΆ€λ₯Ό κ²°μ •ν•©λ‹ˆλ‹€. ν˜„μž¬ 파일이 git μ €μž₯μ†Œμ˜ 일뢀가 μ•„λ‹Œ 경우 리포지토리에 μ†ν•˜μ§€ μ•ŠμœΌλ©΄ None을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

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

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

ν˜„μž¬ 파일이 git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 일뢀인 경우 trueμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def is_git_dir():
    """
    Determines whether the current file is part of a git repository. If the current file is not part of a git
    repository, returns None.

    Returns:
        (bool): True if current file is part of a git repository.
    """
    return get_git_dir() is not None



ultralytics.utils.get_git_dir()

ν˜„μž¬ 파일이 git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 일뢀인지 μ—¬λΆ€λ₯Ό κ²°μ •ν•˜κ³ , λ§Œμ•½ κ·Έλ ‡λ‹€λ©΄ 리포지토리 루트 디렉터리λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€. λ§Œμ•½ 이면 ν˜„μž¬ 파일이 git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 일뢀가 μ•„λ‹Œ 경우 None을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

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

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

루트 디렉터리λ₯Ό 찾으면 Git, 찾지 λͺ»ν•˜λ©΄ μ—†μŒμœΌλ‘œ μ„€μ •ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_git_dir():
    """
    Determines whether the current file is part of a git repository and if so, returns the repository root directory. If
    the current file is not part of a git repository, returns None.

    Returns:
        (Path | None): Git root directory if found or None if not found.
    """
    for d in Path(__file__).parents:
        if (d / ".git").is_dir():
            return d



ultralytics.utils.get_git_origin_url()

git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 원본 URL을 κ²€μƒ‰ν•©λ‹ˆλ‹€.

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

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

git λ¦¬ν¬μ§€ν† λ¦¬μ˜ 원본 URL λ˜λŠ” git 디렉터리가 μ•„λ‹Œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_git_origin_url():
    """
    Retrieves the origin URL of a git repository.

    Returns:
        (str | None): The origin URL of the git repository or None if not git directory.
    """
    if is_git_dir():
        with contextlib.suppress(subprocess.CalledProcessError):
            origin = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
            return origin.decode().strip()



ultralytics.utils.get_git_branch()

ν˜„μž¬ git 브랜치 이름을 λ°˜ν™˜ν•©λ‹ˆλ‹€. git 리포지토리에 μ—†λŠ” 경우 None을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

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

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

ν˜„μž¬ git 브랜치 이름 λ˜λŠ” git 디렉터리가 μ•„λ‹Œ 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_git_branch():
    """
    Returns the current git branch name. If not in a git repository, returns None.

    Returns:
        (str | None): The current git branch name or None if not a git directory.
    """
    if is_git_dir():
        with contextlib.suppress(subprocess.CalledProcessError):
            origin = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"])
            return origin.decode().strip()



ultralytics.utils.get_default_args(func)

ν•¨μˆ˜μ— λŒ€ν•œ κΈ°λ³Έ 인수의 λ”•μ…”λ„ˆλ¦¬λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

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

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

κ²€μ‚¬ν•˜λŠ” κΈ°λŠ₯μž…λ‹ˆλ‹€.

ν•„μˆ˜

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

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

각 ν‚€κ°€ λ§€κ°œλ³€μˆ˜ 이름이고 각 값이 ν•΄λ‹Ή λ§€κ°œλ³€μˆ˜μ˜ 기본값인 λ”•μ…”λ„ˆλ¦¬μž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_default_args(func):
    """
    Returns a dictionary of default arguments for a function.

    Args:
        func (callable): The function to inspect.

    Returns:
        (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
    """
    signature = inspect.signature(func)
    return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}



ultralytics.utils.get_ubuntu_version()

OSκ°€ μš°λΆ„νˆ¬μΈ 경우 μš°λΆ„νˆ¬ 버전을 κ²€μƒ‰ν•©λ‹ˆλ‹€.

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

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

μš°λΆ„νˆ¬ 버전 λ˜λŠ” μš°λΆ„νˆ¬ OSκ°€ μ•„λ‹Œ 경우 μ—†μŒ.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_ubuntu_version():
    """
    Retrieve the Ubuntu version if the OS is Ubuntu.

    Returns:
        (str): Ubuntu version or None if not an Ubuntu OS.
    """
    if is_ubuntu():
        with contextlib.suppress(FileNotFoundError, AttributeError):
            with open("/etc/os-release") as f:
                return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]



ultralytics.utils.get_user_config_dir(sub_dir='Ultralytics')

ν™˜κ²½ 운영 μ²΄μ œμ— 따라 μ μ ˆν•œ μ„€μ • 디렉터리λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

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

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

생성할 ν•˜μœ„ λ””λ ‰ν„°λ¦¬μ˜ μ΄λ¦„μž…λ‹ˆλ‹€.

'Ultralytics'

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

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

μ‚¬μš©μž ꡬ성 λ””λ ‰ν„°λ¦¬μ˜ κ²½λ‘œμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def get_user_config_dir(sub_dir="Ultralytics"):
    """
    Return the appropriate config directory based on the environment operating system.

    Args:
        sub_dir (str): The name of the subdirectory to create.

    Returns:
        (Path): The path to the user config directory.
    """
    if WINDOWS:
        path = Path.home() / "AppData" / "Roaming" / sub_dir
    elif MACOS:  # macOS
        path = Path.home() / "Library" / "Application Support" / sub_dir
    elif LINUX:
        path = Path.home() / ".config" / sub_dir
    else:
        raise ValueError(f"Unsupported operating system: {platform.system()}")

    # GCP and AWS lambda fix, only /tmp is writeable
    if not is_dir_writeable(path.parent):
        LOGGER.warning(
            f"WARNING ⚠️ user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD."
            "Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path."
        )
        path = Path("/tmp") / sub_dir if is_dir_writeable("/tmp") else Path().cwd() / sub_dir

    # Create the subdirectory if it does not exist
    path.mkdir(parents=True, exist_ok=True)

    return path



ultralytics.utils.colorstr(*input)

제곡된 색상 및 μŠ€νƒ€μΌ 인수λ₯Ό 기반으둜 λ¬Έμžμ—΄μ— 색을 μ§€μ •ν•©λ‹ˆλ‹€. ANSI μ΄μŠ€μΌ€μ΄ν”„ μ½”λ“œλ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€. μžμ„Έν•œ λ‚΄μš©μ€ https://en.wikipedia.org/wiki/ANSI_escape_code 을 μ°Έμ‘°ν•˜μ„Έμš”.

이 ν•¨μˆ˜λŠ” 두 가지 λ°©λ²•μœΌλ‘œ ν˜ΈμΆœν•  수 μžˆμŠ΅λ‹ˆλ‹€.
  • colorstr('color', 'style', 'your string')
  • colorstr('λ¬Έμžμ—΄')

두 번째 μ–‘μ‹μ—μ„œλŠ” 기본적으둜 'νŒŒλž€μƒ‰'κ³Ό 'ꡡ게'κ°€ μ μš©λ©λ‹ˆλ‹€.

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

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

처음 n-1개의 λ¬Έμžμ—΄μ΄ 색상 및 μŠ€νƒ€μΌ 인수인 λ¬Έμžμ—΄ μ‹œν€€μŠ€μž…λ‹ˆλ‹€, λ§ˆμ§€λ§‰ λ¬Έμžμ—΄μ€ 색을 지정할 λ¬Έμžμ—΄μž…λ‹ˆλ‹€.

()
μ§€μ›λ˜λŠ” 색상 및 μŠ€νƒ€μΌ

κΈ°λ³Έ 색상: 'κ²€μ •', 'λΉ¨κ°•', '초둝', 'λ…Έλž‘', 'νŒŒλž‘', 'λ§ˆμ  νƒ€', '청둝', '흰색' 밝은 색상: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow', 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white' 기타: '끝', 'ꡡ게', '밑쀄'

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

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

μ§€μ •λœ 색상 및 μŠ€νƒ€μΌμ— λŒ€ν•œ ANSI μ΄μŠ€μΌ€μ΄ν”„ μ½”λ“œλ‘œ λž˜ν•‘λœ μž…λ ₯ λ¬Έμžμ—΄μž…λ‹ˆλ‹€.

μ˜ˆμ‹œ:

>>> colorstr('blue', 'bold', 'hello world')
>>> 'hello world'
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def colorstr(*input):
    """
    Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes.
    See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.

    This function can be called in two ways:
        - colorstr('color', 'style', 'your string')
        - colorstr('your string')

    In the second form, 'blue' and 'bold' will be applied by default.

    Args:
        *input (str): A sequence of strings where the first n-1 strings are color and style arguments,
                      and the last string is the one to be colored.

    Supported Colors and Styles:
        Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
        Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
                       'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
        Misc: 'end', 'bold', 'underline'

    Returns:
        (str): The input string wrapped with ANSI escape codes for the specified color and style.

    Examples:
        >>> colorstr('blue', 'bold', 'hello world')
        >>> '\033[34m\033[1mhello world\033[0m'
    """
    *args, string = input if len(input) > 1 else ("blue", "bold", input[0])  # color arguments, string
    colors = {
        "black": "\033[30m",  # basic colors
        "red": "\033[31m",
        "green": "\033[32m",
        "yellow": "\033[33m",
        "blue": "\033[34m",
        "magenta": "\033[35m",
        "cyan": "\033[36m",
        "white": "\033[37m",
        "bright_black": "\033[90m",  # bright colors
        "bright_red": "\033[91m",
        "bright_green": "\033[92m",
        "bright_yellow": "\033[93m",
        "bright_blue": "\033[94m",
        "bright_magenta": "\033[95m",
        "bright_cyan": "\033[96m",
        "bright_white": "\033[97m",
        "end": "\033[0m",  # misc
        "bold": "\033[1m",
        "underline": "\033[4m",
    }
    return "".join(colors[x] for x in args) + f"{string}" + colors["end"]



ultralytics.utils.remove_colorstr(input_string)

λ¬Έμžμ—΄μ—μ„œ ANSI μ΄μŠ€μΌ€μ΄ν”„ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ—¬ 효과적으둜 색상을 ν•΄μ œν•©λ‹ˆλ‹€.

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

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

색상 및 μŠ€νƒ€μΌμ„ μ œκ±°ν•  λ¬Έμžμ—΄μž…λ‹ˆλ‹€.

ν•„μˆ˜

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

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

λͺ¨λ“  ANSI μ΄μŠ€μΌ€μ΄ν”„ μ½”λ“œκ°€ 제거된 μƒˆ λ¬Έμžμ—΄μž…λ‹ˆλ‹€.

μ˜ˆμ‹œ:

>>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))
>>> 'hello world'
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def remove_colorstr(input_string):
    """
    Removes ANSI escape codes from a string, effectively un-coloring it.

    Args:
        input_string (str): The string to remove color and style from.

    Returns:
        (str): A new string with all ANSI escape codes removed.

    Examples:
        >>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))
        >>> 'hello world'
    """
    ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
    return ansi_escape.sub("", input_string)



ultralytics.utils.threaded(func)

기본적으둜 λŒ€μƒ ν•¨μˆ˜λ₯Ό λ©€ν‹° μŠ€λ ˆλ“œλ‘œ μ‹€ν–‰ν•˜κ³  μŠ€λ ˆλ“œ λ˜λŠ” ν•¨μˆ˜ κ²°κ³Όλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

μŠ€λ ˆλ“œ λ°μ½”λ ˆμ΄ν„°λ‘œ μ‚¬μš©ν•©λ‹ˆλ‹€. 'threaded=False'κ°€ μ „λ‹¬λ˜μ§€ μ•ŠλŠ” ν•œ ν•¨μˆ˜λŠ” λ³„λ„μ˜ μŠ€λ ˆλ“œμ—μ„œ μ‹€ν–‰λ©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def threaded(func):
    """
    Multi-threads a target function by default and returns the thread or function result.

    Use as @threaded decorator. The function runs in a separate thread unless 'threaded=False' is passed.
    """

    def wrapper(*args, **kwargs):
        """Multi-threads a given function based on 'threaded' kwarg and returns the thread or function result."""
        if kwargs.pop("threaded", True):  # run in thread
            thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
            thread.start()
            return thread
        else:
            return func(*args, **kwargs)

    return wrapper



ultralytics.utils.set_sentry()

였λ₯˜ 좔적 및 보고λ₯Ό μœ„ν•΄ Sentry SDKλ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€. sentry_sdk νŒ¨ν‚€μ§€κ°€ μ„€μΉ˜λ˜μ–΄ 있고 μ„€μ •μ—μ„œ sync=True인 κ²½μš°μ—λ§Œ μ‚¬μš©λ©λ‹ˆλ‹€. 'yolo settings'λ₯Ό μ‹€ν–‰ν•˜μ—¬ μ„€μ • YAML νŒŒμΌμ„ ν™•μΈν•˜κ³  μ—…λ°μ΄νŠΈν•©λ‹ˆλ‹€.

였λ₯˜ 전솑에 ν•„μš”ν•œ 쑰건(λͺ¨λ“  쑰건이 μΆ©μ‘±λ˜μ§€ μ•ŠμœΌλ©΄ 였λ₯˜κ°€ λ³΄κ³ λ˜μ§€ μ•ŠμŒ): - sentry_sdk νŒ¨ν‚€μ§€κ°€ μ„€μΉ˜λ¨ - YOLO μ„€μ •μ—μ„œ sync=true - pytestκ°€ μ‹€ν–‰λ˜κ³  μžˆμ§€ μ•ŠμŒ - pip νŒ¨ν‚€μ§€ μ„€μΉ˜μ—μ„œ μ‹€ν–‰ 쀑 - git이 μ•„λ‹Œ λ””λ ‰ν„°λ¦¬μ—μ„œ μ‹€ν–‰ 쀑 - μˆœμœ„ -1 λ˜λŠ” 0으둜 μ‹€ν–‰ 쀑 - 온라인 ν™˜κ²½ - CLI νŒ¨ν‚€μ§€λ₯Ό μ‹€ν–‰ν•˜λŠ” 데 μ‚¬μš©λ¨(κΈ°λ³Έ CLI λͺ…λ Ήμ˜ 이름에 'yolo'둜 확인)

λ˜ν•œ 이 ν•¨μˆ˜λŠ” ν‚€λ³΄λ“œ μΈν„°λŸ½νŠΈ 및 파일 미탐색 μ—λŸ¬ μ˜ˆμ™Έλ₯Ό λ¬΄μ‹œν•˜κ³  μ˜ˆμ™Έ λ©”μ‹œμ§€μ— 'λ©”λͺ¨λ¦¬ λΆ€μ‘±'이 ν¬ν•¨λœ 이벀트λ₯Ό μ œμ™Έν•˜λ„λ‘ μ„€μ •ν•©λ‹ˆλ‹€.

λ˜ν•œ 이 κΈ°λŠ₯은 μ„ΌνŠΈλ¦¬ μ΄λ²€νŠΈμ— λŒ€ν•œ μ‚¬μš©μž 지정 νƒœκ·Έ 및 μ‚¬μš©μž 정보λ₯Ό μ„€μ •ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def set_sentry():
    """
    Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and
    sync=True in settings. Run 'yolo settings' to see and update settings YAML file.

    Conditions required to send errors (ALL conditions must be met or no errors will be reported):
        - sentry_sdk package is installed
        - sync=True in YOLO settings
        - pytest is not running
        - running in a pip package installation
        - running in a non-git directory
        - running with rank -1 or 0
        - online environment
        - CLI used to run package (checked with 'yolo' as the name of the main CLI command)

    The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError
    exceptions and to exclude events with 'out of memory' in their exception message.

    Additionally, the function sets custom tags and user information for Sentry events.
    """

    def before_send(event, hint):
        """
        Modify the event before sending it to Sentry based on specific exception types and messages.

        Args:
            event (dict): The event dictionary containing information about the error.
            hint (dict): A dictionary containing additional information about the error.

        Returns:
            dict: The modified event or None if the event should not be sent to Sentry.
        """
        if "exc_info" in hint:
            exc_type, exc_value, tb = hint["exc_info"]
            if exc_type in (KeyboardInterrupt, FileNotFoundError) or "out of memory" in str(exc_value):
                return None  # do not send event

        event["tags"] = {
            "sys_argv": sys.argv[0],
            "sys_argv_name": Path(sys.argv[0]).name,
            "install": "git" if is_git_dir() else "pip" if is_pip_package() else "other",
            "os": ENVIRONMENT,
        }
        return event

    if (
        SETTINGS["sync"]
        and RANK in (-1, 0)
        and Path(sys.argv[0]).name == "yolo"
        and not TESTS_RUNNING
        and ONLINE
        and is_pip_package()
        and not is_git_dir()
    ):
        # If sentry_sdk package is not installed then return and do not use Sentry
        try:
            import sentry_sdk  # noqa
        except ImportError:
            return

        sentry_sdk.init(
            dsn="https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016",
            debug=False,
            traces_sample_rate=1.0,
            release=__version__,
            environment="production",  # 'dev' or 'production'
            before_send=before_send,
            ignore_errors=[KeyboardInterrupt, FileNotFoundError],
        )
        sentry_sdk.set_user({"id": SETTINGS["uuid"]})  # SHA-256 anonymized UUID hash



ultralytics.utils.deprecation_warn(arg, new_arg, version=None)

더 이상 μ‚¬μš©λ˜μ§€ μ•ŠλŠ” μΈμˆ˜κ°€ μ‚¬μš©λ˜λ©΄ μ‚¬μš© 쀑단 κ²½κ³ λ₯Ό λ°œν–‰ν•˜μ—¬ μ—…λ°μ΄νŠΈλœ 인수λ₯Ό μ œμ•ˆν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def deprecation_warn(arg, new_arg, version=None):
    """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
    if not version:
        version = float(__version__[:3]) + 0.2  # deprecate after 2nd major release
    LOGGER.warning(
        f"WARNING ⚠️ '{arg}' is deprecated and will be removed in 'ultralytics {version}' in the future. "
        f"Please use '{new_arg}' instead."
    )



ultralytics.utils.clean_url(url)

URLμ—μ„œ 인증을 μ œκ±°ν•©λ‹ˆλ‹€(예: https://url.com/file.txt?auth -> https://url.com/file.txt).

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def clean_url(url):
    """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
    url = Path(url).as_posix().replace(":/", "://")  # Pathlib turns :// -> :/, as_posix() for Windows
    return urllib.parse.unquote(url).split("?")[0]  # '%2F' to '/', split https://url.com/file.txt?auth



ultralytics.utils.url2file(url)

URL을 파일 μ΄λ¦„μœΌλ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€(예: https://url.com/file.txt?auth -> file.txt).

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/utils/__init__.py
def url2file(url):
    """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
    return Path(clean_url(url)).name





생성됨 2023-11-12, μ—…λ°μ΄νŠΈλ¨ 2024-01-27
μž‘μ„±μž: glenn-jocher (7), Laughing-q (1)