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

์ฐธ์กฐ ultralytics/cfg/__init__.py

์ฐธ๊ณ 

์ด ํŒŒ์ผ์€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/cfg/init.py์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ๋ฐœ๊ฒฌํ•˜๋ฉด ํ’€ ๋ฆฌํ€˜์ŠคํŠธ (๐Ÿ› ๏ธ)๋ฅผ ์ œ์ถœํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋„๋ก ๋„์™€์ฃผ์„ธ์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ™!



ultralytics.cfg.cfg2dict(cfg)

ํŒŒ์ผ ๊ฒฝ๋กœ, ๋ฌธ์ž์—ด, SimpleNamespace ๊ฐœ์ฒด ๋“ฑ ๊ตฌ์„ฑ ๊ฐœ์ฒด๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
cfg str | Path | dict | SimpleNamespace

๊ตฌ์„ฑ ๊ฐœ์ฒด๋ฅผ ์‚ฌ์ „์œผ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

ํ•„์ˆ˜

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

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช…
cfg dict

์‚ฌ์ „ ํ˜•์‹์˜ ๊ตฌ์„ฑ ๊ฐœ์ฒด์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def cfg2dict(cfg):
    """
    Convert a configuration object to a dictionary, whether it is a file path, a string, or a SimpleNamespace object.

    Args:
        cfg (str | Path | dict | SimpleNamespace): Configuration object to be converted to a dictionary.

    Returns:
        cfg (dict): Configuration object in dictionary format.
    """
    if isinstance(cfg, (str, Path)):
        cfg = yaml_load(cfg)  # load dict
    elif isinstance(cfg, SimpleNamespace):
        cfg = vars(cfg)  # convert to dict
    return cfg



ultralytics.cfg.get_cfg(cfg=DEFAULT_CFG_DICT, overrides=None)

ํŒŒ์ผ ๋˜๋Š” ์‚ฌ์ „์—์„œ ๊ตฌ์„ฑ ๋ฐ์ดํ„ฐ๋ฅผ ๋กœ๋“œํ•˜๊ณ  ๋ณ‘ํ•ฉํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
cfg str | Path | Dict | SimpleNamespace

๊ตฌ์„ฑ ๋ฐ์ดํ„ฐ.

DEFAULT_CFG_DICT
overrides str | Dict | optional

ํŒŒ์ผ ์ด๋ฆ„ ๋˜๋Š” ์‚ฌ์ „ ํ˜•์‹์œผ๋กœ ์žฌ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ ์—†์Œ์ž…๋‹ˆ๋‹ค.

None

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

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

๊ต์œก ์ธ์ˆ˜ ๋„ค์ž„์ŠคํŽ˜์ด์Šค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, overrides: Dict = None):
    """
    Load and merge configuration data from a file or dictionary.

    Args:
        cfg (str | Path | Dict | SimpleNamespace): Configuration data.
        overrides (str | Dict | optional): Overrides in the form of a file name or a dictionary. Default is None.

    Returns:
        (SimpleNamespace): Training arguments namespace.
    """
    cfg = cfg2dict(cfg)

    # Merge overrides
    if overrides:
        overrides = cfg2dict(overrides)
        if "save_dir" not in cfg:
            overrides.pop("save_dir", None)  # special override keys to ignore
        check_dict_alignment(cfg, overrides)
        cfg = {**cfg, **overrides}  # merge cfg and overrides dicts (prefer overrides)

    # Special handling for numeric project/name
    for k in "project", "name":
        if k in cfg and isinstance(cfg[k], (int, float)):
            cfg[k] = str(cfg[k])
    if cfg.get("name") == "model":  # assign model to 'name' arg
        cfg["name"] = cfg.get("model", "").split(".")[0]
        LOGGER.warning(f"WARNING โš ๏ธ 'name=model' automatically updated to 'name={cfg['name']}'.")

    # Type and Value checks
    check_cfg(cfg)

    # Return instance
    return IterableSimpleNamespace(**cfg)



ultralytics.cfg.check_cfg(cfg, hard=True)

