
    /jm                    d   d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
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 d dlZd dlZd dl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,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 e)j6        dz  dfd	Z7dXdZ8ej9        dYdZd            Z:d[dZ;d\dZ<ej9        d             Z=ej9        	 	 	 	 	 	 d]d^d             Z>d_d"Z?d# Z@ e/            ej9        d`d%                        ZAdadbd)ZB e0            d*             ZC e0            e)j6        dz  d+d'dfd,            ZDd- ZEdcddd0ZFd1 ZGded4ZHdfdgd6ZIdhdid:ZJdjd<ZKdkd>ZLdldBZMej9        dmdC            ZNdndDZOdE ZPdF ZQdG ZRdodpdJZSdqdLZTd[dMZUdN ZVdO ZWd[dPZX eBdQdd'R            eG              e'jY        dQ          ZZ e'jY        dS          Z[ e'jY        dT          Z\ e'jY        dU          Z] e'jY        dV          Z^ eBdSdW          Z_ eBdTdW          Z` eBdUdW          ZadS )r    )annotationsN)metadata)Path)SimpleNamespace)ARM64ASSETS
ASSETS_URLAUTOINSTALLGITIS_COLAB	IS_DOCKER	IS_JETSON	IS_KAGGLEIS_PIP_PACKAGELINUXLOGGERMACOSONLINEPYTHON_VERSION
RKNN_CHIPSROOTTORCH_VERSIONTORCHVISION_VERSIONUSER_CONFIG_DIRWINDOWSRetryThreadingLocked	TryExcept	clean_urlcolorstr	downloadsis_github_action_runningurl2filezrequirements.txt c                <   |r$d t          j        |          j        D             }n3t          |                                                                           }g }|D ]}|                                }|r|                    d          s|                    d          d                                         }t          j
        d|          x}rL|                    t          |d         |d         r|d                                         nd                     |S )	a/  Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'.

    Args:
        file_path (Path): Path to the requirements.txt file.
        package (str, optional): Python package to use instead of requirements.txt file.

    Returns:
        requirements (list[SimpleNamespace]): List of parsed requirements as SimpleNamespace objects with `name` and
            `specifier` attributes.

    Examples:
        >>> from ultralytics.utils.checks import parse_requirements
        >>> parse_requirements(package="ultralytics")
    c                    g | ]}d |v|	S )z	extra ==  .0xs     ]/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/checks.py
<listcomp>z&parse_requirements.<locals>.<listcomp>J   s#    ___!+]^J^J^AJ^J^J^    #r   z ([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?      r$   name	specifier)r   distributionrequiresr   	read_text
splitlinesstrip
startswith	partitionrematchappendr   )	file_pathpackager5   requirementsliner<   s         r+   parse_requirementsrB   :   s     <__x4W==F___	??,,..99;;L t tzz|| 	t,, 	t>>#&&q)//11D!DdKKKu t##OqafghaiMqUSTX^^M]M]M]oq$r$r$rsssr-   import_namestrreturnc                    t          j                    D ]>}|                    d          pd                                }| |v r|j         d         c S ?| S )z`Get the pip distribution name for a given import name (e.g., 'cv2' -> 'opencv-python-headless').ztop_level.txtr$   Name)r   distributionsr6   split)rC   dist	top_levels      r+   get_distribution_namerL   Y   se    &(( ) )^^O44:AACC	)##=(((( $r-   0.0.0tuplec           	         	 t          t          t          t          j        d|           dd                             S # t
          $ r%}t          j        d|  d|            Y d}~dS d}~ww xY w)a%  Convert a version string to a tuple of integers, ignoring any extra non-numeric string attached to the version.

    Args:
        version (str): Version string, i.e. '2.0.1+cpu'

    Returns:
        (tuple): Tuple of integers representing the numeric part of the version, i.e. (2, 0, 1)
    z\d+N   zfailure for parse_version(z), returning (0, 0, 0): )r   r   r   )rN   mapintr;   findall	Exceptionr   warning)versiones     r+   parse_versionrX   b   s    Sbj99"1"=>>???   XGXXUVXXYYYwwwwws   <? 
A.	A))A.boolc                N    t          d t          |           D                       S )a  Check if a string is composed of only ASCII characters.

    Args:
        s (str | list | tuple | dict): Input to be checked (all are converted to string for checking).

    Returns:
        (bool): True if the string is composed only of ASCII characters, False otherwise.
    c              3  <   K   | ]}t          |          d k     V  dS )   N)ord)r)   cs     r+   	<genexpr>zis_ascii.<locals>.<genexpr>|   s,      ,,s1vv|,,,,,,r-   )allrD   )ss    r+   is_asciirb   s   s'     ,,SVV,,,,,,r-       r/   r0   c                   t          t          t          j                  r                                n          t          | t                     r| g} nt          | t
          t          f          rt          |           } nvt          | t                    r9|                                 rt          |           gnt          j
        |           } n(t          d|  dt          |           j         d          t          |           |k    rTd}|dk    rt          d|  d|           t!          j        dt	          |            d	|            t	          |           g} fd
