o
    Vh                     @   s@  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	m
Z
mZ d dlZd dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# ddd	d
ddddddddddZ$e%h dZ&e%h dZ'ddddddZ(ddddd dZ)d!d"d#d$d!dZ*e%d%d& e'D Z+ej,pd'd'gZ-d(e.d)ge-d*d   d+e/e$0 dd,  d-Z1d(e.d)ge-d*d   d.e' d/e& d0e/e$0 d*d,  d1	Z2e%h d2Z3e%h d3Z4e%h d4Z5e%h d5Z6d6ee.ee	ef d7e	fd8d9Z7edfd6ee.ee	ef d:e	d7efd;d<Z8dbd6e	d>e9d7dfd?d@Z:dcdAedBe.d7efdCdDZ;dEe	d7e	fdFdGZ<dcdHe	dEe	dIe=d7dfdJdKZ>dAe
e. d7e
e. fdLdMZ?dAe
e. d7dfdNdOZ@dAe
e. d7dfdPdQZAdAe
e. d7dfdRdSZBdddUe.d7eCfdVdWZDdXe.d7efdYdZZEded[e.d7dfd\d]ZFdfd^d_ZGeHd`kreFd'da dS dS )g    N)Path)SimpleNamespace)AnyDictListUnion)__version__)ASSETSDEFAULT_CFGDEFAULT_CFG_DICTDEFAULT_CFG_PATHDEFAULT_SOL_DICT	IS_VSCODELOGGERRANKROOTRUNS_DIRSETTINGSSETTINGS_FILETESTS_RUNNINGIterableSimpleNamespacecheckscolorstrdeprecation_warn
vscode_msg	yaml_load
yaml_printObjectCounterObjectCropperObjectBlurrerAIGymHeatmapInstanceSegmentation	VisionEyeSpeedEstimatorQueueManager	Analytics	Inference	TrackZone)countcropblurworkoutheatmapisegment	visioneyespeedqueue	analytics	inference	trackzonehelp>   valtracktrainexportpredict	benchmark>   obbposedetectsegmentclassifyz
coco8.yamlzcoco8-seg.yaml
imagenet10zcoco8-pose.yamlz
dota8.yaml)r>   r?   r@   r=   r<   
yolo11n.ptzyolo11n-seg.ptzyolo11n-cls.ptzyolo11n-pose.ptzyolo11n-obb.ptzmetrics/mAP50-95(B)zmetrics/mAP50-95(M)zmetrics/accuracy_top1zmetrics/mAP50-95(P)c                 C   s   h | ]}t | qS  )
TASK2MODEL).0taskrC   rC   L/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/cfg/__init__.py	<setcomp>M   s    rH    z
    Arguments received: yolo   z. Ultralytics 'yolo solutions' usage overview:

        yolo solutions SOLUTION ARGS

        Where SOLUTION (optional) is one of a.  
              ARGS (optional) are any number of custom 'arg=value' pairs like 'show_in=True' that override defaults 
                  at https://docs.ultralytics.com/usage/cfg
                
    1. Call object counting solution
        yolo solutions count source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"

    2. Call heatmaps solution
        yolo solutions heatmap colormap=cv2.COLORMAP_PARULA model=yolo11n.pt

    3. Call queue management solution
        yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" model=yolo11n.pt

    4. Call workouts monitoring solution for push-ups
        yolo solutions workout model=yolo11n-pose.pt kpts=[6, 8, 10]

    5. Generate analytical graphs
        yolo solutions analytics analytics_type="pie"
    
    6. Track objects within specific zones
        yolo solutions trackzone source="path/to/video.mp4" region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]"
        
    7. Streamlit real-time webcam inference GUI
        yolo streamlit-predict
    z. Ultralytics 'yolo' commands use the following syntax:

        yolo TASK MODE ARGS

        Where   TASK (optional) is one of z+
                MODE (required) is one of a  
                ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
                    See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'

    1. Train a detection model for 10 epochs with an initial learning_rate of 0.01
        yolo train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01

    2. Predict a YouTube video using a pretrained segmentation model at image size 320:
        yolo predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320

    3. Val a pretrained detection model at batch-size 1 and image size 640:
        yolo val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640

    4. Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
        yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128

    5. Ultralytics solutions usage
        yolo solutions count or in a   source="path/to/video.mp4"

    6. Run special commands:
        yolo help
        yolo checks
        yolo version
        yolo settings
        yolo copy-cfg
        yolo cfg
        yolo solutions help

    Docs: https://docs.ultralytics.com
    Solutions: https://docs.ultralytics.com/solutions/
    Community: https://community.ultralytics.com
    GitHub: https://github.com/ultralytics/ultralytics
    >	   boxclsdfltimebatchsheardegrees	workspacewarmup_epochs>   bgrioulr0lrfconfhsv_hhsv_shsv_vmixupscalefliplrflipudmosaicdropoutfractionmomentum	translate
copy_pasteperspectiveweight_decaywarmup_bias_lrwarmup_momentum>   nbsseedepochsmax_detworkerspatience
line_width
mask_ratio
vid_stridesave_periodclose_mosaic>!   dnnnmsr6   halfint8rectsaveshowkerasplotscos_lraugmentdynamicprofileverboseexist_okoptimizesave_txtsimplify	save_conf	save_crop	save_json	show_conf	visualize
show_boxes
single_clsmulti_scalesave_framesshow_labelsagnostic_nmsoverlap_maskretina_masksdeterministiccfgreturnc                 C   s0   t | ttfrt| } | S t | trt| } | S )a  
    Converts a configuration object to a dictionary.

    Args:
        cfg (str | Path | Dict | SimpleNamespace): Configuration object to be converted. Can be a file path,
            a string, a dictionary, or a SimpleNamespace object.

    Returns:
        (dict): Configuration object in dictionary format.

    Examples:
        Convert a YAML file path to a dictionary:
        >>> config_dict = cfg2dict("config.yaml")

        Convert a SimpleNamespace to a dictionary:
        >>> from types import SimpleNamespace
        >>> config_sn = SimpleNamespace(param1="value1", param2="value2")
        >>> config_dict = cfg2dict(config_sn)

        Pass through an already existing dictionary:
        >>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})

    Notes:
        - If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
        - If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
        - If cfg is already a dictionary, it's returned unchanged.
    )
isinstancestrr   r   r   varsr   rC   rC   rG   cfg2dict   s   
r   	overridesc                 C   s   t | } |rt |}d| vr|dd t| | i | |} dD ]}|| v r8t| | ttfr8t| | | |< q!| ddkrZt| dddd | d< t	
d	| d  d
 t|  tdi | S )a@  
    Load and merge configuration data from a file or dictionary, with optional overrides.

    Args:
        cfg (str | Path | Dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or
            SimpleNamespace object.
        overrides (Dict | None): Dictionary containing key-value pairs to override the base configuration.

    Returns:
        (SimpleNamespace): Namespace containing the merged configuration arguments.

    Examples:
        >>> from ultralytics.cfg import get_cfg
        >>> config = get_cfg()  # Load default configuration
        >>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})

    Notes:
        - If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
        - Special handling ensures alignment and correctness of the configuration, such as converting numeric
          `project` and `name` to strings and validating configuration keys and values.
        - The function performs type and value checks on the configuration data.
    save_dirN)projectnamer   modelrI   .r   z,'name=model' automatically updated to 'name='.rC   )r   popcheck_dict_alignmentr   intfloatr   getsplitr   warning	check_cfgr   )r   r   krC   rC   rG   get_cfg  s    
r   Thardc                 C   s  |   D ]\}}|dur|tv r:t|ttfs:|r3td| d| dt|j d| d| d| dt|| |< q|tv rt|ttfsi|ratd| d| dt|j d| d| d| dt| | |< }d	|  krsd
ksn t	d| d| d| dq|t
v rt|ts|rtd| d| dt|j d| d| dt|| |< q|tv rt|ts|rtd| d| dt|j d| d| d| dt|| |< qdS )a  
    Checks configuration argument types and values for the Ultralytics library.

    This function validates the types and values of configuration arguments, ensuring correctness and converting
    them if necessary. It checks for specific key types defined in global variables such as `CFG_FLOAT_KEYS`,
    `CFG_FRACTION_KEYS`, `CFG_INT_KEYS`, and `CFG_BOOL_KEYS`.

    Args:
        cfg (dict): Configuration dictionary to validate.
        hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them.

    Examples:
        >>> config = {
        ...     "epochs": 50,  # valid integer
        ...     "lr0": 0.01,  # valid float
        ...     "momentum": 1.2,  # invalid float (out of 0.0-1.0 range)
        ...     "save": "true",  # invalid bool
        ... }
        >>> check_cfg(config, hard=False)
        >>> print(config)
        {'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False}  # corrected 'save' key

    Notes:
        - The function modifies the input dictionary in-place.
        - None values are ignored as they may be from optional arguments.
        - Fraction keys are checked to be within the range [0.0, 1.0].
    N'=z' is of invalid type z	. Valid 'z' types are int (i.e. 'z=0') or float (i.e. 'z=0.5')g        g      ?z' is an invalid value. Valid 'z!' values are between 0.0 and 1.0.z. 'z' must be an int (i.e. 'z=8')z' must be a bool (i.e. 'z=True' or 'z=False'))itemsCFG_FLOAT_KEYSr   r   r   	TypeErrortype__name__CFG_FRACTION_KEYS
ValueErrorCFG_INT_KEYSCFG_BOOL_KEYSbool)r   r   r   vrC   rC   rG   r   G  sd   (r   argsr   c                 C   s   t | ddr| j}t|S ddlm} | jp!trtjd nt| j	 }|p*| j
p*| j }|t|| tdv r8| jndd}t|S )	a  
    Returns the directory path for saving outputs, derived from arguments or default settings.

    Args:
        args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task',
            'mode', and 'save_dir'.
        name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name'
            or the 'args.mode'.

    Returns:
        (Path): Directory path where outputs should be saved.

    Examples:
        >>> from types import SimpleNamespace
        >>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
        >>> save_dir = get_save_dir(args)
        >>> print(save_dir)
        my_project/detect/train
    r   Nr   )increment_pathztests/tmp/runs>   r   rL   T)r   )getattrr   ultralytics.utils.filesr   r   r   r   parentr   rF   r   moder   r   r   )r   r   r   r   r   rC   rC   rG   get_save_dir  s   "r   customc                 C   s   ddd fddd fddd fdd	d fd
}h d}|  D ]\}\}}|| vr*qt|| || || |< q|D ]}|| vrBq;t| | | q;| S )a  
    Handles deprecated configuration keys by mapping them to current equivalents with deprecation warnings.

    Args:
        custom (dict): Configuration dictionary potentially containing deprecated keys.

    Examples:
        >>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
        >>> _handle_deprecation(custom_config)
        >>> print(custom_config)
        {'show_boxes': True, 'show_labels': True, 'line_width': 2}

    Notes:
        This function modifies the input dictionary in-place, replacing deprecated keys with their current
        equivalents. It also handles value conversions where necessary, such as inverting boolean values for
        'hide_labels' and 'hide_conf'.
    r   c                 S      | S NrC   r   rC   rC   rG   <lambda>      z%_handle_deprecation.<locals>.<lambda>r   c                 S   
   t |  S r   r   r   rC   rC   rG   r        
 r   c                 S   r   r   r   r   rC   rC   rG   r     r   rr   c                 S   r   r   rC   r   rC   rC   rG   r     r   )boxeshide_labels	hide_confline_thickness>   save_hybridcrop_fractionlabel_smoothing)r   r   r   )r   deprecated_mappingsremoved_keysold_keynew_key	transformkeyrC   rC   rG   _handle_deprecation  s"   




r   baseec           
         s   t |}dd  |fD \}fdd|D  }rUddlm} d}|D ])}||} fdd|D }|r<d	| d
nd}	|dtdd| d|	 d7 }q$t|t |dS )av  
    Checks alignment between custom and base configuration dictionaries, handling deprecated keys and providing error
    messages for mismatched keys.

    Args:
        base (dict): The base configuration dictionary containing valid keys.
        custom (dict): The custom configuration dictionary to be checked for alignment.
        e (Exception | None): Optional error instance passed by the calling function.

    Raises:
        SystemExit: If mismatched keys are found between the custom and base dictionaries.

    Examples:
        >>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
        >>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
        >>> try:
        ...     check_dict_alignment(base_cfg, custom_cfg)
        ... except SystemExit:
        ...     print("Mismatched keys found")

    Notes:
        - Suggests corrections for mismatched keys based on similarity to valid keys.
        - Automatically replaces deprecated keys in the custom configuration with updated equivalents.
        - Prints detailed error messages for each mismatched key to help users correct their configurations.
    c                 s   s    | ]	}t | V  qd S r   )	frozensetkeysrE   xrC   rC   rG   	<genexpr>  s    z'check_dict_alignment.<locals>.<genexpr>c                    s   g | ]}| vr|qS rC   rC   rE   r   )	base_keysrC   rG   
<listcomp>  s    z(check_dict_alignment.<locals>.<listcomp>r   )get_close_matchesrI   c                    s0   g | ]}  |d ur| d |  n|qS )Nr   )r   r   )r   rC   rG   r     s   0 zSimilar arguments are i.e. r   r   redboldz ' is not a valid YOLO argument. 
N)r   difflibr   r   SyntaxErrorCLI_HELP_MSG)
r   r   r   custom_keys
mismatchedr   stringr   matches	match_strrC   )r   r   rG   r     s   
 r   c                 C   sJ  g }d}d}d}|t | k r| | }|dkr:d|  k r$t | d k r:n n|d  d| |d   7  < |d7 }q|dra|t | d k rad| |d  vra|| | |d    |d7 }q|drw|dkrw|d  |7  < |d7 }q||d|d 7 }||7 }|dkr|| d}|d7 }|t | k s|r|| |S )	a{  
    Merges arguments around isolated '=' in a list of strings and joins fragments with brackets.

    This function handles the following cases:
        1. ['arg', '=', 'val'] becomes ['arg=val']
        2. ['arg=', 'val'] becomes ['arg=val']
        3. ['arg', '=val'] becomes ['arg=val']
        4. Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]']

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

    Returns:
        (List[str]): A list of strings where the arguments around isolated '=' are merged and fragments with brackets are joined.

    Examples:
        >>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"]
        >>> merge_equals_args(args)
        ['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]']
    rI   r   r   rK   rL      [])lenendswithappend
startswithr)   )r   new_argscurrentdepthiargrC   rC   rG   merge_equals_args  s8   (*

r   c                 C   sZ   ddl m} | d dkrt| dkr| d nd}|| dS | d dkr+|  dS dS )a5  
    Handles Ultralytics HUB command-line interface (CLI) commands for authentication.

    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. The first argument should be either 'login'
            or 'logout'. For 'login', an optional second argument can be the API key.

    Examples:
        $ yolo login YOUR_API_KEY

    Notes:
        - The function imports the 'hub' module from ultralytics to perform login and logout operations.
        - For the 'login' command, if no API key is provided, an empty string is passed to the login function.
        - The 'logout' command does not require any additional arguments.
    r   )hubloginrK   rI   logoutN)ultralyticsr   r   r   r   )r   r   r   rC   rC   rG   handle_yolo_hub1  s   r  c              
   C   s   d}z;t | r.| d dkrt  t  td ntdd | D }tt| t	| tt td|  W dS  t
y\ } ztd| d	| d
 W Y d}~dS d}~ww )a{  
    Handles YOLO settings command-line interface (CLI) commands.

    This function processes YOLO settings CLI commands such as reset and updating individual settings. 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.

    Examples:
        >>> handle_yolo_settings(["reset"])  # Reset YOLO settings
        >>> handle_yolo_settings(["default_cfg_path=yolo11n.yaml"])  # Update a specific setting

    Notes:
        - If no arguments are provided, the function will display the current settings.
        - The 'reset' command will delete the existing settings file and create new default settings.
        - Other arguments are treated as key-value pairs to update specific settings.
        - The function will check for alignment between the provided settings and the existing ones.
        - After processing, the updated settings will be displayed.
        - For more information on handling YOLO settings, visit:
          https://docs.ultralytics.com/quickstart/#ultralytics-settings
    z=https://docs.ultralytics.com/quickstart/#ultralytics-settingsr   resetzSettings reset successfullyc                 s   s    | ]}t |V  qd S r   )parse_key_value_pair)rE   arC   rC   rG   r   n  s    z'handle_yolo_settings.<locals>.<genexpr>u.   💡 Learn more about Ultralytics Settings at zsettings error: 'z'. Please see z
 for help.N)anyr   unlinkr   r  r   infodictr   update	Exceptionr   )r   urlnewr   rC   rC   rG   handle_yolo_settingsO  s    


&r  c                    s  i t tdddd}i }t| D ]I}|dd}d|v rKzt|\}}|||< W q tttt	fyJ } zt
||di| W Y d	}~qd	}~ww ||v r[t||tr[d
||< qt
|| | sktd dg} | d dkrxtt d	S | d tv r| d}ntd| d  ddtt d	d  d d}|dkrtd td tddttd dd|ddg d	S ddlm} t|t| d0dd
i|}	t !|	j"d   |d!kr  fd"d#t j#t j$t j%fD \}
}}|d$krd%\}
}t&t'd&d'd(d)}|j(d
d* t )t|| d+ t j*d, ||
|f}z\d} + rh , \}}|s2n=|d$kr@|	||d-  }n|	|}|d!krO|-|j. t /d-d.@ t0d/kr\n + s(W  1  d	S W  1  d	S W  1  d	S W  1  d	S  1  w )1a  
    Processes YOLO solutions arguments and runs the specified computer vision solutions pipeline.

    Args:
        args (List[str]): Command-line arguments for configuring and running the Ultralytics YOLO
            solutions: https://docs.ultralytics.com/solutions/, It can include solution name, source,
            and other configuration parameters.

    Examples:
        Run people counting solution with default settings:
        >>> handle_yolo_solutions(["count"])

        Run analytics with custom configuration:
        >>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"])

        Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
        >>> handle_yolo_solutions(["inference", "model=yolo11n.pt"])

    Notes:
        - Default configurations are merged from DEFAULT_SOL_DICT and DEFAULT_CFG_DICT
        - Arguments can be provided in the format 'key=value' or as boolean flags
        - Available solutions are defined in SOLUTION_MAP with their respective classes and methods
        - If an invalid solution is provided, defaults to 'count' solution
        - Output videos are saved in 'runs/solution/{solution_name}' directory
        - For 'analytics' solution, frame numbers are tracked for generating analytical graphs
        - Video processing can be interrupted by pressing 'q'
        - Processes video frames sequentially and saves output in .avi format
        - If no source is specified, downloads and uses a default sample video
        - The inference solution will be launched using the 'streamlit run' command.
        - The Streamlit app file is located in the Ultralytics package directory.
    g      ?)   r  zcropped-detections)
blur_ratiovision_pointcrop_dir-,r   rI   NTzMNo solution name provided. i.e `yolo solutions count`. Defaulting to 'count'.r)   r   r5   u   ❌ 'uQ   ' is not a valid solution. 💡 Defaulting to 'count'.
🚀 Available solutions: z, rL   r   r3   zstreamlit>=1.29.0,<1.44.0u.   💡 Loading Ultralytics live inference app...	streamlitrunz solutions/streamlit_inference.pyz--server.headlesstruer   rB   )	solutionsis_clisourcer*   c                 3   s    | ]
}t  |V  qd S r   )r   r   r   caprC   rG   r     s    
z(handle_yolo_solutions.<locals>.<genexpr>r2   )i   i  zruns/solutionsexpF)r   r   r   )parentsz.avimp4vrK      qrC   )2r   r   r   lstriprstripr  	NameErrorr   r   AssertionErrorr   r   r   r   r   r   r  SOLUTIONS_HELP_MSGSOLUTION_MAPr   joinlistr   r   check_requirements
subprocessr  r   r   r  r  r   cv2VideoCaptureCFGCAP_PROP_FRAME_WIDTHCAP_PROP_FRAME_HEIGHTCAP_PROP_FPSr   r   mkdirVideoWriterVideoWriter_fourccisOpenedreadwriteplot_imwaitKeyordrelease)r   full_args_dictr   r   r   r   r   solution_namer  solutionwhfpsr   vwf_nsuccessframeresultsrC   r  rG   handle_yolo_solutionsx  s    








(
$


rG  	key=valuepairc                 C   sB   |  dd\}}| | }}|sJ d| d|t|fS )aw  
    Parses a key-value pair string into separate key and value components.

    Args:
        pair (str): A string containing a key-value pair in the format "key=value".

    Returns:
        key (str): The parsed key.
        value (str): The parsed value.

    Raises:
        AssertionError: If the value is missing or empty.

    Examples:
        >>> key, value = parse_key_value_pair("model=yolo11n.pt")
        >>> print(f"Key: {key}, Value: {value}")
        Key: model, Value: yolo11n.pt

        >>> key, value = parse_key_value_pair("epochs=100")
        >>> print(f"Key: {key}, Value: {value}")
        Key: epochs, Value: 100

    Notes:
        - The function splits the input string on the first '=' character.
        - Leading and trailing whitespace is removed from both key and value.
        - An assertion error is raised if the value is empty after stripping.
    r   rK   z	missing 'z' value)r   stripsmart_value)rI  r   r   rC   rC   rG   r    s   r  r   c                 C   sN   |   }|dkr
dS |dkrdS |dkrdS zt| W S  ty&   |  Y S w )a3  
    Converts a string representation of a value to its appropriate Python type.

    This function attempts to convert a given string into a Python object of the most appropriate type. It handles
    conversions to None, bool, int, float, and other types that can be evaluated safely.

    Args:
        v (str): The string representation of the value to be converted.

    Returns:
        (Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion
            is applicable.

    Examples:
        >>> smart_value("42")
        42
        >>> smart_value("3.14")
        3.14
        >>> smart_value("True")
        True
        >>> smart_value("None")
        None
        >>> smart_value("some_string")
        'some_string'

    Notes:
        - The function uses a case-insensitive comparison for boolean and None values.
        - For other types, it attempts to use Python's eval() function, which can be unsafe if used on untrusted input.
        - If no conversion is possible, the original string is returned.
    noneNr  TfalseF)lowerevalr  )r   v_lowerrC   rC   rG   rK    s   
rK  debugc                    s  | r|  dntdd   stt dS dd tjdd  fdddd  fd	d fd
d fddt fddd
}i tdd t	D dd t
D |}|dd | D  |dd | D  i |dd | D dd | D }i }t D ]}|drtd| d|dd  d |dd }|drtd| d|dd  d |dd }d|v rz.t|\}}|dkr|durtdt d|  d d tt| D }n|||< W q ttttfy } zt||d!i| W Y d}~qd}~ww |t	v r||d"< q|t
v r%||d#< q| |v r6||     dS |tv rHtt| trHd$||< q|tv rctd%td&d'| d(| dt|  d)t t||d!i qt|| |d#}|du rtj pd*}td+t
 d,| d n|t
vrtd-| d.t
 d/t |!d"d}	|	r|	t	vr|	d0krtd1 d2\}	}ntd3|	 d4t	 d/t d5|vrt"|	 |d5< |!d5tj#}
|
du rd6}
td7|
 d |
|d5< t$|
j% }d8|v rd9d:l&m'} ||
}
n6d;|v rd9d<l&m(} ||
}
n&d=|v s%d>|v s%d?|v r0d9d@l&m)} ||
}
nd9dAl&m*} ||
|	dB}
t|dCt+rL|
,|dC  |	|
j-krl|	ritdD|	 dE|
j- dF|	 dG|
j- dH	 |
j-}	|dIv rdJ|vr|	dKkr}dLntj.pt/|dJ< tdM|dJ  d nI|dNv rdO|vrdP|vrtj0pt1|	ptj-tj0|dO< tdQ|dO  d n|dRkrdS|vrtj2pdT|dS< tdU|dS  d t3|
|dXi | tdV|  t4rt5dWd$r tt6  dS dS dS )Ya  
    Ultralytics entrypoint function for parsing and executing command-line arguments.

    This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and
    executing the corresponding tasks such as training, validation, prediction, exporting models, and more.

    Args:
        debug (str): Space-separated string of command-line arguments for debugging purposes.

    Examples:
        Train a detection model for 10 epochs with an initial learning_rate of 0.01:
        >>> entrypoint("train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01")

        Predict a YouTube video using a pretrained segmentation model at image size 320:
        >>> entrypoint("predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")

        Validate a pretrained detection model at batch-size 1 and image size 640:
        >>> entrypoint("val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640")

    Notes:
        - If no arguments are passed, the function will display the usage help message.
        - For a list of all available commands and their arguments, see the provided help messages and the
          Ultralytics documentation at https://docs.ultralytics.com.
     rK   Nc                   S   
   t tS r   )r   r  r   rC   rC   rC   rG   r   Y  r   zentrypoint.<locals>.<lambda>c                   S   rS  r   )r   r  r   rC   rC   rC   rG   r   [  r   c                         t  dd  S NrK   )r  rC   r   rC   rG   r   \      c                   S   s   t tS r   )r   r   rC   rC   rC   rG   r   ]      c                      rT  rU  r  rC   rV  rC   rG   r   ^  rW  c                         t  S r   rY  rC   rV  rC   rG   r   _  rX  c                      rZ  r   rY  rC   rV  rC   rG   r   `  rX  c                      rT  rU  )rG  rC   rV  rC   rG   r   b  rW  )