Ultralytics ๊ตฌ์„ฑ ์ธ์ˆ˜ ์œ ํ˜• ๋ฐ ๊ฐ’์„ ํ™•์ธํ•˜์„ธ์š”.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def check_cfg(cfg, hard=True):
    """Check Ultralytics configuration argument types and values."""
    for k, v in cfg.items():
        if v is not None:  # None values may be from optional args
            if k in CFG_FLOAT_KEYS and not isinstance(v, (int, float)):
                if hard:
                    raise TypeError(
                        f"'{k}={v}' is of invalid type {type(v).__name__}. "
                        f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
                    )
                cfg[k] = float(v)
            elif k in CFG_FRACTION_KEYS:
                if not isinstance(v, (int, float)):
                    if hard:
                        raise TypeError(
                            f"'{k}={v}' is of invalid type {type(v).__name__}. "
                            f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
                        )
                    cfg[k] = v = float(v)
                if not (0.0 <= v <= 1.0):
                    raise ValueError(f"'{k}={v}' is an invalid value. " f"Valid '{k}' values are between 0.0 and 1.0.")
            elif k in CFG_INT_KEYS and not isinstance(v, int):
                if hard:
                    raise TypeError(
                        f"'{k}={v}' is of invalid type {type(v).__name__}. " f"'{k}' must be an int (i.e. '{k}=8')"
                    )
                cfg[k] = int(v)
            elif k in CFG_BOOL_KEYS and not isinstance(v, bool):
                if hard:
                    raise TypeError(
                        f"'{k}={v}' is of invalid type {type(v).__name__}. "
                        f"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')"
                    )
                cfg[k] = bool(v)



ultralytics.cfg.get_save_dir(args, name=None)

train/val/predict ์ธ์ž๋กœ๋ถ€ํ„ฐ ์ƒ์„ฑ๋œ save_dir์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def get_save_dir(args, name=None):
    """Return save_dir as created from train/val/predict arguments."""

    if getattr(args, "save_dir", None):
        save_dir = args.save_dir
    else:
        from ultralytics.utils.files import increment_path

        project = args.project or (ROOT.parent / "tests/tmp/runs" if TESTS_RUNNING else RUNS_DIR) / args.task
        name = name or args.name or f"{args.mode}"
        save_dir = increment_path(Path(project) / name, exist_ok=args.exist_ok if RANK in {-1, 0} else True)

    return Path(save_dir)



ultralytics.cfg._handle_deprecation(custom)

๋” ์ด์ƒ ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” ๊ตฌ์„ฑ ํ‚ค๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•˜๋“œ์ฝ”๋”ฉ๋œ ํ•จ์ˆ˜.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def _handle_deprecation(custom):
    """Hardcoded function to handle deprecated config keys."""

    for key in custom.copy().keys():
        if key == "boxes":
            deprecation_warn(key, "show_boxes")
            custom["show_boxes"] = custom.pop("boxes")
        if key == "hide_labels":
            deprecation_warn(key, "show_labels")
            custom["show_labels"] = custom.pop("hide_labels") == "False"
        if key == "hide_conf":
            deprecation_warn(key, "show_conf")
            custom["show_conf"] = custom.pop("hide_conf") == "False"
        if key == "line_thickness":
            deprecation_warn(key, "line_width")
            custom["line_width"] = custom.pop("line_thickness")

    return custom



ultralytics.cfg.check_dict_alignment(base, custom, e=None)

์ด ๊ธฐ๋Šฅ์€ ์‚ฌ์šฉ์ž ์ง€์ • ๊ตฌ์„ฑ ๋ชฉ๋ก๊ณผ ๊ธฐ๋ณธ ๊ตฌ์„ฑ ๋ชฉ๋ก ๊ฐ„์— ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ํ‚ค๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ํ‚ค๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด ๊ธฐ๋ณธ ๋ชฉ๋ก์—์„œ ์œ ์‚ฌํ•œ ํ‚ค๋ฅผ ์ถœ๋ ฅํ•˜๊ณ  ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
custom dict

์‚ฌ์šฉ์ž ์ง€์ • ๊ตฌ์„ฑ ์˜ต์…˜ ์‚ฌ์ „

ํ•„์ˆ˜
base dict

๊ธฐ๋ณธ ๊ตฌ์„ฑ ์˜ต์…˜ ์‚ฌ์ „