| D             }|| k    rt!          j        d|  d d|            |dk    r#t          |          dk    r|d         |d         gn"|dk    rt          |          dk    r|d         n|}|S )a(  Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the
    stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.

    Args:
        imgsz (int | list[int]): Image size.
        stride (int): Stride value.
        min_dim (int): Minimum number of dimensions.
        max_dim (int): Maximum number of dimensions.
        floor (int): Minimum allowed value for image size.

    Returns:
        (list[int] | int): Updated image size.
    z'imgsz=z' is of invalid type zK. Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'z'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'r/   zimgsz=z is not a valid image size. zupdating to 'imgsz=z'. c                `    g | ]*}t          t          j        |z            z            +S r'   )maxmathceil)r)   r*   floorstrides     r+   r,   zcheck_imgsz.<locals>.<listcomp>   s6    	D	D	D#diF
##f,e
4
4	D	D	Dr-   z  must be multiple of max stride z, updating to r0   r   )rR   
isinstancetorchTensorrf   listrN   rD   	isnumericastliteral_eval	TypeErrortype__name__len
ValueErrorr   rU   )imgszrj   min_dimmax_dimri   msgszs    `  `  r+   check_imgszr|      s    FEL!A!AMvNNF % 

	ED%=	)	) 
U	E3		 
 % 1 1NUs7G7N7NYe Y Y$u++2F Y Y Y
 
 	
 5zzGY 	 a<<NeNNNNOOOASZZAACAABBBU	D	D	D	D	De	D	D	DB 
U{{aaavaa]_aabbb #a<<CGGqLL"Q%AwRS||X[\^X_X_cdXdXdbeejlBIr-   c                 h    	 t          j        ddgd          j        dk    S # t          $ r Y dS w xY w)zBCheck if uv package manager is installed and can run successfully.uvz-VT)capture_outputr   F)
subprocessrun
returncodeFileNotFoundErrorr'   r-   r+   check_uvr      sJ    ~tTl4@@@KqPP   uus    # 
11rV   Fcurrentrequiredr2   hardverboserz   c                   | st          j        d|  d| d           dS | d                                         sJ	 | }t          j        |           } n2# t          j        $ r }|rt          |  d          |Y d}~dS d}~ww xY w|sdS d	|v r't          rd
|vst          rd|vst          r
d|vrd|vrdS d}d}d}	t          |           }
|                    d                              d          D ]}t          j        d|                                          \  }}|sd}t          |          }|dk    r	|
|k    rd}	N|dk    r	|
|k    rd}	]|dk    r	|
|k    sd}	l|dk    r	|
|k    sd}	{|dk    r	|
|k    sd}	|dk    r|
|k     sd}	|	s6| | d| d|  d| }|rt          |          |rt          j        |           |	S )a  Check current version against the required version or range.

    Args:
        current (str): Current version or package name to get version from.
        required (str): Required version or range (in pip-style format).
        name (str): Name to be used in warning message.
        hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met.
        verbose (bool): If True, print warning message if requirement is not met.
        msg (str): Extra message to display if verbose.

    Returns:
        (bool): True if requirement is met, False otherwise.

    Examples:
        Check if current version is exactly 22.04
        >>> check_version(current="22.04", required="==22.04")

        Check if current version is greater than or equal to 22.04
        >>> check_version(current="22.10", required="22.04")  # assumes '>=' inequality if none passed

        Check if current version is less than or equal to 22.04
        >>> check_version(current="22.04", required="<=22.04")

        Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
        >>> check_version(current="21.10", required=">20.04,<22.04")
    zinvalid check_version(, z!) requested, please check values.Tr   z& package is required but not installedNFsys_platformwin32linuxmacosdarwinr$   ,z([^0-9]*)([\d.]+)>=z==z!=z<=><z is required, but z is currently installed )r   rU   isdigitr   rV   PackageNotFoundErrorModuleNotFoundErrorr   r   r   rX   r8   rI   r;   r<   groups)r   r   r2   r   r   rz   rW   oprV   resultr^   rvrU   s                 r+   check_versionr      s   F  fff8fffgggtQZ!! 	D&w//GG, 	 	 	 )W*\*\*\]]cdduuuuu		  t!!	 "H,, -X-- .X--((2J2Jt	BGFgA^^C  &&s++  h3Q77>>@@G 	B'""::!q&&FF4ZZAFFFF4ZZaFF4ZZaFF3YYAFF3YYAF $e8eeteewee`cee 	/%g... 	$N7###Ms   A B!A<<Bultralyticsc                    ddl }	 |j        j                                         |                    d|  dd          }|j        dk    r |                                d         d	         S dS # t          $ r Y dS w xY w)
a  Return the latest version of a PyPI package without downloading or installing it.

    Args:
        package_name (str): The name of the package to find the latest version for.

    Returns:
        (str | None): The latest version of the package, or None if unavailable.
    r   Nzhttps://pypi.org/pypi/z/jsonrP   )timeout   inforV   )requestspackagesurllib3disable_warningsgetstatus_codejsonrT   )package_namer   responses      r+   check_latest_pypi_versionr     s     OOO!22444<< L L L LVW<XX3&&==??6*955 '&   tts   A#A, ,
A:9A:c                     t           rZt          rS	 ddlm}  t	                      }t          | d|           rt          j        d| d           dS n# t          $ r Y nw xY wdS )zCheck if a new version of the ultralytics package is available on PyPI.

    Returns:
        (bool): True if an update is available, False otherwise.
    r   )__version__r   z)New https://pypi.org/project/ultralytics/u8    available 😃 Update with 'pip install -U ultralytics'TF)	r   r   r   r   r   r   r   r   rT   )r   latests     r+   check_pip_update_availabler   )  s      . 	//////.00F[,f,,77 @ @ @ @   t  	 	 	D	5s   ?A 
