
    |h                        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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-m.Z.m/Z/m0Z0 e%jb                  dz  dfd	Z2e jf                  d9d
e4fd       Z5d
e6fdZ7d:dZ8e jf                  d        Z9e jf                  	 	 	 	 	 	 d;de:de:de:de6de6de:d
e6fd       Z;d<dZ<d Z= e*       e jf                  d=d              Z>d>de:de6de6d
e6fdZ? e+       e%jb                  dz  dddfd       Z@d ZAd?d ZBd@d!e:de6fd"ZCdAd#ZDdBd$ZEdCd%ZFd& ZGe jf                  dDd'       ZHdEd(ZId) ZJd* ZKe%fd+ZLdFd,eeM   fd-ZNd
eOfd.ZPd
e6fd/ZQd0 ZRd1 ZSd
e6fd2ZT e?d3dd4        eA         e#j                  d3      ZV e#j                  d5      ZW e#j                  d6      ZX e?d7d8      ZY e?d5d8      ZZy)G    N)metadata)Path)SimpleNamespace)Optional)ARM64ASSETSAUTOINSTALLIS_COLAB
IS_GIT_DIR	IS_JETSON	IS_KAGGLEIS_PIP_PACKAGELINUXLOGGERMACOSONLINEPYTHON_VERSION
RKNN_CHIPSROOTTORCHVISION_VERSIONUSER_CONFIG_DIRWINDOWSRetryThreadingLocked	TryExcept	clean_urlcolorstr	downloadsis_github_action_runningurl2filezrequirements.txt c                    |r2t        j                  |      j                  D cg c]	  }d|vs| }}n't        |       j	                         j                         }g }|D ]  }|j                         }|s|j                  d      r(|j                  d      d   j                         }t        j                  d|      x}sc|j                  t        |d   |d   r|d   j                         nd              |S c c}w )	a4  
    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")
    z	extra == #r   z ([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?      r!   )name	specifier)r   distributionrequiresr   	read_text