ํ•„์ˆ˜
e Error

ํ˜ธ์ถœ ํ•จ์ˆ˜์— ์˜ํ•ด ์ „๋‹ฌ๋˜๋Š” ์„ ํƒ์  ์˜ค๋ฅ˜์ž…๋‹ˆ๋‹ค.

None
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def check_dict_alignment(base: Dict, custom: Dict, e=None):
    """
    This function checks for any mismatched keys between a custom configuration list and a base configuration list. If
    any mismatched keys are found, the function prints out similar keys from the base list and exits the program.

    Args:
        custom (dict): a dictionary of custom configuration options
        base (dict): a dictionary of base configuration options
        e (Error, optional): An optional error that is passed by the calling function.
    """
    custom = _handle_deprecation(custom)
    base_keys, custom_keys = (set(x.keys()) for x in (base, custom))
    mismatched = [k for k in custom_keys if k not in base_keys]
    if mismatched:
        from difflib import get_close_matches

        string = ""
        for x in mismatched:
            matches = get_close_matches(x, base_keys)  # key list
            matches = [f"{k}={base[k]}" if base.get(k) is not None else k for k in matches]
            match_str = f"Similar arguments are i.e. {matches}." if matches else ""
            string += f"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\n"
        raise SyntaxError(string + CLI_HELP_MSG) from e



ultralytics.cfg.merge_equals_args(args)

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

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
args List[str]

๊ฐ ์š”์†Œ๊ฐ€ ์ธ์ˆ˜๊ฐ€ ๋˜๋Š” ๋ฌธ์ž์—ด ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜

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

์œ ํ˜• ์„ค๋ช…
List[str]

๊ณ ๋ฆฝ๋œ '=' ์ฃผ์œ„์˜ ์ธ์ˆ˜๊ฐ€ ๋ณ‘ํ•ฉ๋œ ๋ฌธ์ž์—ด ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def merge_equals_args(args: List[str]) -> List[str]:
    """
    Merges arguments around isolated '=' args in a list of strings. The function considers cases where the first
    argument ends with '=' or the second starts with '=', as well as when the middle one is an equals sign.

    Args:
        args (List[str]): A list of strings where each element is an argument.

    Returns:
        (List[str]): A list of strings where the arguments around isolated '=' are merged.
    """
    new_args = []
    for i, arg in enumerate(args):
        if arg == "=" and 0 < i < len(args) - 1:  # merge ['arg', '=', 'val']
            new_args[-1] += f"={args[i + 1]}"
            del args[i + 1]
        elif arg.endswith("=") and i < len(args) - 1 and "=" not in args[i + 1]:  # merge ['arg=', 'val']
            new_args.append(f"{arg}{args[i + 1]}")
            del args[i + 1]
        elif arg.startswith("=") and i > 0:  # merge ['arg', '=val']
            new_args[-1] += arg
        else:
            new_args.append(arg)
    return new_args



ultralytics.cfg.handle_yolo_hub(args)

Ultralytics HUB ๋ช…๋ น์ค„ ์ธํ„ฐํŽ˜์ด์Šค(CLI) ๋ช…๋ น์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

์ด ํ•จ์ˆ˜๋Š” ๋กœ๊ทธ์ธ ๋ฐ ๋กœ๊ทธ์•„์›ƒ๊ณผ ๊ฐ™์€ Ultralytics HUB CLI ๋ช…๋ น์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. HUB ์ธ์ฆ๊ณผ ๊ด€๋ จ๋œ ์ธ์ˆ˜๊ฐ€ ํฌํ•จ๋œ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•  ๋•Œ ํ˜ธ์ถœํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
args List[str]

๋ช…๋ น์ค„ ์ธ์ˆ˜ ๋ชฉ๋ก

ํ•„์ˆ˜
์˜ˆ
python my_script.py hub login your_api_key
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def handle_yolo_hub(args: List[str]) -> None:
    """
    Handle Ultralytics HUB command-line interface (CLI) commands.

    This function processes Ultralytics HUB CLI commands such as login and logout.
    It should be called when executing a script with arguments related to HUB authentication.

    Args:
        args (List[str]): A list of command line arguments

    Example:
        ```bash
        python my_script.py hub login your_api_key
        ```
    """
    from ultralytics import hub

    if args[0] == "login":
        key = args[1] if len(args) > 1 else ""
        # Log in to Ultralytics HUB using the provided API key
        hub.login(key)
    elif args[0] == "logout":
        # Log out from Ultralytics HUB
        hub.logout()