AA	Arial.ttfc                ^    ddl m} t                     j        }t          |z  }|                                r|S  fd|                                D             }t          |          r|d         S t           d| }t          j
        |d          rt          j        ||           |S dS )	zFind font locally or download to user's configuration directory if it does not already exist.

    Args:
        font (str): Path or name of font.

    Returns:
        (Path | str): Resolved font file path.
    r   )font_managerc                    g | ]}|v |	S r'   r'   )r)   ra   fonts     r+   r,   zcheck_font.<locals>.<listcomp>S  s    FFFQDAIIqIIIr-   /T)check)urlfileN)
matplotlibr   r   r2   r   existsfindSystemFontsanyr	   r!   is_urlsafe_download)r   r   r2   r   matchesr   s   `     r+   
check_fontr   ?  s     (''''' ::?DT!D{{}}  GFFF,6688FFFG
7|| qz 
 
 $
 
 C4((( Cd3333 r-   3.8.0Tminimumc                4    t          t          | d||          S )a  Check current python version against the required minimum version.

    Args:
        minimum (str): Required minimum version of python.
        hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met.
        verbose (bool): If True, print warning message if requirement is not met.

    Returns:
        (bool): Whether the installed Python version meets the minimum constraints.
    Python)r2   r   r   )r   r   )r   r   r   s      r+   check_pythonr   ^  s     xdT[\\\\r-   c                   t          ddd          }g }| D ]	 t          j        ddgddd          }|j        d	k    s2t	          fd
|j                                        D                       s|                               q# t          $ r |                               Y w xY w|rt          j
        | ddt          |          dk    z   d| d           t                      rdgng ddgz   }t          j        |ddd          }t                      rdgng g dz   |z   }t          j        |ddd          }t          j
        | d           t          j        | dt          dd           d           dS dS )zCheck if apt packages are installed and install missing ones.

    Args:
        requirements (list[str]): List of apt package names to check and install.
    redboldzapt requirements:dpkgz-lTF)r   textr   r   c              3  J   K   | ]}|                     d           o|v V  dS )iiN)r9   )r)   rA   r?   s     r+   r_   z)check_apt_requirements.<locals>.<genexpr>{  sI       1 1>B%%9'T/1 1 1 1 1 1r-    Ultralytics requirementra   r/    $ not found, attempting AutoUpdate...sudoaptupdate)r   r   r   )r   installz-yu    AutoUpdate success ✅;Restart runtime or rerun command for updates to take effect
N)r    r   r   r   r   stdoutr7   r=   rT   r   r   ru   is_sudo_availablerU   )r@   prefixmissing_packagesr   cmdr?   s        @r+   check_apt_requirementsr   l  s&    eV%899F - -
	-^VT7$;DW[chiiiF A%%S 1 1 1 1FLmF^F^F`F`1 1 1 . .% !''000 	- 	- 	-##G,,,,,	-
  x  J  Jsc:J6K6Ka6O/P  J  JSc  J  J  J	
 	
 	
 -..6xxB5(:KK44PPP -..6xxB:R:R:RRUee44PPPv666777&vv8F4q#r#rvvvwwwwwx xs   A-BB*)B*r'   c                .   t          ddd          }t          j                            dd          dk    rt	          j        | d           dS t          | t                    rT|                                 }|	                                sJ | d	| d
            fdt          |          D             } nt          | t                    r| g} g }| D ]6}t          |t          t          f          r|n|g}d}	|D ]}
|
                    d          d                             dd          }t!          j        d|          }|d         |d         r|d                                         nd}}	 t'          t)          j        |          |          rd}	 n# t,          t(          j        f$ r Y w xY w|	sV|d         }d|v r5|                    d          \  }}}t!          j        dd|          |z   |z   }|                    |           8t7          dd          d             }d	                    d |D                       }|rL|rGt:          r?t=          |          }t	          j        | dd|dk    z   d	| d           	 t?          j                    }t@          s
J d            tB           otE                      }t	          j         ||||                     t?          j                    |z
  }t	          j        | d |d!d           t	          j#        | d	t          dd"           d#           nY# tH          $ rJ}| d$| }tK          |d%          r|j&        r|d#|j&         z  }t	          j#        |           Y d&}~dS d&}~ww xY wdS dS )'a  Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed.

    Args:
        requirements (Path | str | list[str|tuple] | tuple[str]): Path to a requirements.txt file, a single package
            requirement as a string, a list of package requirements as strings, or a list containing strings and tuples
            of interchangeable packages.
        exclude (tuple): Tuple of package names to exclude from checking.
        install (bool): If True, attempt to auto-update packages that don't meet requirements.
        cmds (str): Additional commands to pass to the pip install command when auto-updating.

    Examples:
        >>> from ultralytics.utils.checks import check_requirements

        Check a requirements.txt file
        >>> check_requirements("path/to/requirements.txt")

        Check a single package
        >>> check_requirements("ultralytics>=8.3.200", cmds="--index-url https://download.pytorch.org/whl/cpu")

        Check multiple packages
        >>> check_requirements(["numpy", "ultralytics"])

        Check with interchangeable packages
        >>> check_requirements([("onnxruntime", "onnxruntime-gpu"), "numpy"])
    r   r   zrequirements:$ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS01zN ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS=1 detected, skipping requirements check.Tr   z not found, check failed.c                B    g | ]}|j         v|j          |j         S r'   r1   )r)   r*   excludes     r+   r,   z&check_requirements.<locals>.<listcomp>  s7    lllQVWV\dkVkVk1601;00VkVkVkr-   Fr   z.gitr$   z([a-zA-Z0-9-_]+)([<>!=~]+.*)?r/   r0   r   zgit+;z[<>!=~]+.*$)timesdelayc           	         |r6t          j        dt          j         d|  d| ddt           j        d          S t          j        d|  d| dt           j        d          S )zGAttempt package installation with uv if available, falling back to pip.z(uv pip install --no-cache-dir --python "z" r   z; --index-strategy=unsafe-best-match --break-system-packagesT)shellstderrr   zpip install --no-cache-dir )r   check_outputsys
executableSTDOUT)r   commandsuse_uvs      r+   attempt_installz+check_requirements.<locals>.attempt_install  s      		 *N3> N NX N NX` N N N!(    &?(??X??tT^Telp
 
 
 	
r-   c              3  "   K   | ]
}d | d V  dS )"Nr'   r(   s     r+   r_   z%check_requirements.<locals>.<genexpr>  s*      ((aQ((((((r-   r   ra   r   zAutoUpdate skipped (offline))r   u    AutoUpdate success ✅ .1fr   r   u    ❌ outputN)'r    osenvironr   r   r   rk   r   resolver   rB   rD   rn   rN   
rpartitionreplacer;   r<   r8   r   r   rV   AssertionErrorr   r:   subr=   r   joinr
   ru   timer   r   r   rU   rT   hasattrr   )r@   r   r   cmdsr   r   pkgsr   