r5   r   versionsettingsr   r   r   r   zcopy-cfgr  c                 S   s   i | ]}|d qS r   rC   r   rC   rC   rG   
<dictcomp>d  s    zentrypoint.<locals>.<dictcomp>c                 S   s   i | ]	\}}|d  |qS )r   rC   rE   r   r   rC   rC   rG   r]  g  s    c                 S   s4   i | ]\}}t |d kr|dr|dd |qS )rK   sNrL   )r   r   r^  rC   rC   rG   r]  h  s   4 c                 S      i | ]
\}}d | |qS )r  rC   r^  rC   rC   rG   r]  i      c                 S   r`  )--rC   r^  rC   rC   rG   r]  i  ra  rb  z
argument 'z5' does not require leading dashes '--', updating to 'r   r   r  z4' does not require trailing comma ',', updating to 'rL   r   r   zOverriding z with c                 S   s   i | ]\}}|d kr||qS r   rC   )rE   r   r6   rC   rC   rG   r]  x  s    rI   rF   r   Tr   r   r   zR' is a valid YOLO argument but is missing an '=' sign to set its value, i.e. try 'z'
r:   z,'mode' argument is missing. Valid modes are z. Using default 'mode=zInvalid 'mode=z'. Valid modes are z.
r7   zfinvalid 'task=track', setting 'task=detect' and 'mode=track'. Valid tasks are {TASKS}.
{CLI_HELP_MSG}.)r>   r7   zInvalid 'task=z'. Valid tasks are r   rB   z2'model' argument is missing. Using default 'model=rtdetrr   )RTDETRfastsam)FastSAMsam_sam2_zsam2.1_)SAM)YOLO)rF   
pretrainedzconflicting 'task=z' passed with 'task=z' model. Ignoring 'task=z' and updating to 'task=z' to match model.>   r7   r:   r  r<   z(https://ultralytics.com/images/boats.jpgz4'source' argument is missing. Using default 'source=>   r6   r8   dataresumez0'data' argument is missing. Using default 'data=r9   formattorchscriptz4'format' argument is missing. Using default 'format=u6   💡 Learn more at https://docs.ultralytics.com/modes/r   rC   )7r   ARGVr   r  r   r   collect_system_infocopy_default_cfgr   TASKSMODESr
  r   r   r   r   r   r  r   r   
check_yamlr$  r   r   r%  r   rN  r   r   r   r   r
   r   r   rD   r   r   stemr  rd  rf  ri  rj  r   loadrF   r  r	   rl  	TASK2DATArn  r   r   r   r   )rQ  specialr<  r   r  r   r   r   r   rF   r   rv  rd  rf  ri  rj  rC   rV  rG   
entrypoint:  s   





(,
 
 





















"

rz  c                  C   sB   t  tjdd } tt|  tt d|  d|  d dS )a#  
    Copies the default configuration file and creates a new one with '_copy' appended to its name.

    This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it
    with '_copy' appended to its name in the current working directory. It provides a convenient way
    to create a custom configuration file based on the default settings.

    Examples:
        >>> copy_default_cfg()
        # Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
        # Example YOLO command with this new custom cfg:
        #   yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8

    Notes:
        - The new configuration file is created in the current working directory.
        - After copying, the function prints a message with the new file's location and an example
          YOLO command demonstrating how to use the new configuration file.
        - This function is useful for users who want to modify the default configuration without
          altering the original file.
    z.yamlz
_copy.yamlz copied to z>
Example YOLO command with this new custom cfg:
    yolo cfg='z' imgsz=320 batch=8N)	r   cwdr   r   replaceshutilcopy2r   r  )new_filerC   rC   rG   rr    s   rr  __main__)rQ  )Tr   )rH  )rI   )r   N)Ir}  r+  syspathlibr   typesr   typingr   r   r   r   r,  r  r   ultralytics.utilsr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r'  r   rt  rs  rx  rD   TASK2METRICMODELSargvrp  r   r)  r   r&  r   r   r   r   r   r   r   r   r   r   r   r  r   r   r  r  rG  tupler  rK  rz  rr  r   rC   rC   rC   rG   <module>   s   X)'(#0> )(;)s"- 
-