splitlinesstrip
startswith	partitionrematchappendr   )	file_pathpackagexr)   requirementsliner0   s          W/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/checks.pyparse_requirementsr8   4   s      '44W=FF_!+]^J^A__	?,,.99;L tzz|,>>#&q)//1D!DdKKuK##OqafghaiUSTX^^M]oq$rst  `s
   	C>C>returnc           	          	 t        t        t        t        j                  d|       dd             S # t
        $ r%}t        j                  d|  d|        Y d}~y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   )tuplemapintr/   findall	Exceptionr   warning)versiones     r7   parse_versionrD   T   s[    Sbjj9"1=>?? 3G9<TUVTWXYs   /2 	A AA c                 8    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   8   K   | ]  }t        |      d k    yw)   N)ord).0cs     r7   	<genexpr>zis_ascii.<locals>.<genexpr>p   s     ,s1v|,s   )allstr)ss    r7   is_asciirO   f   s     ,SV,,,    c           	      l   t        t        |t        j                        r|j	                         n|      }t        | t               r| g} nt        | t
        t        f      rt        |       } n]t        | t              r(| j                         rt        |       gn
t        |       } n%t        d|  dt        |       j                   d      t        |       |kD  rHd}|dk7  rt        d|  d|       t        j                   dt	        |        d	|        t	        |       g} | D cg c]'  }t	        t#        j$                  ||z        |z  |      ) }}|| k7  rt        j                   d|  d
| d|        |dk(  rt        |      dk(  r|d   |d   g}|S |dk(  rt        |      dk(  r|d   }|S |}|S c c}w )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'. z  must be multiple of max stride z, updating to r%   r   )r>   
isinstancetorchTensormaxlistr<   rM   	isnumericeval	TypeErrortype__name__len
ValueErrorr   rA   mathceil)imgszstridemin_dimmax_dimfloormsgr4   szs           r7   check_imgszrg   s   s     FELL!AvNF %	ED%=	)U	E3	 % 1UtE{eW1$u+2F2F1G HX Y
 	
 5zGY 	 a<veW,HNOO,SZLC5ABU>C	D#diiF
#f,e
4	DB	D 
U{w&Fvhn]_\`ab #a<CGqL"Q%ABI HORS|X[\^X_cdXdbeBI kmBI 
Es   #,F1c                  n    	 t        j                  ddgd      j                  dk(  S # t        $ r Y yw xY w)zBCheck if uv package manager is installed and can run successfully.uvz-VT)capture_outputr   F)
subprocessrun
returncodeFileNotFoundError rP   r7   check_uvrp      s9    ~~tTl4@KKqPP s   %( 	44Fcurrentrequiredr&   hardverbosere   c                 0   | st        j                  d|  d| d       y| d   j                         s	 | }t        j                  |       } |syd	|v r#t        rd
|vst        rd|vst        r	d|vrd|vryd}d}d}	t        |       }
|j                  d      j                  d      D ]  }t        j                  d|      j                         \  }}|sd}t        |      }|dk(  r|
|k7  rd}	F|dk(  r|
|k(  rd}	S|dk(  r|
|k\  sd}	`|dk(  r|
|k  sd}	m|dk(  r|
|kD  sd}	z|dk(  s|
|k  rd}	 |	s3| | d| d|  d| }|rt        |      |rt        j                  |       |	S # t        j
                  $ r}|rt        |  d      |Y d}~yd}~ww xY w)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 an AssertionError 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<=><z is required, but z is currently installed )r   rA   isdigitr   rB   PackageNotFoundErrorModuleNotFoundErrorr   r   r   rD   r,   splitr/   r0   groups)rq   rr   r&   rs   rt   re   rC   oprB   resultrJ   rvrA   s                 r7   check_versionr      s   H /y8*DefgQZ!	D&&w/G !	WH,gX-gX-((2J	BGFgA^^C &&s+ hh3Q7>>@GB'":!q&F4ZAFF4ZaF4ZaF3YAF3YAF!" F8*$6tfBwiG_`c_de%g..NN7#MW ,, 	)WI5[*\]cdd		s   E' 'F:FFc                     ddl }	 |j                  j                  j                          |j	                  d|  dd      }|j
                  dk(  r|j                         d   d	   S y# t        $ r Y yw xY w)
z
    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): The latest version of the package.
    r   Nzhttps://pypi.org/pypi/z/jsonr;   )timeout   inforB   )requestspackagesurllib3disable_warningsgetstatus_codejsonr@   )package_namer   responses      r7   check_latest_pypi_versionr     s|     !!224<<"8e LVW<X3&==?6*955 ' s   AA' '	A32A3c                      t         rBt        r<	 ddlm}  t	               }t        | d|       rt        j                  d| d       y	 yy# t        $ r Y yw xY w)z
    Check 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   ultralyticsr   r   r   r   r   r@   )r   latests     r7   check_pip_update_availabler      sn     .	/.0F[AfX,7?x H? @  8   		s   8A
 
	AAc                 H   ddl m} t        |       j                  }t        |z  }|j                         r|S |j                         D cg c]	  }| |v s| }}t        |      r|d   S d| }t        j                  |d      rt        j                  ||       |S yc c}w )z
    Find 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): Resolved font file path.
    r   )font_managerz?https://github.com/ultralytics/assets/releases/download/v0.0.0/T)check)urlfileN)