candidates	satisfied	candidate
r_strippedr<   r2   r   pkgr   sepmarkerr   ra   ntr   dtrW   rz   s    `                         r+   check_requirementsr
    s*   6 eV_55F	z~~<cBBcIIvmmmnnnt,%% &##%%{{}}IIII$IIIII}llll:LT:R:Rlll	L#	&	& &$~D  $Qu66?QQQC
	# 		 		I"--c2226>>vrJJJH=zJJE"1X58'KuQx~~'7'7'7(D !1$!7!7BB  $IE #H$AB     	Q-C}}#&==#5#5 S&f^R55;fDKK
!
 
 
  	((4(((((A  	{ 	D		AK6uu3!a%=uu4uuuvvvIKK=====v"1xzzOOAtFCCCDDDY[[1_vHHrHHHHIIIss1n o osss       ))a))1h'' +AH +???*Cs###uuuuu 54s+   0$FF0/F0B3L< <
N?NNc                     t           rt          rt          rt          d           t          ddt	          j        d          d                     t          d           dS )	zSCheck and install ExecuTorch requirements including platform-specific dependencies.zpackaging>=22.0
executorchztorch==+r   )r   znumpy<=2.3.5N)r   r   r   r
  r   rI   r'   r-   r+   check_executorch_requirementsr     si      . .9 .,---|*QM4G4L4LQ4O*Q*QRRRR~&&&&&r-   7.0.0min_versionc                    t           rBt          j        j                            d          d         }t          d| d|  d           dS dS )zCheck and install TensorRT requirements including platform-specific dependencies.

    Args:
        min_version (str): Minimum supported TensorRT version (default: "7.0.0").
    .r   ztensorrt-cur   z	,!=10.1.0N)r   rl   rV   cudarI   r
  )r  cuda_versions     r+   check_tensorrtr    s^      Q})//44Q7OOOOOOPPPPPQ Qr-   c                    dgdgdgdgdgdgdgdgd	gd
gdgdgdgd} d                     t          j        dd          d                             d          dd                   }|| v r| |         }d                     t          j        dd          d                             d          dd                   t	          fd|D                       r(t          j        d d| d|d          d           dS dS dS )a,  Check the installed versions of PyTorch and Torchvision to ensure they're compatible.

    This function checks the installed versions of PyTorch and Torchvision, and warns if they're incompatible according
    to the compatibility table based on: https://github.com/pytorch/vision#installation.
    z0.25z0.24z0.23z0.22z0.21z0.20z0.19z0.18z0.17z0.16z0.15z0.14z0.13)z2.10z2.9z2.8z2.7z2.6z2.5z2.4z2.3z2.2z2.1z2.0z1.13z1.12r  r  r/   r   Nr0   c              3  $   K   | ]
}|k    V  d S )Nr'   )r)   r   v_torchvisions     r+   r_   z$check_torchvision.<locals>.<genexpr>1  s(      ??a}!??????r-   ztorchvision==z is incompatible with torch==z .
Run 'pip install torchvision==z' to fix torchvision or 'pip install -U torch torchvision' to update both.
For a full compatibility table see https://github.com/pytorch/vision#installation)r   r   rI   r   r`   r   rU   )compatibility_tablev_torchcompatible_versionsr  s      @r+   check_torchvisionr    sv    xxxxxxxxxx " hh}*32215;;C@@!DEEG%%%1':!4!:3!B!B1!E!K!KC!P!PQSRSQS!TUU????+>????? 	Nd d dG d d1DQ1Gd d d    	 &%	 	r-   
yolo26n.pt.ptc                `   | r|rt          |t                    r|h}t          | t          t          f          r| n| gD ]o}t          |                              d          d                                                                         x}rd| |v sJ | | d| d|             ldS dS dS )zCheck file(s) for acceptable suffix.

    Args:
        file (str | list[str]): File or list of files to check.
        suffix (str | tuple): Acceptable suffix or tuple of suffixes.
        msg (str): Additional message to display in case of error.
    r  r   z acceptable suffix is z, not .N)rk   rD   rn   rN   r   lowerr8   )r   suffixrz   fra   s        r+   check_suffixr#  :  s      ^ ^fc"" 	XF#D4-88Dtf 	^ 	^AFF%%c**2.4466<<>>>q ^1ww&(((S*]!*]*]6*]*]Z[*]*](((^ ^ ^ ^	^ 	^r-   r   c                *   d| v sd| v rd| v r|                      dd          } nod| v rkd| vrg| }t          j        dd|           } t          j        d	d|           } t          j        d
d|           } | |k    r|rt          j        d| d|  d           | S )a  Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.

    Args:
        file (str): Filename to check and potentially update.
        verbose (bool): Whether to print information about the replacement.

    Returns:
        (str): Updated filename.
    yolov3yolov5zu.yaml.yamlr  uz(.*yolov5([nsmlx]))\.ptz\1u.ptz(.*yolov5([nsmlx])6)\.ptz(.*yolov3(|-tiny|-spp))\.ptu   PRO TIP 💡 Replace 'model=z' with new 'model=z'.
YOLOv5 'u' models are trained with https://github.com/ultralytics/ultralytics and feature improved performance vs standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.
)r   r;   r   r   r   )r   r   original_files      r+   check_yolov5u_filenamer*  J  s     48t++t<<'22DDd]]s$ M64iFFD65y$GGD68)TJJD}$$$d= d dTX d d d  
 Kr-   yolo11nmodel
str | Pathc                    t          |           }|j        s(|j        t          j        v r|                    d          S | S )zReturn a model filename from a valid model stem.

    Args:
        model (str): Model stem to check.

    Returns:
        (str | Path): Model filename with appropriate suffix.
    r  )r   r!  stemr!   GITHUB_ASSETS_STEMSwith_suffix)r,  paths     r+   check_model_file_from_stemr3  e  sA     ;;D; '49	(EEE&&&Lr-   r  c                B   t          | |           t          |                                           } t          |           } | rLd| vr!t	          |                                           s'|                                                     d          r| S |r	|                                                     d          rddlm	}  || |          }|g S | dd         }t	          |          |z  t          |          z  }|j        d	k    r|                    d
           |                                r(t          j        dt          |           d|            n3|j                            d
d
           t%          j        ||d           t          |          S |r|                                                     d          r|                     d          rd| dd         z   } | }t	          |          t          |           z  } |                                 r(t          j        dt          |           d|             nt%          j        || d           t          |           S t)          j        t          t*          dz  | z            d
          p-t)          j        t          t*          j        | z                      }	|	s|rt-          d|  d          t/          |	          dk    r|rt-          d|  d|	           t/          |	          r|	d         ng S )aK  Search/download file (if necessary), check suffix (if provided), and return path.

    Args:
        file (str): File name or path, URL, platform URI (ul://), or GCS path (gs://).
        suffix (str | tuple): Acceptable suffix or tuple of suffixes to validate against the file.
        download (bool): Whether to download the file if it doesn't exist locally.
        download_dir (str): Directory to download the file to.
        hard (bool): Whether to raise an error if the file is not found.

    Returns:
        (str | list): Path to the file, or an empty list if not found.
    z://zgrpc://zul://r   )resolve_platform_urir   N   z.ndjsonT)
missing_okzFound z locally at )parentsexist_okF)r   r   unzip)zhttps://zhttp://zrtsp://zrtmp://ztcp://gs://r<  zhttps://storage.googleapis.com/z**)	recursive'z' does not existr/   zMultiple files match 'z', specify exact path: )r#  rD   r8   r*  r   r   r   r9   $ultralytics.utils.callbacks.platformr5  r#   r!  unlinkr   r   r   parentmkdirr!   r   globr   r   ru   )
r   r!  downloaddownload_dirr   r5  r   uri_path
local_filefiless
             r+   
check_filerI  t  s6    vt99??D!$''D*.$t**"3"3"5"5::<<""9--  	 $.djjll--g66 $.MMMMMM""4d333;I8,''(2Xc]]B
	))... 	KKI3IIZIIJJJJ##D4#@@@#*EJJJJ:	 .djjll--H  . ??7## 	@4tABBx?DL!!HTNN2;;== 	EKC3CCTCCDDDD#$eDDDD4yy	#dTkD011TBBBhdiPSTXT_bfTfPgPgFhFh 	c 	c#$>$>$>$>???ZZ!^^^#$aT$a$aZ_$a$abbbu::-uQxx2-r-   r'  z.ymlc                &    t          | ||          S )aa  Search/download YAML file (if necessary) and return path, checking suffix.

    Args:
        file (str | Path): File name or path.
        suffix (tuple): Tuple of acceptable YAML file suffixes.
        hard (bool): Whether to raise an error if the file is not found or multiple files are found.

    Returns:
        (str): Path to the YAML file.
    r6  )rI  )r   r!  r   s      r+   
check_yamlrL    s     dF....r-   basedir
Path | strr2  c                   t          |                                           }t          |                                          }|                                o)|j        dt	          |j                           |j        k    S )a  Check if the resolved path is under the intended directory to prevent path traversal.

    Args:
        basedir (Path | str): The intended directory.
        path (Path | str): The path to check.

    Returns:
        (bool): True if the path is safe, False otherwise.
    N)r   r   r   partsru   )rM  r2  base_dir_resolvedpath_resolveds       r+   check_is_path_saferS    sm     W--//JJ&&((M!!tm&9:XC@Q@W<X<X:X&Y]n]t&ttr-   c                   	 t           r(t          st          rJ dt          j        v s
J d            t          j        dt          j        dt          j	                             t          j
        d           t          j                     t          j
        d           dS # t          $ r$}| rt          j        d|            Y d	}~d
S d	}~ww xY w)zCheck if environment supports image displays.

    Args:
        warn (bool): Whether to warn if environment doesn't support image displays.

    Returns:
        (bool): True if environment supports image displays, False otherwise.
    DISPLAYz+The DISPLAY environment variable isn't set.test)   rW  rP   )dtyper/   Tz>Environment does not support cv2.imshow() or PIL Image.show()
NF)r   r   r   r   r   cv2imshownpzerosuint8waitKeydestroyAllWindowsrT   r   rU   )warnrW   s     r+   check_imshowra    s     	Z1	111
***,Y***
628IRX>>>???AAt    	bN`]^``aaauuuuus   BB! !
C+C

