o
    Wht                     @   s  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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/ e$j0d dfd	d
Z1d`de2fddZ3de4fddZ5daddZ6						dbde7de7de7de4de4de7de4fddZ8dcd!d"Z9d#d$ Z:e) ddd&d'Z;ded*e7de4de4de4fd+d,Z<e* e$j0d d-d)dfd.d/Z=d0d1 Z>dfd4d5Z?dgd6e7de4fd7d8Z@dhd:d;ZAdid=d>ZBdjd@dAZCdBdC ZDdkdDdEZEdldFdGZFdHdI ZGdJdK ZHe$fdLdMZIdmdNeeJ fdOdPZKdeLfdQdRZMde4fdSdTZNdUdV ZOde4fdWdXZPe<dYdd)dZ e>  e"QdYZRe"Qd[ZSe"Qd\ZTe"Qd]ZUe<d^dd_ZVe<d\dd_ZWdS )n    N)metadata)Path)SimpleNamespace)Optional)ARM64ASSETSAUTOINSTALLIS_COLAB
IS_GIT_DIR	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                 C   s   |rdd t |jD }nt|   }g }|D ]3}| }|rM|dsM|dd  }t	
d| }rM|t|d |d rH|d  ndd	 q|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:
        (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                 S   s   g | ]}d |vr|qS )z	extra ==  .0xr    r    L/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/checks.py
<listcomp>C       z&parse_requirements.<locals>.<listcomp>#r   z ([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?      r   name	specifier)r   distributionrequiresr   	read_text
splitlinesstrip
startswithsplitrematchappendr   )	file_pathpackager.   requirementsliner5   r    r    r$   parse_requirements3   s   *r;   0.0.0returnc              
   C   s^   zt tttd| dd W S  ty. } ztd|  d|  W Y d}~dS d}~ww )a9  
    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[int, int, int]): 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intr4   findall	Exceptionr   warning)versioner    r    r$   parse_versionR   s   
 rG   c                 C   s   t d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                 s   s    | ]	}t |d k V  qdS )   N)ord)r"   cr    r    r$   	<genexpr>m       zis_ascii.<locals>.<genexpr>)allstr)sr    r    r$   is_asciic   s   
rP       r(   r)   c                    s`  t ttjr nt| t r| g} n-t| ttfr#t| } n!t| tr6|  r1t | gnt	| } nt
d|  dt| j dt| |krld}|dkrZtd|  d| tdt|  d	|  t| g}  fd
d| D }|| krtd|  d d|  |dkrt|dkr|d |d g}|S |dkrt|dkr|d }|S |}|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                    s$   g | ]}t t|   qS r    )maxmathceilr!   floorstrider    r$   r%      s   $ zcheck_imgsz.<locals>.<listcomp>z  must be multiple of max stride z, updating to r)   r   )rA   
isinstancetorchTensorrR   listr?   rN   	isnumericeval	TypeErrortype__name__len
ValueErrorr   rD   )imgszrW   min_dimmax_dimrV   msgszr    rU   r$   check_imgszp   s4   



$rh   rE   Fcurrentrequiredr+   hardverboserf   c              
   C   s  | st d|  d| d dS | d  s>z	| }t| } W n tjy= } z|r2t|  d|W Y d}~dS d}~ww |sBdS d	|v r^trLd
|vs\trRd|vs\t	r^d|vr^d|vr^dS d}d}d}	t
| }
|ddD ]U}td| \}}|sd}t
|}|dkr|
|krd}	qp|dkr|
|krd}	qp|dkr|
|ksd}	qp|dkr|
|ksd}	qp|dkr|
|ksd}	qp|dkr|
|k sd}	qp|	s| | d| d|  d| }|rt||rt | |	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 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   rD   isdigitr   rE   PackageNotFoundErrorModuleNotFoundErrorr   r   r   rG   r1   r3   r4   r5   groups)ri   rj   r+   rk   rl   rf   rF   oprE   resultrJ   rvrD   r    r    r$   check_version   sn   #
r~   ultralyticsc                 C   sZ   z"t jj  t jd|  ddd}|jdkr | d d W S W dS  ty,   Y dS w )	z
    Returns 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.
    zhttps://pypi.org/pypi/z/jsonr>   )timeout   inforE   N)requestspackagesurllib3disable_warningsgetstatus_codejsonrC   )package_nameresponser    r    r$   check_latest_pypi_version   s   