matplotlibr   r   r&   r   existsfindSystemFontsanyr   is_urlsafe_download)fontr   r&   r   rN   matchesr   s          r7   
check_fontr   7  s     ( :??DT!D{{} '668FQDAIqFGF
7|qz LD6
RC4(Cd3 ) Gs   		BBTminimumc                 *    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 an AssertionError 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)r&   rs   rt   )r   r   )r   rs   rt   s      r7   check_pythonr   W  s     xdT[\\rP   ro   c                 0   t        ddd      }t        | t              rm| j                         }|j	                         sJ | d| d       t        |      D cg c]+  }|j                  |vs|j                   |j                   - } }nt        | t              r| g} g }| D ]}  }|j                  d      d   j                  dd	      }	t        j                  d
|	      }
|
d   |
d   r|
d   j                         nd	}}	 t        t        j                   |      |      sJ  t)        dd      d        }dj+                  d |D              }|r|rt,        rt/        |      }t1        j2                  | dd|dkD  z   d| d       	 t5        j4                         }t6        sJ d       t1        j2                   |||t8         xr
 t;                            t5        j4                         |z
  }t1        j2                  | d|dd       t1        j<                  | dt        dd       d       yyyc c}w # t"        t        j$                  f$ r |j'                  |       Y w xY w# t>        $ r$}t1        j<                  | d|        Y d}~yd}~ww xY w)a  
    Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed.

    Args:
        requirements (Path | str | List[str]): Path to a requirements.txt file, a single package requirement as a
            string, or a list of package requirements as strings.
        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.0.0")

        Check multiple packages
        >>> check_requirements(["numpy", "ultralytics>=8.0.0"])
    redboldzrequirements: z not found, check failed./z.gitr!   z([a-zA-Z0-9-_]+)([<>!=~]+.*)?r$   r%   )timesdelayc                    |r>d|  d| d}	 t        j                  |dt         j                        j                         S t        j                  d|  d| d	      j                         S # t         j                  $ rh}|j
                  rVd|j
                  j                         v r:t        j                  |j                  dd      d	      j                         cY d
}~S  d
}~ww xY w)zGAttempt package installation with uv if available, falling back to pip.zuv pip install --no-cache-dir r   zN --index-strategy=unsafe-best-match --break-system-packages --prerelease=allowT)shellstderrzNo virtual environment foundzuv pip installzuv pip install --systemr   Nzpip install --no-cache-dir )rk   check_outputPIPEdecodeCalledProcessErrorr   replace)r   commandsuse_uvbaserC   s        r7   attempt_installz+check_requirements.<locals>.attempt_install  s     3H:Qxj  IW  XD!..t4
X__aa &&)DXJaPXz'Zbfgnnpp 00 88 >!((//BS S%22%57PQY]fh s$   3A, ,C'?AC"C'!C""C'c              3   (   K   | ]
  }d | d   yw)"Nro   )rI   r4   s     r7   rK   z%check_requirements.<locals>.<genexpr>  s     (a1QCq(s   z Ultralytics requirementrN   z$ not found, attempting AutoUpdate...zAutoUpdate skipped (offline))r   u    AutoUpdate success ✅ .1fz;Restart runtime or rerun command for updates to take effect
u    ❌ NFT) r   rR   r   resolver   r8   r&   r'   rM   
rpartitionr   r/   r0   r,   r   r   rB   AssertionErrorr   r1   r   joinr	   r\   r   r   timer   r   rp   rA   r@   )r5   excludeinstallcmdsprefixr   r4   pkgsr   
r_strippedr0   r&   rr   r   rN   ntdtrC   s                      r7   check_requirementsr   f  sz   0 eV_5F,%##%{{}I$/HII}:LT:RlQVWV\V\dkVk166(1;;-0ll	L#	&$~D \\#&r*2262>
9:FquQx58>>#3Rh	 !1!1$!7BBB !q q 	(4((A{D	AKK6(":3!a%=/4&PtuvIIK===vOAtI<T(*UVYY[1_vh&>r#haHIha1n opprs  e m  = => 	KKN	B  &qc23s7   H2,H2?!H7B(I( 7*I%$I%(	J1JJc                     dgdgdgdgdgdgdgdgd	gd
gd
} dj                  t        j                  j                  dd      d   j                  d      dd       }|| v rw| |   }dj                  t	        j                  dd      d   j                  d      dd       t        fd|D              r#t        j                  d d| d|d    d       yyy)a1  
    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.22z0.21z0.20z0.19z0.18z0.17z0.16z0.15z0.14z0.13)