Cc           	        ddl }ddlm} t          rt	          j        dd           | rd}|                                j        }t	          j        d          \  }}}d	t          j
                     d
||z  dd||z
  |z  dd||z  dd	}		 ddlm}
 |
                                 n# t          $ r Y nw xY wd}	t          j        rt#                        ||d           t%          j        d|	            dS )zPrint a human-readable YOLO software and hardware summary.

    Args:
        verbose (bool): Whether to print verbose information.
        device (str | torch.device): Device to use for YOLO.
    r   N)select_devicesample_dataT)ignore_errors   @r   (z CPUs, r   z	 GB RAM, z	 GB disk))displayr$   F)devicenewlineu   Setup complete ✅ )psutilultralytics.utils.torch_utilsrc  r   shutilrmtreevirtual_memorytotal
disk_usager   	cpu_countIPythonrh  clear_outputImportErrorr   is_repocheck_multiple_installr   r   )r   ri  rk  rc  gibramrp  _usedfreera   rh  s              r+   
check_yolor|    s]    MMM;;;;;; 9m48888 ##%%+#.s33udtttsSytttPS?StttZ_beZetttt	''''''  """" 	 	 	D	 
{ !   M////
K)a))*****s   B( (
B54B5c                     ddl } ddlm} ddlm}m} d}t          j                                        }t                       t          j        d          \  }}}t          j                    |t          t          j        rdn
t           rdnd	t#          t$                    |                                 j        |z  d
d||z
  |z  dd||z  dd |            t+          j                    |r |d          nd|rt          j                                        nd|rt          j        j        ndd}	t3          j        dd                    d |	                                D                       z   dz              i }