r   c                  C   sb   t r/tr/z ddlm}  t }t| d| r"td| d W dS W dS  ty.   Y dS w dS )z
    Checks if a new version of the ultralytics package is available on PyPI.

    Returns:
        (bool): True if an update is available, False otherwise.
    r   )__version__ru   z)New https://pypi.org/project/ultralytics/u8    available 😃 Update with 'pip install -U ultralytics'TF)	r   r   r   r   r   r~   r   r   rC   )r   latestr    r    r$   check_pip_update_available  s    
r   	Arial.ttfc                    s~   ddl m} t j}t| }| r|S  fdd| D }t|r(|d S d| }tj	|ddr=tj
||d |S d	S )
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_managerc                    s   g | ]} |v r|qS r    r    )r"   rO   fontr    r$   r%   <  r&   zcheck_font.<locals>.<listcomp>z?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)r   r   r+   r   matchesr   r    r   r$   
check_font(  s   

r   3.8.0Tminimumc                 C   s   t t| d||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+   rk   rl   )r~   r   )r   rk   rl   r    r    r$   check_pythonG  s   r   r    c                    s  t ddd}t| tr)|  }| sJ | d| d fddt|D } nt| tr1| g} g }| D ]A}|dd	 d
d}t	
d|}	|	d |	d rU|	d  nd}
}ztt|
|sdJ W q5 ttjfyv   || Y q5w tddddd }ddd |D }|r|r
tr
t|}t| dd|dk  d| d zAt }tsJ dt||| t | }t| d|dd| dd|dk  d| 	 t| dt dd d W d"S  ty	 } zt| d|  W Y d }~d!S d }~ww d!S d"S )#a  
    Check if installed dependencies meet YOLOv8 requirements and attempt to auto-update if needed.

    Args:
        requirements (Union[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[str]): 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.c                    s&   g | ]}|j  vr|j  |j qS r    r*   r!   excluder    r$   r%   r  s   & z&check_requirements.<locals>.<listcomp>/z.gitr   z([a-zA-Z0-9-_]+)([<>!=~]+.*)?r(   r)   )timesdelayc                 S   s   t jd|  d| dd S )z4Attempt pip install command with retries on failure.zpip install --no-cache-dir r   Tshell)
subprocesscheck_outputdecode)r   commandsr    r    r$   attempt_install  s   z+check_requirements.<locals>.attempt_installc                 s   s    | ]	}d | d V  qdS )"Nr    r!   r    r    r$   rK     rL   z%check_requirements.<locals>.<genexpr>z Ultralytics requirementrO   z$ not found, attempting AutoUpdate...zAutoUpdate skipped (offline)u    AutoUpdate success ✅ .1fzs, installed z package: z;Restart runtime or rerun command for updates to take effect
u    ❌ NFT)r   rX   r   resolver   r;   rN   r3   replacer4   r5   r1   r~   r   rE   AssertionErrorrw   r6   r   joinr   ra   r   r   timer   rD   rC   )r9   r   installcmdsprefixr   pkgsr|   
r_strippedr5   r+   rj   r   rO   ntdtrF   r    r   r$   check_requirementsV  sR   

"