z2.7z2.6z2.5z2.4z2.3z2.2z2.1z2.0z1.13z1.12.+r$   r   Nr%   c              3   (   K   | ]	  }|k7    y w)Nro   )rI   r   v_torchvisions     r7   rK   z$check_torchvision.<locals>.<genexpr>  s     ?a}!?s   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   rS   r   r   r   rL   r   rA   )compatibility_tablev_torchcompatible_versionsr   s      @r7   check_torchvisionr     s    xxxxxxxx hhu((..sA6q9??DRaHIG%%1':!4!:!:3!B1!E!K!KC!PQSRS!TU?+>??NN.KG9 U11DQ1G0H Idd @ &rP   c                    | r|rt        |t              r|h}t        | t        t        f      r| n| gD ]V  }t        |      j	                  d      d   j                         j                         x}s?d| |v rGJ | | d| d|         yyy)a  
    Check 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)rR   rM   rV   r<   r   lowerr,   )r   suffixre   frN   s        r7   check_suffixr     s     fc"XF#D4-8tf 	^AF%%c*2.446<<>>q>1#w&(]SE!4J6(RYZ[Y\*]](	^ trP   r   c                 *   d| v sd| v rd| v r| j                  dd      } | S d| v rnd| vrj| }t        j                  dd|       } t        j                  d	d|       } t        j                  d
d|       } | |k7  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.yaml.pt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/   subr   r   )r   rt   original_files      r7   check_yolov5u_filenamer     s     48t+t<<'2D K d]s$ M664iFD665y$GD668)TJD}$2=/ASTXSY Zc d
 KrP   c                     t        |       }|j                  s-|j                  t        j                  v r|j                  d      S | S )z
    Return 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)modelpaths     r7   check_model_file_from_stemr     s;     ;D;;499	(E(EE&&LrP   c                 \   t        | |       t        |       j                         } t        |       } | r<d| vrt	        |       j                         s| j                         j                  d      r| S |r| j                         j                  d      r{| }t	        |      t        |       z  } | j                         r/t        j                  dt        |       d|         t        |       S t        j                  || d       t        |       S t        j                  t        t        dz  | z        d	
      xs/ t        j                  t        t        j                   | z              }|s|rt#        d|  d      t%        |      dkD  r|rt#        d|  d|       t%        |      r|d   S g S )a  
    Search/download file (if necessary), check suffix (if provided), and return path.

    Args:
        file (str): File name or path.
        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): Path to the file.
    z://zgrpc://)zhttps://zhttp://zrtsp://zrtmp://ztcp://zFound z locally at F)r   r   unzipz**T)	recursive'z' does not existr$   zMultiple files match 'z', specify exact path: r   )r   rM   r,   r   r   r   r   r-   r    r   r   r   r   r   globr   parentrn   r\   )r   r   downloaddownload_dirrs   r   filess          r7   
check_filer     sr    vt9??D!$'D$t*"3"3"5::<""9-	djjl--.efL!HTN2;;=KK&3 0TFCD 4y ##$eD4y		#dTkD01TBhdiiPSTXT_T_bfTfPgFh#av-=$>??Z!^#&<TFBYZ_Y`$abbu:uQx-2-rP   c                     t        | ||      S )af  
    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.
    rs   )r   )r   r   rs   s      r7   
check_yamlr   >  s     dF..rP   c                     t        |       j                         }t        |      j                         }|j                         xr/ |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   partsr\   )basedirr   base_dir_resolvedpath_resolveds       r7   check_is_path_safer  M  sc     W--/J&&(M!tm&9&9:XC@Q@W@W<X&Y]n]t]t&ttrP   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       y# t        $ r$}| rt        j                  d|        Y d	}~y
d	}~ww xY w)z
    Check 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)   r
  r;   )dtyper$   Tz>Environment does not support cv2.imshow() or PIL Image.show()
