์ฝ˜ํ…์ธ ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

์ฐธ์กฐ 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 any

์‚ฌ์šฉ์ž ์ง€์ • ๊ธฐ๋ณธ๊ฐ’์ด ์ ์šฉ๋œ ํ‚ค์›Œ๋“œ ์ธ์ˆ˜์ž…๋‹ˆ๋‹ค.

{}
์˜ ์†Œ์Šค ์ฝ”๋“œ 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 (any): 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๋Š” ์ดํ„ฐ๋Ÿฌ๋ธ” ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•˜๊ณ  dict() ๋ฐ ๋ฃจํ”„์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ 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 ์„ค์ • 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

        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)
            help_msg = (
                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'. "
                "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
            )
            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 "
                    f"with your settings or a recent ultralytics package update. {help_msg}"
                )
                self.reset()

            if self.get("datasets_dir") == self.get("runs_dir"):
                LOGGER.warning(
                    f"WARNING โš ๏ธ Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
                    f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
                    f"Please change one to avoid possible issues during training. {help_msg}"
                )

    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

    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)
        help_msg = (
            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'. "
            "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
        )
        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 "
                f"with your settings or a recent ultralytics package update. {help_msg}"
            )
            self.reset()

        if self.get("datasets_dir") == self.get("runs_dir"):
            LOGGER.warning(
                f"WARNING โš ๏ธ Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
                f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
                f"Please change one to avoid possible issues during training. {help_msg}"
            )

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, ensuring compatibility across different
    environments.
    """
    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, with checks for compatibility
    formatter = logging.Formatter("%(message)s")  # Default formatter
    if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":

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

        try:
            # Attempt to reconfigure stdout to use UTF-8 encoding if possible
            if hasattr(sys.stdout, "reconfigure"):
                sys.stdout.reconfigure(encoding="utf-8")
            # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
            elif hasattr(sys.stdout, "buffer"):
                import io

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

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

    # Set up the logger
    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.read_device_model()

์‹œ์Šคํ…œ์—์„œ ์žฅ์น˜ ๋ชจ๋ธ ์ •๋ณด๋ฅผ ์ฝ๊ณ  ๋น ๋ฅธ ์•ก์„ธ์Šค๋ฅผ ์œ„ํ•ด ์บ์‹œ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. is_jetson() ๋ฐ is_raspberrypi().

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
str

์„ฑ๊ณต์ ์œผ๋กœ ์ฝ์œผ๋ฉด ํŒŒ์ผ ๋‚ด์šฉ์„ ๋ชจ๋ธ๋งํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/utils/__init__.py
def read_device_model() -> str:
    """
    Reads the device model information from the system and caches it for quick access. Used by is_jetson() and
    is_raspberrypi().

    Returns:
        (str): Model file contents if read successfully or empty string otherwise.
    """
    with contextlib.suppress(Exception):
        with open("/proc/device-tree/model") as f:
            return f.read()
    return ""



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 ๋…ธํŠธ๋ถ ๋‚ด์—์„œ ์‹คํ–‰ ์ค‘์ด๋ฉด True, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด False์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ 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.
    """
    with contextlib.suppress(Exception):
        with open("/proc/self/cgroup") as f:
            return "docker" in f.read()
    return False



ultralytics.utils.is_raspberrypi()

์žฅ์น˜ ๋ชจ๋ธ ์ •๋ณด๋ฅผ ํ™•์ธํ•˜์—ฌ Python ํ™˜๊ฒฝ์ด ๋ผ์ฆˆ๋ฒ ๋ฆฌํŒŒ์ด์—์„œ ์‹คํ–‰ ์ค‘์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
bool

๋ผ์ฆˆ๋ฒ ๋ฆฌ ํŒŒ์ด์—์„œ ์‹คํ–‰ ์ค‘์ด๋ฉด ์ฐธ, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๊ฑฐ์ง“์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/utils/__init__.py
def is_raspberrypi() -> bool:
    """
    Determines if the Python environment is running on a Raspberry Pi by checking the device model information.

    Returns:
        (bool): True if running on a Raspberry Pi, False otherwise.
    """
    return "Raspberry Pi" in PROC_DEVICE_MODEL



ultralytics.utils.is_jetson()

์žฅ์น˜ ๋ชจ๋ธ์„ ํ™•์ธํ•˜์—ฌ Python ํ™˜๊ฒฝ์ด Jetson Nano ์žฅ์น˜์—์„œ ์‹คํ–‰ ์ค‘์ธ์ง€ ๋˜๋Š” Jetson Orin ์žฅ์น˜์—์„œ ์‹คํ–‰ ์ค‘์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. ์ •๋ณด๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
bool