$0	r   c               
      s   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 }|| v r^| | }d tdd ddd  t fdd|D r`td  d| d|d  d dS dS dS )a2  
    Checks 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.21z0.20z0.19z0.18z0.17z0.16z0.15z0.14z0.13)	z2.6z2.5z2.4z2.3z2.2z2.1z2.0z1.13z1.12.+r   Nr)   c                 3   s    | ]} |kV  qd S )Nr    )r"   r}   v_torchvisionr    r$   rK     s    z$check_torchvision.<locals>.<genexpr>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   rY   r   r3   r   rM   r   rD   )compatibility_tablev_torchcompatible_versionsr    r   r$   check_torchvision  s,   $"r   
yolo11n.pt.ptc                 C   s   | r:|r<t |tr|f}t | ttfr| n| gD ]%}t|j  }t|r9||v s9J | | d| d| qdS dS dS )a  
    Check file(s) for acceptable suffix.

    Args:
        file (str | List[str]): File or list of files to check.
        suffix (str | Tuple[str]): Acceptable suffix or tuple of suffixes.
        msg (str): Additional message to display in case of error.
    z acceptable suffix is z, not N)	rX   rN   r[   r?   r   suffixlowerr1   ra   )r   r   rf   frO   r    r    r$   check_suffix  s   	
$r   r   c                 C   s   d| v sd| v rEd| v r|  dd} | S d| v rEd| vrE| }tdd| } td	d| } td
d| } | |krE|rEt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   r4   subr   r   )r   rl   original_filer    r    r$   check_yolov5u_filename  s   r   yolo11nc                 C   s0   | rt | jst | jtjv rt | 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)modelr    r    r$   check_model_file_from_stem  s   
r   r   c                 C   s.  t | | t|  } t| } | r"d| vrt|  s"|  dr$| S |rX|  drX| }t|t|  } |  rLt	
dt| d|   t| S tj|| dd t| S tjttd |  d	d
pntttj|  }|s{|r{td|  dt|dkr|rtd|  d| t|r|d S g S )a  
    Search/download file (if necessary) and return path.

    Args:
        file (str): File name or path.
        suffix (str): File suffix to check.
        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   rN   r1   r   r   r   r   r2   r   r   r   r   r   r   globr   parentFileNotFoundErrorra   )r   r   downloaddownload_dirrk   r   filesr    r    r$   
check_file  s.   
.r   r   z.ymlc                 C   s   t | ||dS )a5  
    Search/download YAML file (if necessary) and return path, checking suffix.

    Args:
        file (str): File name or path.
        suffix (tuple): Acceptable file suffixes.
        hard (bool): Whether to raise an error if the file is not found.

    Returns:
        (str): Path to the YAML file.
    rk   )r   )r   r   rk   r    r    r$   
check_yaml#  s   r   c                 C   s:   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   partsra   )basedirpathbase_dir_resolvedpath_resolvedr    r    r$   check_is_path_safe2  s   "r   c              
   C   s   z.t rtstr	J dtjv sJ dtdtjdtj	d t
d t  t
d W dS  tyK } z| r@td|  W Y d	}~d
S d	}~w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destroyAllWindowsrC   r   rD   )warnrF   r    r    r$   check_imshowC  s   


r  c              	   C   s   ddl }ddlm} trtjddd | rVd}| j}td\}}}d	t	
  d
|| dd|| | dd|| dd	}	zddlm}
 |
  W n tyU   Y nw d}	||dd td|	  dS )z
    Return a human-readable YOLO software and hardware summary.

    Args:
        verbose (bool): Whether to print verbose information.
        device (str): 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   )rl   r  r
  r  gibramr  usedfreerO   r  r    r    r$   
check_yolo\  s$   
8r  c                  C   s  ddl } ddlm} ddlm}m} d}totj }t	  t
d\}}}t |ttr/dntr3dnd	tt|  j| d
d|| | dd|| dd| t |r\|ddnd|rdtj nd|rktjjndd}	tdddd |	 D  d  i }
tddD ]C}zt|j}t|t|j |jddrdnd}W n tj!y   d}d}Y nw | | |j  |
|j< t|jd|
|j   q|
|	d< t" rt#dt#dt#dt#dt#dt#d d!}tddd"d | D   ||	d#< |	S )$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                 s   s"    | ]\}}|d | V  qdS )<20Nr    r"   kr}   r    r    r$   rK          z&collect_system_info.<locals>.<genexpr>r   )r8   T)r+   rk   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/  r0  r1  r2  c                 s   s"    | ]\}}| d | V  qdS )r   Nr    r*  r    r    r$   rK     r,  zGitHub Info)$r
  ultralytics.utilsr  r  r  r  rY   cudais_availabler  r  r  platformr   r
   r   rN   r   r  r  r   r  device_countrE   r   r   r   itemsr;   r   r+   r~   r,   rw   r   getenv)r
  r  r  r  r  r4  r  r  r  	info_dictpackage_infor|   ri   is_metgithub_infor    r    r$   collect_system_info~  sX   &$"r>  c              	      sH  ddl m  t jtd}jdv rdS tdtj	}t
j}t||r9t| d| d dS  fd	d
}td }t| d d}zddlm} ||d|s_J t| d W dS  ty}   t| d|  Y dS  ttfy   t| d|  Y dS  ty   t| d Y dS w )a|  
    Checks the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO11 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 (nn.Module): A YOLO11 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                    s   |gd }t dtj  d }| ||ddd jj} dd | ||ddd jj}W d	   n1 s9w   Y  ~ |j|jkoNtj|| d
dS )zAll close FP32 vs AMP results.r         F)rc   r  rl   r   T)enabledNg      ?)atol)	rR   rA   rW   boxesdatashaperY   allclosefloat)mimbatchrc   abr?  r  r   r    r$   amp_allclose  s   
 zcheck_amp.<locals>.amp_allclosez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 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  r?  next
parametersr  r   r_   r4   compile
IGNORECASErY   r4  get_device_nameboolsearchr   rD   r   r   r   rR  ConnectionErrorAttributeErrorrx   r   error)r   r   patterngpurQ  rL  warning_msgrR  r    rP  r$   	check_amp  sN   


r`  c                 C   s:   zt jd|  ddd dd W S  ty   Y dS 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   )r   r   r   rC   )r   r    r    r$   git_describe  s
   