NF)r   r
   r   osenvironcv2imshownpzerosuint8waitKeydestroyAllWindowsr@   r   rA   )warnrC   s     r7   check_imshowr  ^  s    	11

*Y,YY*

6288IRXX>?AA NN\]^\_`as   B$B' '	C0CCc           	         ddl }ddlm} t        rt	        j
                  dd       | r}d}|j                         j                  }t	        j                  d      \  }}}d	t        j                          d
||z  dd||z
  |z  dd||z  dd	}		 ddlm}
 |
j                          nd}	 ||d       t        j                   d|	        y# t        $ r Y .w xY w)z
    Return 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_utilsr  r
   shutilrmtreevirtual_memorytotal
disk_usager  	cpu_countIPythonr  clear_outputImportErrorr   r   )rt   r  r   r  gibramr%  usedfreerN   r  s              r7   
check_yolor/  x  s     ;m48##%++"--c2tTwsSyoYPS?STW>XXYZ_beZefiYjjst	'  " /
KK%aS)*  		s   C 	CCc                     ddl } ddlm} ddlm}m} d}t        j                  j                         }t                t        j                  d      \  }}}t        j                         |t        t        rdn	t        rdnd	t!        t"              | j%                         j&                  |z  d
d||z
  |z  dd||z  dd |       t)        j*                         |r	 |d      nd|rt        j                  j-                         nd|rt        j.                  j                  ndd}	t1        j2                  ddj5                  d |	j7                         D              z   dz          i }
t9        d      D ]  }	 t;        j.                  |j<                        }t?        |t!        |j@                        |j<                  d      rdnd}| | |j@                   |
|j<                  <   t1        j2                  |j<                  d|
|j<                              |
|	d<   tE               rt)        jF                  d      t)        jF                  d      t)        jF                  d      t)        jF                  d      t)        jF                  d      t)        jF                  d      d }t1        j2                  ddj5                  d! |j7                         D              z          ||	d"<   |	S # t:        jB                  $ r d}d}Y 9w xY w)#z
    Collect 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_infor  r   gitpipotherz.2fz GBr   )index)OSEnvironmentr   Installr   RAMDiskCPUz	CPU countGPUz	GPU countCUDAr   c              3   0   K   | ]  \  }}|d |   yw)<20Nro   rI   kr   s      r7   rK   z&collect_system_info.<locals>.<genexpr>  s      M41aAc71# M   r   )r3   T)r&   rs   u   ✅ u   ❌ z(not installed)rA  zPackage Info	RUNNER_OSGITHUB_EVENT_NAMEGITHUB_WORKFLOWGITHUB_ACTORGITHUB_REPOSITORYGITHUB_REPOSITORY_OWNER)rE  rF  rG  rH  rI  rJ  c              3   0   K   | ]  \  }}| d |   yw): Nro   rB  s      r7   rK   z&collect_system_info.<locals>.<genexpr>  s     $QTQs"QC[$QrD  zGitHub Info)$r   ultralytics.utilsr1  r!  r2  r3  rS   cudais_availabler/  r"  r&  platformr   r   r   rM   r   r$  r%  r  r'  device_countrB   r   r   r   itemsr8   r   r&   r   r'   r   r   getenv)r   r1  r2  r3  r+  rN  r%  r-  r.  	info_dictpackage_infor   rq   is_metgithub_infos                  r7   collect_system_inforX    s{    -H
C::""$DL))#.E4 !" &5^ED	'')//#5c:#>DLC',Aeck#->cB~\\^(,|!$$26UZZ,,.D&*""I KKtyy M9??;L MMMPTTUL6 ;	&&qvv.G,Wc!++6FQVVZ^_VekF #)'1;;-@QVVqvvcl<#7"89:; !-In!;/!#+>!?!yy):;IIn5!#+>!?')yy1J'K
 	D499$Q[=N=N=P$QQQR#.	- ) ,, 	'GF	s   7AK%%L ?L c                     	 ddl m t         j                               j                  	t        d      }	j                  dv ryt        j                  dt        j                        }t        j                  j                  	      }t        |j                  |            rt        j                   | d| d       y	 fd	}t"        d
z  }t        j$                  | d       d}	 ddlm}  | |d      |      sJ t        j$                  | d       y# t*        $ r t        j                   | d|        Y yt,        t.        f$ r t        j                   | d|        Y yt0        $ r t        j2                  | d       Y yw xY w)a}  
    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 YOLO11 model, else False.

    Examples:
        >>> from ultralytics import YOLO
        >>> from ultralytics.utils.checks import check_amp
        >>> model = YOLO("yolo11n.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                  j                         dz              } | ||d      d   j                  j                  } d      5   | ||d      d   j                  j                  }d	d	d	       ~ |j
                  j
                  k(  xr& t        j                  ||j                         d
      S # 1 sw Y   KxY w)zAll close FP32 vs AMP results.r
        F)r`   r  rt   r   T)enabledNg      ?)atol)	rU   r>   ra   boxesdatashaperS   allclosefloat)	mimbatchr`   abrZ  r  r   s	         r7   amp_allclosezcheck_amp.<locals>.amp_allclose  s    qCU\\--/!345e5?BHHMMd# 	R%uVUCAFLLQQA	Rww!''!LennQ	&LL	R 	Rs   $$CC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.)YOLO
yolo11n.ptu   checks passed ✅zGchecks skipped. Offline and unable to download YOLO11n for AMP checks. zichecks skipped. Unable to load YOLO11n 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)r!  rZ  next
parametersr  r   rZ   r/   compile
IGNORECASErS   rN  get_device_nameboolsearchr   rA   r   r   r   rm  ConnectionErrorAttributeErrorr   r   error)
r   r   patterngpurl  rh  warning_msgrm  rZ  r  s
   `       @@r7   	check_ampr|    s   & 7%""$%,,FgF{{n$ **egigtgt
 jj((0s#$NN(=cU C[ \ M 
)	B
KK6(KLMtK$D.333vh/01   x&!hithuvw  /0 
h hhsgtv	
   h W X	
 s   +/D #F (F* FFc                 z    	 t        j                  d|  dd      j                         dd S # t        $ r Y yw xY w)z
    Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe.

    Args:
        path (Path): Path to git repository.

    Returns:
        (str): Human-readable git description.
    zgit -C z  describe --tags --long --alwaysTr   Nr   r!   )rk   r   r   r@   )r   s    r7   git_describer~     sI    &&6V'W_cdkkmnqoqrr s   +. 	::argsc           
         d t        j                         j                  }t        j                  |      \  }}}}}| Bt        j                  |      \  } }}}|j                         D 	ci c]  \  }}	|| v s||	 } }}		 t        |      j                         j                  t              j                  d      }|r| dnd|r| dndz   }