ultralytics.cfg.handle_yolo_settings(args)

YOLO ์„ค์ • ๋ช…๋ น์ค„ ์ธํ„ฐํŽ˜์ด์Šค(CLI) ๋ช…๋ น์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

์ด ํ•จ์ˆ˜๋Š” ์žฌ์„ค์ •๊ณผ ๊ฐ™์€ YOLO ์„ค์ • CLI ๋ช…๋ น์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. YOLO ์„ค์ • ๊ด€๋ฆฌ์™€ ๊ด€๋ จ๋œ ์ธ์ˆ˜๊ฐ€ ํฌํ•จ๋œ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•  ๋•Œ ํ˜ธ์ถœํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
args List[str]

YOLO ์„ค์ • ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•œ ๋ช…๋ น์ค„ ์ธ์ˆ˜ ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
์˜ˆ
python my_script.py yolo settings reset
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def handle_yolo_settings(args: List[str]) -> None:
    """
    Handle YOLO settings command-line interface (CLI) commands.

    This function processes YOLO settings CLI commands such as reset.
    It should be called when executing a script with arguments related to YOLO settings management.

    Args:
        args (List[str]): A list of command line arguments for YOLO settings management.

    Example:
        ```bash
        python my_script.py yolo settings reset
        ```
    """
    url = "https://docs.ultralytics.com/quickstart/#ultralytics-settings"  # help URL
    try:
        if any(args):
            if args[0] == "reset":
                SETTINGS_YAML.unlink()  # delete the settings file
                SETTINGS.reset()  # create new settings
                LOGGER.info("Settings reset successfully")  # inform the user that settings have been reset
            else:  # save a new setting
                new = dict(parse_key_value_pair(a) for a in args)
                check_dict_alignment(SETTINGS, new)
                SETTINGS.update(new)

        LOGGER.info(f"๐Ÿ’ก Learn about settings at {url}")
        yaml_print(SETTINGS_YAML)  # print the current settings
    except Exception as e:
        LOGGER.warning(f"WARNING โš ๏ธ settings error: '{e}'. Please see {url} for help.")



ultralytics.cfg.handle_explorer()

Ultralytics ํƒ์ƒ‰๊ธฐ GUI๋ฅผ ์—ฝ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def handle_explorer():
    """Open the Ultralytics Explorer GUI."""
    checks.check_requirements("streamlit")
    LOGGER.info("๐Ÿ’ก Loading Explorer dashboard...")
    subprocess.run(["streamlit", "run", ROOT / "data/explorer/gui/dash.py", "--server.maxMessageSize", "2048"])



ultralytics.cfg.parse_key_value_pair(pair)

ํ•˜๋‚˜์˜ 'ํ‚ค=๊ฐ’' ์Œ์„ ๊ตฌ๋ฌธ ๋ถ„์„ํ•˜์—ฌ ํ‚ค์™€ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def parse_key_value_pair(pair):
    """Parse one 'key=value' pair and return key and value."""
    k, v = pair.split("=", 1)  # split on first '=' sign
    k, v = k.strip(), v.strip()  # remove spaces
    assert v, f"missing '{k}' value"
    return k, smart_value(v)



ultralytics.cfg.smart_value(v)

๋ฌธ์ž์—ด์„ int, float, bool ๋“ฑ๊ณผ ๊ฐ™์€ ๊ธฐ๋ณธ ์œ ํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def smart_value(v):
    """Convert a string to an underlying type such as int, float, bool, etc."""
    v_lower = v.lower()
    if v_lower == "none":
        return None
    elif v_lower == "true":
        return True
    elif v_lower == "false":
        return False
    else:
        with contextlib.suppress(Exception):
            return eval(v)
        return v



ultralytics.cfg.entrypoint(debug='')