Jetson Nano ๋˜๋Š” Jetson Orin์—์„œ ์‹คํ–‰ ์ค‘์ธ ๊ฒฝ์šฐ True, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด False์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/utils/__init__.py
def is_jetson() -> bool:
    """
    Determines if the Python environment is running on a Jetson Nano or Jetson Orin device by checking the device model
    information.

    Returns:
        (bool): True if running on a Jetson Nano or Jetson Orin, False otherwise.
    """
    return "NVIDIA" in PROC_DEVICE_MODEL  # i.e. "NVIDIA Jetson Nano" or "NVIDIA Orin NX"



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.
    """
    with contextlib.suppress(Exception):
        assert str(os.getenv("YOLO_OFFLINE", "")).lower() != "true"  # check if ENV var YOLO_OFFLINE="True"
        import socket

        for dns in ("1.1.1.1", "8.8.8.8"):  # check Cloudflare and Google DNS
            socket.create_connection(address=(dns, 80), timeout=1.0).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๊ฐ€ ์‹คํ–‰ ์ค‘์ด๋ฉด True, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด False์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ 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(ARGV[0]).stem)



ultralytics.utils.is_github_action_running()

ํ˜„์žฌ ํ™˜๊ฒฝ์ด GitHub Actions ๋Ÿฌ๋„ˆ์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
bool

ํ˜„์žฌ ํ™˜๊ฒฝ์ด GitHub Actions ์‹คํ–‰๊ธฐ์ธ ๊ฒฝ์šฐ 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.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.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 GIT_DIR is not None



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()

์˜ค๋ฅ˜ ์ถ”์  ๋ฐ ๋ณด๊ณ ๋ฅผ ์œ„ํ•ด ์„ผํŠธ๋ฆฌ SDK๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. sentry_sdk ํŒจํ‚ค์ง€๊ฐ€ ์„ค์น˜๋˜์–ด ์žˆ๊ณ  ์„ค์ •์—์„œ ์„ค์ •์—์„œ sync=False์ธ ๊ฒฝ์šฐ์—๋งŒ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. 'yolo settings'๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ์„ค์ • YAML ํŒŒ์ผ์„ ํ™•์ธํ•˜๊ณ  ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค.

์˜ค๋ฅ˜ ์ „์†ก์— ํ•„์š”ํ•œ ์กฐ๊ฑด(๋ชจ๋“  ์กฐ๊ฑด์ด ์ถฉ์กฑ๋˜์ง€ ์•Š์œผ๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋ณด๊ณ ๋˜์ง€ ์•Š์Œ): - sentry_sdk ํŒจํ‚ค์ง€๊ฐ€ ์„ค์น˜๋จ - YOLO ์„ค์ •์—์„œ sync=true - pytest๊ฐ€ ์‹คํ–‰๋˜๊ณ  ์žˆ์ง€ ์•Š์Œ - pip ํŒจํ‚ค์ง€ ์„ค์น˜์—์„œ ์‹คํ–‰ ์ค‘ - git์ด ์•„๋‹Œ ๋””๋ ‰ํ„ฐ๋ฆฌ์—์„œ ์‹คํ–‰ ์ค‘ - ์ˆœ์œ„ -1 ๋˜๋Š” 0์œผ๋กœ ์‹คํ–‰ ์ค‘ - ์˜จ๋ผ์ธ ํ™˜๊ฒฝ - CLI ํŒจํ‚ค์ง€๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋จ(๊ธฐ๋ณธ CLI ๋ช…๋ น์˜ ์ด๋ฆ„์œผ๋กœ 'yolo'๋กœ ํ™•์ธ)

๋˜ํ•œ ์ด ํ•จ์ˆ˜๋Š” ํ‚ค๋ณด๋“œ ์ธํ„ฐ๋ŸฝํŠธ ๋ฐ FileNotFoundError ์˜ˆ์™ธ๋ฅผ ๋ฌด์‹œํ•˜๊ณ  ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€์— '๋ฉ”๋ชจ๋ฆฌ ๋ถ€์กฑ'์ด ์žˆ๋Š” ์ด๋ฒคํŠธ๋ฅผ ์ œ์™ธํ•˜๋„๋ก ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

๋˜ํ•œ ์ด ๊ธฐ๋Šฅ์€ ์„ผํŠธ๋ฆฌ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์‚ฌ์šฉ์ž ์ง€์ • ํƒœ๊ทธ์™€ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ 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": ARGV[0],
            "sys_argv_name": Path(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(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-05-08
์ž‘์„ฑ์ž: Burhan-Q (1), ๊ธ€๋ Œ-์กฐ์ฒ˜ (8), ์›ƒ๋Š”-ํ (1)