t        j                  t        |
      dj!                  fdt#        | j                               D              z          yc c}	}w # t        $ r t        |      j                  }Y w xY w)z
    Print 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                 z    t        | t              r*| j                  d      rt        |       dkD  rt	        |       S | S )zTClean longer Ultralytics HUB URLs by stripping potential authentication information.httpd   )rR   rM   r-   r\   r   )r   s    r7   
strip_authzprint_args.<locals>.strip_auth:  s5     *1c 2q||F7KPSTUPVY\P\y|dcddrP   Nr!   rL  rv   c              3   >   K   | ]  \  }}| d  |         yw)=Nro   )rI   rC  r   r  s      r7   rK   zprint_args.<locals>.<genexpr>H  s$     '`41a1#Qz!}o(>'`s   )inspectcurrentframef_backgetframeinfogetargvaluesrR  r   r   relative_tor   r   r]   r   r   r   r   r   sorted)r  	show_file	show_funcr4   r   _funcfrmrC  r   rN   r  s              @r7   
print_argsr  0  s!   e 	%%A!..q1D!T1a|!..q1aC!$:AT	1::Dz!!#//5AA"E "D6rYbkBOA
KKdii'`6RVR\R\R^K_'```a ;  Dzs   -D":D";D( (E	E	c                  "   t         rt        j                  j                         S 	 t	        j
                  g dd      } | j                         j                  dd      d   }t        |      S # t        j                  t        t        f$ r Y yw xY w)z
    Get 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   rS   rN  rQ  rk   r   r,   r   r>   r   rn   r]   )output