์ด ํ•จ์ˆ˜๋Š” ultralytics ํŒจํ‚ค์ง€ ์ง„์ž…์ ์œผ๋กœ, ํŒจํ‚ค์ง€๋กœ ์ „๋‹ฌ๋œ ๋ช…๋ น์ค„ ์ธ์ˆ˜๋ฅผ ๋ฅผ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค.

์ด ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด - ํ•„์ˆ˜ YOLO ์ธ์ˆ˜๋ฅผ ๋ฌธ์ž์—ด ๋ชฉ๋ก์œผ๋กœ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค. - ์ˆ˜ํ–‰ํ•  ์ž‘์—…์„ 'detect', 'segment' ๋˜๋Š” 'classify' ์ค‘ ํ•˜๋‚˜๋กœ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. - 'train', 'val', 'test' ๋˜๋Š” 'predict' ์ค‘ ํ•˜๋‚˜์˜ ๋ชจ๋“œ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. - 'checks'์™€ ๊ฐ™์€ ํŠน์ˆ˜ ๋ชจ๋“œ ์‹คํ–‰ - ํŒจํ‚ค์ง€ ๊ตฌ์„ฑ์— ์˜ค๋ฒ„๋ผ์ด๋“œ ์ „๋‹ฌํ•˜๊ธฐ