$ra  argsc           	         s   dd t  j}t |\}}}}} du r+t |\ }}} fdd| D  zt| t	
d}W n tyG   t|j}Y nw |rO| dnd|rW| dnd }tt|dfd	d
  D   dS )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                 S   s,   t | tr| drt| dkrt| S | S )zTClean longer Ultralytics HUB URLs by stripping potential authentication information.httpd   )rX   rN   r2   ra   r   )r}   r    r    r$   
strip_auth  s   ,zprint_args.<locals>.strip_authNc                    s   i | ]\}}| v r||qS r    r    r*  )rb  r    r$   
<dictcomp>&  s    zprint_args.<locals>.<dictcomp>r   r   rm   c                 3   s&    | ]\}}| d  | V  qdS )=Nr    r*  )re  r    r$   rK   ,  s   $ zprint_args.<locals>.<genexpr>)inspectcurrentframef_backgetframeinfogetargvaluesr8  r   r   relative_tor   r   rb   r   r   r   r   r   )	rb  	show_file	show_funcr#   r   _funcfrmrO   r    )rb  re  r$   
print_args  s   

$.rs  c               
   C   sL   zt jg ddd} |  dd }t|W S  t jttfy%   Y dS 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   r1   r3   rA   CalledProcessErrorr   rb   )output
first_liner    r    r$   cuda_device_count/  s   
rx  c                   C   s
   t  dkS )z
    Check if CUDA is available in the environment.

    Returns:
        (bool): True if one or more NVIDIA GPUs are available, False otherwise.
    r   )rx  r    r    r    r$   cuda_is_availableE  s   
ry  c                  C   s   t rGtrGz8td&} |  }|d^ }}|ddtv r(	 W d   W dS W d   n1 s2w   Y  W dS W dS  tyF   Y dS w dS )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/compatiblers    r   NTF)r   r   openreadr3   r   r   OSError)r   dev_strrp  socr    r    r$   is_rockchipO  s   
(r  c                  C   s(   t rdS d} tj| dtjtjd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   stdoutstderrr   )r   r   runDEVNULL
returncode)cmdr    r    r$   is_sudo_availablec  s   r  z3.8)rk   rl   z3.11z3.12z3.13z3.10r   )r<   )rQ   r(   r)   r   )r<   r<   rE   FFr   )r   )r   )r   TF)r   r   r   )T)r   )r   Tr   T)r   T)F)Tr   )NTF)Xr   rh  rS   r   r6  r4   r  r   r   	importlibr   pathlibr   typesr   typingr   r   numpyr   r   rY   r3  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?   rG   rX  rP   rh   rN   r~   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r>  r`  ra  dictrs  rA   rx  ry  r  r  r2   IS_PYTHON_3_8IS_PYTHON_3_11IS_PYTHON_3_12IS_PYTHON_3_13IS_PYTHON_MINIMUM_3_10IS_PYTHON_MINIMUM_3_12r    r    r    r$   <module>   s   l
7

XE
!


(

"=I