t;          t=          d                    D ]}	 t?          j        |j                   }tC          |t#          |j"                  |j         d          rdnd}n# t>          j#        $ r d}d}Y nw xY w| | |j"         |
|j         <   t3          j        |j         d|
|j                              |
|	d<   tI                      rt+          j%        d          t+          j%        d          t+          j%        d          t+          j%        d          t+          j%        d          t+          j%        d          d }t3          j        dd                    d! |                                D                       z              ||	d"<   |	S )#zCollect and print relevant system information including OS, Python, RAM, CPU, and CUDA.

    Returns:
        (dict): Dictionary containing system information.
    r   N)ENVIRONMENT)get_cpu_infoget_gpu_inforf  r   gitpipotherz.2fz GBr   )index)OSEnvironmentr   Installr   RAMDiskCPUz	CPU countGPUz	GPU countCUDAr   c              3  *   K   | ]\  }}|d | V  dS )<23Nr'   r)   kr   s      r+   r_   z&collect_system_info.<locals>.<genexpr>*  s0       M M41aA1 M M M M M Mr-   r   )r?   T)r2   r   u   ✅ u   ❌ z(not installed)r  zPackage Info	RUNNER_OSGITHUB_EVENT_NAMEGITHUB_WORKFLOWGITHUB_ACTORGITHUB_REPOSITORYGITHUB_REPOSITORY_OWNER)r  r  r  r  r  r  c              3  *   K   | ]\  }}| d | V  dS ): Nr'   r  s      r+   r_   z&collect_system_info.<locals>.<genexpr>B  s0      $Q$QTQ[[Q[[$Q$Q$Q$Q$Q$Qr-   zGitHub Info)&rk  ultralytics.utilsr~  rl  r  r  rl   r  is_availabler|  rm  rq  platformr   r   rv  r   rD   r   ro  rp  r   rr  device_countrV   r   r   r   itemsrB   rL   r   r2   r   r3   r   r"   getenv)rk  r~  r  r  rx  r  rp  _r{  	info_dictpackage_infor   r   is_metgithub_infos                  r+   collect_system_infor    s;    MMM------HHHHHHHH
C:""$$DLLL&s++NE1d !!" KQ55n-QUU'D		''))/#5>>>>DLC'BBBeckBBBB|~~\^^(,6||!$$$$$26@UZ,,...D&*4"" I Ktyy M M9??;L;L M M MMMMPTTUUUL(=m(L(LMMM ; ;	&qv..G,Wc!+6F6FQVZ^___kVVekFF, 	 	 	'GFFF	 #)@'@1;@@QVqv99<#799:::: ,In!! 
/;//!#+>!?!?!y):;;In55!#+>!?!?')y1J'K'K
 
 	D499$Q$Q[=N=N=P=P$Q$Q$QQQQRRR#.	- s   AG##G98G9c                >   	 ddl m t                                                     j        	t          d          }	j        dv rdS t          j        dt          j	                  }t          j                            	          }t          |                    |                    rt          j        | d| d           dS 	 fd	}t"          d
z  }t          j        | d           d}	 ddlm}  | |d          |          sJ t          j        | d           nw# t*          $ r t          j        | d|            Y nRt,          t.          f$ r t          j        | d|            Y n't0          $ r t          j        | d           Y dS w xY wdS )av  Check the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO model.

    If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP
    results, so AMP will be disabled during training.

    Args:
        model (torch.nn.Module): A YOLO model instance.

    Returns:
        (bool): Returns True if the AMP functionality works correctly with YOLO model, else False.

    Examples:
        >>> from ultralytics import YOLO
        >>> from ultralytics.utils.checks import check_amp
        >>> model = YOLO("yolo26n.pt").model.cuda()
        >>> check_amp(model)
    r   )autocastzAMP: >   cpumpsFzV(nvidia|geforce|quadro|tesla).*?(1660|1650|1630|t400|t550|t600|t1000|t1200|t2000|k40m)u#   checks failed ❌. AMP training on zW GPU may cause NaN losses or zero-mAP results, so AMP will be disabled during training.c                   |gdz  }t          dt          j                                         dz                      } | ||d          d         j        j        } d          5   | ||d          d         j        j        }d	d	d	           n# 1 swxY w Y   ~ |j        |j        k    o(t          j        ||                                d
          S )zAll close FP32 vs AMP results.rW        F)rw   ri  r   r   T)enabledNg      ?)atol)	rf   rR   rj   boxesdatashaperl   allclosefloat)	mimbatchrw   abr  ri  r,  s	         r+   amp_allclosezcheck_amp.<locals>.amp_allclosen  s'   qCU\--//!34455Ae5???BHMXd### 	R 	R%uVUCCCAFLQA	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	Rw!'!LenQ		&L&L&LLs   * BBBzbus.jpgz1running Automatic Mixed Precision (AMP) checks...z`Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False.)YOLOr  u   checks passed ✅zGchecks skipped. Offline and unable to download YOLO26n for AMP checks. zichecks skipped. Unable to load YOLO26n for AMP checks due to possible Ultralytics package modifications. zchecks failed. Anomalies were detected with AMP on your system that may lead to NaN losses or zero-mAP results, so AMP will be disabled during training.T)rl  r  next
parametersri  r    rs   r;   compile
IGNORECASErl   r  get_device_namerY   searchr   rU   r   r   r   r  ConnectionErrorAttributeErrorr   r   error)
r,  r   patterngpur  r  warning_msgr  r  ri  s
   `       @@r+   	check_ampr  H  sn   $ 766666%""$$%%,FgF{n$$u *egigt
 
 j((00s##$$ 	N \ \c \ \ \   5M M M M M M M 
)	B
K6LLLMMMtK$$$$$$|DD..33333v0001111 x x x&vvitvvwwwww/0 
 
 
 v vhsv v	
 	
 	
 	
 	
     X X X	
 	
 	
 uu 4s   14D& &#F)F6 FFc                 R   ddl } 	 t          j        | j        ddddgdd          }d	t          j         d
}|j        dk    r<d|j                                        v rt          j
        dt           d|            dS t          t          j        d|j        t          j                  d                   dz                                  }|                    t	          j                              s$t          j
        d| dt           d|            dS dS # t$          $ r Y dS w xY w)z6Check if there are multiple Ultralytics installations.r   Nz-mr  showr   T)r   r   z>Install your local copy in editable mode with 'pip install -e z?' to avoid issues. See https://docs.ultralytics.com/quickstart/z	not foundz2Ultralytics not found via pip but importing from: z. zlocation:\s+(.+))flagsr   zFMultiple Ultralytics installations detected. The `yolo` command uses: z$, but current session imports from: z$. This may cause version conflicts. )r   r   r   r   r   rA  r   r   r   r   rU   r   r;   rS   r   Ir   samefilerT   )r   r   install_msg	yolo_paths       r+   rw  rw    s}   JJJufm TeiptuuuCT[ C C C 	 !!fm113333iTXii\giijjjF"*%8&-rtTTTUWXYY\iirrtt	!!$,..11 	NmYb m m59m m_jm m    	 	
    s   A6D >BD 