ํŒจํ‚ค์ง€์˜ ๊ธฐ๋ณธ cfg๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์ „๋‹ฌ๋œ ์˜ค๋ฒ„๋ผ์ด๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ ๋‹ค์Œ ์ปดํŒŒ์ผ๋œ cfg๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ CLI ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def entrypoint(debug=""):
    """
    This function is the ultralytics package entrypoint, it's responsible for parsing the command line arguments passed
    to the package.

    This function allows for:
    - passing mandatory YOLO args as a list of strings
    - specifying the task to be performed, either 'detect', 'segment' or 'classify'
    - specifying the mode, either 'train', 'val', 'test', or 'predict'
    - running special modes like 'checks'
    - passing overrides to the package's configuration

    It uses the package's default cfg and initializes it using the passed overrides.
    Then it calls the CLI function with the composed cfg
    """
    args = (debug.split(" ") if debug else ARGV)[1:]
    if not args:  # no arguments passed
        LOGGER.info(CLI_HELP_MSG)
        return

    special = {
        "help": lambda: LOGGER.info(CLI_HELP_MSG),
        "checks": checks.collect_system_info,
        "version": lambda: LOGGER.info(__version__),
        "settings": lambda: handle_yolo_settings(args[1:]),
        "cfg": lambda: yaml_print(DEFAULT_CFG_PATH),
        "hub": lambda: handle_yolo_hub(args[1:]),
        "login": lambda: handle_yolo_hub(args),
        "copy-cfg": copy_default_cfg,
        "explorer": lambda: handle_explorer(),
    }
    full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}

    # Define common misuses of special commands, i.e. -h, -help, --help
    special.update({k[0]: v for k, v in special.items()})  # singular
    special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")})  # singular
    special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}}

    overrides = {}  # basic overrides, i.e. imgsz=320
    for a in merge_equals_args(args):  # merge spaces around '=' sign
        if a.startswith("--"):
            LOGGER.warning(f"WARNING โš ๏ธ argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.")
            a = a[2:]
        if a.endswith(","):
            LOGGER.warning(f"WARNING โš ๏ธ argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.")
            a = a[:-1]
        if "=" in a:
            try:
                k, v = parse_key_value_pair(a)
                if k == "cfg" and v is not None:  # custom.yaml passed
                    LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}")
                    overrides = {k: val for k, val in yaml_load(checks.check_yaml(v)).items() if k != "cfg"}
                else:
                    overrides[k] = v
            except (NameError, SyntaxError, ValueError, AssertionError) as e:
                check_dict_alignment(full_args_dict, {a: ""}, e)

        elif a in TASKS:
            overrides["task"] = a
        elif a in MODES:
            overrides["mode"] = a
        elif a.lower() in special:
            special[a.lower()]()
            return
        elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):
            overrides[a] = True  # auto-True for default bool args, i.e. 'yolo show' sets show=True
        elif a in DEFAULT_CFG_DICT:
            raise SyntaxError(
                f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign "
                f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}"
            )
        else:
            check_dict_alignment(full_args_dict, {a: ""})

    # Check keys
    check_dict_alignment(full_args_dict, overrides)

    # Mode
    mode = overrides.get("mode")
    if mode is None:
        mode = DEFAULT_CFG.mode or "predict"
        LOGGER.warning(f"WARNING โš ๏ธ 'mode' argument is missing. Valid modes are {MODES}. Using default 'mode={mode}'.")
    elif mode not in MODES:
        raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {MODES}.\n{CLI_HELP_MSG}")

    # Task
    task = overrides.pop("task", None)
    if task:
        if task not in TASKS:
            raise ValueError(f"Invalid 'task={task}'. Valid tasks are {TASKS}.\n{CLI_HELP_MSG}")
        if "model" not in overrides:
            overrides["model"] = TASK2MODEL[task]

    # Model
    model = overrides.pop("model", DEFAULT_CFG.model)
    if model is None:
        model = "yolov8n.pt"
        LOGGER.warning(f"WARNING โš ๏ธ 'model' argument is missing. Using default 'model={model}'.")
    overrides["model"] = model
    stem = Path(model).stem.lower()
    if "rtdetr" in stem:  # guess architecture
        from ultralytics import RTDETR

        model = RTDETR(model)  # no task argument
    elif "fastsam" in stem:
        from ultralytics import FastSAM

        model = FastSAM(model)
    elif "sam" in stem:
        from ultralytics import SAM

        model = SAM(model)
    else:
        from ultralytics import YOLO

        model = YOLO(model, task=task)
    if isinstance(overrides.get("pretrained"), str):
        model.load(overrides["pretrained"])

    # Task Update
    if task != model.task:
        if task:
            LOGGER.warning(
                f"WARNING โš ๏ธ conflicting 'task={task}' passed with 'task={model.task}' model. "
                f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model."
            )
        task = model.task

    # Mode
    if mode in {"predict", "track"} and "source" not in overrides:
        overrides["source"] = DEFAULT_CFG.source or ASSETS
        LOGGER.warning(f"WARNING โš ๏ธ 'source' argument is missing. Using default 'source={overrides['source']}'.")
    elif mode in {"train", "val"}:
        if "data" not in overrides and "resume" not in overrides:
            overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)
            LOGGER.warning(f"WARNING โš ๏ธ 'data' argument is missing. Using default 'data={overrides['data']}'.")
    elif mode == "export":
        if "format" not in overrides:
            overrides["format"] = DEFAULT_CFG.format or "torchscript"
            LOGGER.warning(f"WARNING โš ๏ธ 'format' argument is missing. Using default 'format={overrides['format']}'.")

    # Run command in python
    getattr(model, mode)(**overrides)  # default args from model

    # Show help
    LOGGER.info(f"๐Ÿ’ก Learn more at https://docs.ultralytics.com/modes/{mode}")



ultralytics.cfg.copy_default_cfg()

๊ธฐ๋ณธ ์„ค์ • ํŒŒ์ผ์„ ๋ณต์‚ฌํ•˜์—ฌ ์ด๋ฆ„์— '_copy'๋ฅผ ์ถ”๊ฐ€ํ•œ ์ƒˆ ๊ธฐ๋ณธ ์„ค์ • ํŒŒ์ผ์„ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/cfg/__init__.py
def copy_default_cfg():
    """Copy and create a new default configuration file with '_copy' appended to its name."""
    new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")
    shutil.copy2(DEFAULT_CFG_PATH, new_file)
    LOGGER.info(
        f"{DEFAULT_CFG_PATH} copied to {new_file}\n"
        f"Example YOLO command with this new custom cfg:\n    yolo cfg='{new_file}' imgsz=320 batch=8"
    )





์ƒ์„ฑ 2023-11-12, ์—…๋ฐ์ดํŠธ 2024-05-08
์ž‘์„ฑ์ž: Burhan-Q (1), ๊ธ€๋ Œ-์กฐ์ฒ˜ (4), ์•„์œ ์‹œ์—‘์…€ (1), ์›ƒ๋Š”-ํ (1)