first_lines     r7   cuda_device_countr  K  s~     zz&&((	,,T_fF
  --dA6q9Jz?"--/@*M 		s   AA- -BBc                      t               dkD  S )z
    Check if CUDA is available in the environment.

    Returns:
        (bool): True if one or more NVIDIA GPUs are available, False otherwise.
    r   )r  ro   rP   r7   cuda_is_availabler  e  s     ""rP   c                     t         rdt        r^	 t        d      5 } | j                         }|j	                  d      ^ }}|j                  dd      t        v r
	 ddd       y	 ddd       yyy# 1 sw Y   xY w# t        $ r Y yw xY w)z
    Check 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!   NTF)r   r   openreadr   r   r   OSError)r   dev_strr  socs       r7   is_rockchipr  o  s     	45  &&(!--,C;;vr*j8	    9       
  		s.   A8 >A,A8 !A8 ,A51A8 8	BBc                  
   ddl m}  d |        j                         v ry	 t        j                  ddgddd      }d|j
                  j                         v S # t        j                  t        t        j                  f$ r Y y	w xY w)
z
    Check if the system has Intel hardware (CPU or GPU).

    Returns:
        (bool): True if Intel hardware is detected, False otherwise.
    r   )r2  intelTzxpu-smi	discovery   )rj   textr   F)	r!  r2  r   rk   rl   stdoutTimeoutExpiredrn   SubprocessError)r2  r   s     r7   is_intelr    s}     ; ,.&&((K 8TXbcd&----///%%'8*:T:TU s   6A (BBc                      t         ryd} t        j                  | dt        j                  t        j                        j                  dk(  S )z
    Check 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   rk   rl   DEVNULLrm   )cmds    r7   is_sudo_availabler    s<     
C>>#T*2D2DZM_M_`kkoppprP   z3.8)rs   rt   z3.12z3.13z3.10r   )0.0.0)    r$   r%   r   )r  r  rB   FFr!   )r   )z	Arial.ttf)z3.8.0TF)rn  r   r!   )T)yolo11n)r!   Tr   T))r   z.ymlT)F)Tr!   )NTF)[	functoolsr   r  r^   r  rP  r/   r"  rk   r   	importlibr   pathlibr   typesr   typingr   r  numpyr  rS   rM  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   r8   	lru_cacher<   rD   rt  rO   rg   rp   rM   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r/  rX  r|  r~  dictr  r>   r  r  r  r  r  r-   IS_PYTHON_3_8IS_PYTHON_3_12IS_PYTHON_3_13IS_PYTHON_MINIMUM_3_10IS_PYTHON_MINIMUM_3_12ro   rP   r7   <module>r     s       	  	      !  
        < "&/A!A2 @ e  "
-4 
-3l   UUU U 	U
 U 
U 
U Up*. 
  <]# ]t ]T ]VZ ] $(KK2D$DbZ^eg M M`D^" t 8 %.P/u"  2+D:zFR   bXd^ b63 4#4 #(*
q4 
q U -   *))%0***62***62%f59 %f59 rP   