D&%D&argsdict | Nonec           
        	 d 	t          j                    j        }t          j        |          \  }}}}} 9t          j        |          \   }}} fd|                                D              	 t          |                                                              t                    
                    d          }n$# t          $ r t          |          j        }Y nw xY w|r| dnd|r| dndz   }t          j        t          |          d                    	fdt#                                                     D                       z              dS )zPrint function arguments (optional args dict).

    Args:
        args (dict, optional): Arguments to print.
        show_file (bool): Whether to show the file name.
        show_func (bool): Whether to show the function name.
    c                    t          | t                    r7|                     d          r"t          |           dk    rt	          |           n| S )zTClean longer Ultralytics HUB URLs by stripping potential authentication information.httpd   )rk   rD   r9   ru   r   )r   s    r+   
strip_authzprint_args.<locals>.strip_auth  sH     *1c 2 2dq||F7K7KdPSTUPVPVY\P\P\y|||cddr-   Nc                $    i | ]\  }}|v 	||S r'   r'   )r)   r  r   r  s      r+   
<dictcomp>zprint_args.<locals>.<dictcomp>  s$    :::AT		1			r-   r$   r  r   c              3  >   K   | ]\  }}| d  |           V  dS )=Nr'   )r)   r  r   r  s      r+   r_   zprint_args.<locals>.<genexpr>  s=      '`'`41a1(>(>zz!}}(>(>'`'`'`'`'`'`r-   )inspectcurrentframef_backgetframeinfogetargvaluesr  r   r   relative_tor   r1  rv   r/  r   r   r    r   sorted)
r  	show_file	show_funcr*   r   r  funcfrmra   r  s
   `        @r+   
print_argsr    sg   e e e 	%A!.q11D!T1a|!.q11aC:::::::Dzz!!##//55AA"EE   Dzz!	)DrY.NkkkkBOA
Kdii'`'`'`'`6RVR\R\R^R^K_K_'`'`'````aaaaas   4AC C"!C"rR   c                 >   t           rt          j                                        S 	 t	          j        g dd          } |                                                     dd          d         }t          |          S # t          j	        t          t          f$ r Y dS w xY w)zGet the number of NVIDIA GPUs available in the environment.

    Returns:
        (int): The number of NVIDIA GPUs available.
    )z
nvidia-smiz--query-gpu=countz--format=csv,noheader,nounitszutf-8)encodingr   r/   r   )r   rl   r  r  r   r   r8   rI   rR   CalledProcessErrorr   rv   )r   
first_lines     r+   cuda_device_countr    s      z&&(((	,TTT_f  F
  --dA66q9Jz??"-/@*M 	 	 	11	s   AA< <BBc                 &    t                      dk    S )zCheck if CUDA is available in the environment.

    Returns:
        (bool): True if one or more NVIDIA GPUs are available, False otherwise.
    r   )r  r'   r-   r+   cuda_is_availabler    s     ""r-   c                    t           rt          r	 t          d          5 } |                                 }|                    d          ^ }}|                    dd                              dd          d         t          v r	 ddd           d	S 	 ddd           n# 1 swxY w Y   dS dS # t          $ r Y d
S w xY wd
S )zCheck if the current environment is running on a Rockchip SoC.

    Returns:
        (bool): True if running on a Rockchip SoC, False otherwise.
    z/proc/device-tree/compatibler    r$   -r/   r   NTF)r   r   openreadrI   r   r   OSError)r"  dev_strr  socs       r+   is_rockchipr    s9     
 
	455  &&((!--,,C;;vr**00a88;zII	                J                                     
  	 	 	55	 us;   B- A%BB- B- B""B- %B"&B- -
B;:B;c                     ddl m}  d |                                             v rdS 	 t          j        ddgddd          }d|j                                        v S # t          $ r Y d	S w xY w)
zCheck if the system has Intel hardware (CPU or GPU).

    Returns:
        (bool): True if Intel hardware is detected, False otherwise.
    r   )r  intelTzxpu-smi	discoveryr7  )r   r   r   F)rl  r  r   r   r   r   rT   )r  r   s     r+   is_intelr    s     ;::::: ,,..&&((((tK 8TXbcddd&---////   uus   4A 
A+*A+c                     t           rdS d} t          j        | dt          j        t          j                  j        dk    S )zCheck if the sudo command is available in the environment.

    Returns:
        (bool): True if the sudo command is available, False otherwise.
    Fzsudo --versionT)r   r   r   r   )r   r   r   DEVNULLr   )r   s    r+   r   r     s>      u
C>#T*2DZM_```kopppr-   z3.8)r   r   z3.9z3.10z3.12z3.13r6  )rC   rD   rE   rD   )rM   )rE   rN   )rE   rY   )rc   r/   r0   r   )rM   rM   rV   FFr$   )r   rD   r   rD   r2   rD   r   rY   r   rY   rz   rD   rE   rY   )r   )r   )r   TF)r   rD   r   rY   r   rY   rE   rY   )r  )r  rD   )r  r  r$   )T)r   rD   r   rY   rE   rD   )r+  )r,  rD   rE   r-  )r$   Tr  T)rJ  T)rM  rN  r2  rN  rE   rY   )F)Tr$   )NTF)r  r  )rE   rR   )b
__future__r   rp   	functoolsrC  r  rg   r   r  r;   rm  r   r   r   	importlibr   pathlibr   typesr   rY  numpyr[  rl   r  r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   rA  rB   rL   	lru_cacherX   rb   r|   r   r   r   r   r   r   r   r
  r  r  r  r#  r*  r3  rI  rL  rS  ra  r|  r  r  rw  r  r  r  r  r  r   r9   IS_PYTHON_3_8IS_PYTHON_3_9IS_PYTHON_3_10IS_PYTHON_3_12IS_PYTHON_3_13IS_PYTHON_MINIMUM_3_9IS_PYTHON_MINIMUM_3_10IS_PYTHON_MINIMUM_3_12r'   r-   r+   <module>r
     sR   # " " " " " 



        				  				      



              ! ! ! ! ! ! 



                                                                  B "&/A!A2    >         	- 	- 	- 	-2 2 2 2j    T T T T Tn   (  , 
    :] ] ] ] ] $x $x $xN $(K2D$DbZ^eg h h h hV' ' 'Q Q Q Q Q! ! !H^ ^ ^ ^     6    :. :. :. :.z/ / / /u u u u     0!+ !+ !+ !+H9 9 9xE E EP  0b b b b b4   2# # # #  &  (	q 	q 	q 	q U - - - -      *)%00))%00**622**622**622$U777 %f5999 %f5999   r-   