
    FPh                     V   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mZ d dlZd dlZd dlZd dlmZ d dlmZ  e ej>                  dd            Z  e ej>                  d	d            Z! ee"      jG                         Z$e$jJ                  d
   Z&e&dz  Z'e&dz  Z( e)d e*d
 ejV                         d
z
              Z, e- ej>                  dd            j]                         dk(  Z/ e- ej>                  dd            j]                         dk(  Z0e0rdndZ1dZ2d dD        \  Z3Z4Z5 ejl                         dv Z7dZ8 ejr                  ddd        ejr                  dddjt                  i        ejv                  d         e-e,      ejx                  d<   d ejx                  d!<   d"ejx                  d#<    G d$ d%e      Z= G d& d'      Z> G d( d)e      Z?dad*Z@e2dfd+ZAdbd,ZB G d- d.ej                        ZD eAe2e0/        ej                  e2      ZFe5reFj                   eD               G d0 d1      ZHdcd2ZIddd3ZJd4ee-eeKf   d5dfd6ZL eJe(      ZMeMj                         D ](  \  ZOZP eQePe-      sePj]                         d7k(  s$deMeO<   * eMj                         ZS e?dei eMZTd5eUfd8ZVd9 ZWd: ZXd; ZYd5eUfd<ZZd5eUfd=Z[ e[       Z\e]fd>e-d5eUfd?Z^d@ee-ef   d5eUfdAZ_dB Z`d5eUfdCZadD ZbdE ZcdF ZddG ZedH ZfdI ZgdfdJZh e ej>                  dK      xs  eh             ZieidLz  ZjdM ZkdN Zl G dO dPe j                        ZndQ ZodR Zp G dS dTeK      ZqdgdUZrdV ZsdW Zt ekdX      Zu eq       Zv eevdY         Zw eevdZ         Zx eevd[         Zy eW       rd\n+ eX       rd]n" eY       rd^n eZ       rd_n ej                         Z{ e`       xs  ea       Z| ep        d
d`l}m~Z~mZmZmZ ee_        e5re~eece_~        e_        e_        yy)h    N)Path)SimpleNamespace)Union)tqdm)__version__RANK
LOCAL_RANK   assetszcfg/default.yaml   YOLO_AUTOINSTALLTtrueYOLO_VERBOSEz{l_bar}{bar:10}{r_bar}ultralyticsc              #   J   K   | ]  }t        j                         |k(    y wN)platformsystem).0xs     eC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/utils/__init__.py	<genexpr>r   )   s     X9WA*a/9Ws   !#)DarwinLinuxWindows)arm64aarch64a  
    Usage examples for running YOLOv8:

    1. Install the ultralytics package:

        pip install ultralytics

    2. Use the Python SDK:

        from ultralytics import YOLO

        # Load a model
        model = YOLO('yolov8n.yaml')  # build a new model from scratch
        model = YOLO("yolov8n.pt")  # load a pretrained model (recommended for training)

        # Use the model
        results = model.train(data="coco128.yaml", epochs=3)  # train the model
        results = model.val()  # evaluate model performance on the validation set
        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image
        success = model.export(format='onnx')  # export the model to ONNX format

    3. Use the command line interface (CLI):

        YOLOv8 'yolo' CLI commands use the following syntax:

            yolo TASK MODE ARGS

            Where   TASK (optional) is one of [detect, segment, classify]
                    MODE (required) is one of [train, val, predict, export]
                    ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
                        See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'

        - Train a detection model for 10 epochs with an initial learning_rate of 0.01
            yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01

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

        - Val a pretrained detection model at batch-size 1 and image size 640:
            yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640

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

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

    Docs: https://docs.ultralytics.com
    Community: https://community.ultralytics.com
    GitHub: https://github.com/ultralytics/ultralytics
    i@     default)	linewidth	precisionprofile
float_kindz{:11.5g})r!   	formatterNUMEXPR_MAX_THREADSz:4096:8CUBLAS_WORKSPACE_CONFIG2TF_CPP_MIN_LOG_LEVELc                   "     e Zd ZdZ fdZ xZS )TQDMz
    Custom Ultralytics tqdm class with different default arguments.

    Args:
        *args (list): Positional arguments passed to original tqdm.
        **kwargs (dict): Keyword arguments, with custom defaults applied.
    c                     t          xs |j                  dd      |d<   |j                  dt               t	        |   |i | y)zJInitialize custom Ultralytics tqdm class with different default arguments.disableF
bar_formatN)VERBOSEget
setdefaultTQDM_BAR_FORMATsuper__init__selfargskwargs	__class__s      r   r4   zTQDM.__init__w   sC     !(KG6::i+Gy,8$)&)    )__name__
__module____qualname____doc__r4   __classcell__r9   s   @r   r+   r+   n   s    * *r:   r+   c                   "    e Zd ZdZd Zd Zd Zy)SimpleClasszUltralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute
    access methods for easier debugging and usage.
    c                    g }t        |       D ]  }t        | |      }t        |      r|j                  d      r-t	        |t
              r*| d|j                   d|j                  j                   d}n| dt        |       }|j                  |        | j                   d| j                  j                   ddj                  |      z   S )<Return a human-readable string representation of the object._: .z objectz object with attributes:


)dirgetattrcallable
startswith
isinstancerB   r<   r9   r;   reprappendjoin)r6   attravss        r   __str__zSimpleClass.__str__   s    TAa AA;q||C'8a-#R~Qq{{/C/C.DGLA#RQy)AA  //"!DNN$;$;#<<XY\`\e\efj\kkkr:   c                 "    | j                         S )z>Return a machine-readable string representation of the object.)rU   r6   s    r   __repr__zSimpleClass.__repr__   s    ||~r:   c                 j    | j                   j                  }t        d| d| d| j                         )?Custom attribute access error message with helpful information.'' object has no attribute 'z'. See valid attributes below.
)r9   r;   AttributeErrorr>   r6   rQ   names      r   __getattr__zSimpleClass.__getattr__   s9    ~~&&q&A$Gghlhthtguvwwr:   N)r;   r<   r=   r>   rU   rX   r`    r:   r   rB   rB      s    lxr:   rB   c                   *    e Zd ZdZd Zd Zd ZddZy)IterableSimpleNamespacezUltralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and
    enables usage with dict() and for loops.
    c                 F    t        t        |       j                               S )zFReturn an iterator of key-value pairs from the namespace's attributes.)itervarsitemsrW   s    r   __iter__z IterableSimpleNamespace.__iter__   s    DJ$$&''r:   c                 `    dj                  d t        |       j                         D              S )rD   rH   c              3   0   K   | ]  \  }}| d |   yw)=Nra   )r   krS   s      r   r   z2IterableSimpleNamespace.__str__.<locals>.<genexpr>   s!     C0B1A3as0Bs   )rP   rf   rg   rW   s    r   rU   zIterableSimpleNamespace.__str__   s$    yyCT
0@0@0BCCCr:   c           	      `    | j                   j                  }t        d| d| dt         d      )rZ   z
            'r\   z'. This may be caused by a modified or out of date ultralytics
            'default.yaml' file.
Please update your code with 'pip install -U ultralytics' and if necessary replace
            z with the latest version from
            https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
            )r9   r;   r]   DEFAULT_CFG_PATHr^   s      r   r`   z#IterableSimpleNamespace.__getattr__   sD    ~~&& "V.tf 5   	r:   Nc                     t        | ||      S )zXReturn the value of the specified key if it exists; otherwise, return the default value.)rJ   )r6   keyr    s      r   r0   zIterableSimpleNamespace.get   s    tS'**r:   r   )r;   r<   r=   r>   rh   rU   r`   r0   ra   r:   r   rc   rc      s    (D+r:   rc   c                 "      ddi  fd}|S )ai  
    Decorator to temporarily set rc parameters and the backend for a plotting function.

    Example:
        decorator: @plt_settings({"font.size": 12})
        context manager: with plt_settings({"font.size": 12}):

    Args:
        rcparams (dict): Dictionary of rc parameters to set.
        backend (str, optional): Name of the backend to use. Defaults to 'Agg'.

    Returns:
        (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be
            applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.
    z	font.size   c                       fd}|S )zEDecorator to apply temporary rc parameters and backend to a function.c                  P   t        j                         }|k7  r*t        j                  d       t        j                         t        j                        5   | i |}ddd       |k7  r*t        j                  d       t        j                  |       S # 1 sw Y   :xY w)zWSets rc parameters and backend, calls the original function, and restores the settings.allN)pltget_backendcloseswitch_backend
rc_context)r7   r8   original_backendresultbackendfuncrcparamss       r   wrapperz0plt_settings.<locals>.decorator.<locals>.wrapper   s    "0**		% ""7+)t.v. * **		% ""#34M *)s   	BB%ra   )r~   r   r}   r   s   ` r   	decoratorzplt_settings.<locals>.decorator   s    	 r:   ra   )r   r}   r   s   `` r   plt_settingsr      s"    " $( r:   c                     t        t        j                  dd            }|r|dv rt        j                  nt        j
                  }t        j                  j                  dd| ddii| d| |d	i| || gdd
id       y)z#Sets up logging for the given name.r   r	   >   r   r	   r   Fformatz%(message)szlogging.StreamHandler)classr%   level)r   handlers	propagate)versiondisable_existing_loggers
formattersr   loggersN)intosgetenvloggingINFOERRORconfig
dictConfig)r_   verboserankr   s       r   set_loggingr      s    ryy$%D#GLLW]]ENN$)-)* 0! ! !F"$%& 'r:   c                 R    t         r | j                         j                  dd      S | S )z7Return platform-dependent emoji-safe version of string.asciiignore)WINDOWSencodedecode)strings    r   emojisr      s"    8?6==?!!'84KVKr:   c                   "     e Zd ZdZ fdZ xZS )EmojiFilterz
    A custom logging filter class for removing emojis in log messages.

    This filter is particularly useful for ensuring compatibility with Windows terminals that may not support the
    display of emojis in log messages.
    c                 V    t        |j                        |_        t        |   |      S )z3Filter logs by emoji unicode characters on windows.)r   msgr3   filter)r6   recordr9   s     r   r   zEmojiFilter.filter  s"    FJJ'
w~f%%r:   )r;   r<   r=   r>   r   r?   r@   s   @r   r   r      s    & &r:   r   )r   c                       e Zd ZdZd Zd Zy)ThreadingLockedaH  
    A decorator class for ensuring thread-safe execution of a function or method. This class can be used as a decorator
    to make sure that if the decorated function is called from multiple threads, only one thread at a time will be able
    to execute the function.

    Attributes:
        lock (threading.Lock): A lock object used to manage access to the decorated function.

    Example:
        ```python
        from ultralytics.utils import ThreadingLocked

        @ThreadingLocked()
        def my_function():
            # Your code here
            pass
        ```
    c                 6    t        j                         | _        y)zRInitializes the decorator class for thread-safe execution of a function or method.N)	threadingLocklockrW   s    r   r4   zThreadingLocked.__init__'  s    NN$	r:   c                 8     ddl m}  |       fd       }|S )z0Run thread-safe execution of function or method.r   )wrapsc                  X    j                   5   | i |cddd       S # 1 sw Y   yxY w)z:Applies thread-safety to the decorated function or method.N)r   )r7   r8   fr6   s     r   	decoratedz+ThreadingLocked.__call__.<locals>.decorated/  s#     $)&) s    ))	functoolsr   )r6   r   r   r   s   ``  r   __call__zThreadingLocked.__call__+  s$    #	q	* 
	*
 r:   N)r;   r<   r=   r>   r4   r   ra   r:   r   r   r     s    &%
r:   r   c           
         |i }t        |       } | j                  j                         s| j                  j                  dd       t        t
        t        t        t        t        t        t        d      f}|j                         D ]   \  }}t        ||      rt        |      ||<   " t        | ddd      5 }|r|j                  |       t!        j"                  ||dd	       ddd       y# 1 sw Y   yxY w)
a  
    Save YAML data to a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        data (dict): Data to save in YAML format.
        header (str, optional): YAML header to add.

    Returns:
        (None): Data is saved to the specified file.
    NTparentsexist_okwr   utf-8errorsencodingF	sort_keysallow_unicode)r   parentexistsmkdirr   floatstrboollisttupledicttyperg   rM   openwriteyaml	safe_dump)filedataheadervalid_typesrl   rS   r   s          r   	yaml_saver   8  s     |:D;;$6 uc4udDJFK

1![)!fDG 
 
dC7	;qGGFOtQ%tD 
<	;	;s   8-C..C7c                 R   t        |       j                  dv sJ d|  d       t        | dd      5 }|j                         }|j	                         st        j                  dd|      }t        j                  |      xs i }|rt        |       |d	<   |cd
d
d
       S # 1 sw Y   y
xY w)a  
    Load YAML data from a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.

    Returns:
        (dict): YAML data and file name.
    )z.yamlz.ymlz!Attempting to load non-YAML file z with yaml_load()r   r   r   zJ[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+ 	yaml_fileN)
r   suffixr   readisprintableresubr   	safe_loadr   )r   append_filenamer   rT   r   s        r   	yaml_loadr   X  s     : 11n5VW[V\\m3nn1	d8g	6!FFH }}dfhjklA ~~a &B #D	D 
7	6	6s   A"BB&r   returnc                     t        | t        t        f      rt        |       n| }t	        j
                  |dd      }t        j                  dt        dd|        d|        y)	z
    Pretty prints a YAML file or a YAML-formatted dictionary.

    Args:
        yaml_file: The file path of the YAML file or a YAML-formatted dictionary.

    Returns:
        None
    FTr   z
Printing 'boldblackz'

N)	rM   r   r   r   r   dumpLOGGERinfocolorstr)r   	yaml_dictr   s      r   
yaml_printr   r  sS     )39sDk(J	)$PYI99Y%tDD
KK*XfgyAB%vNOr:   nonec                      t        j                  t              5  t        d      5 } d| j	                         v cddd       cddd       S # 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w)zi
    Check if the OS is Ubuntu.

    Returns:
        (bool): True if OS is Ubuntu, False otherwise.
    /etc/os-releasez	ID=ubuntuNF)
contextlibsuppressFileNotFoundErrorr   r   r   s    r   	is_ubuntur     s[     
		.	/#$!&&(* %$ 
0	/$$$ 
0  
0 s!   A!A	A!A	A!!A*c                  N    dt         j                  v xs dt         j                  v S )z
    Check if the current script is running inside a Google Colab notebook.

    Returns:
        (bool): True if running inside a Colab notebook, False otherwise.
    COLAB_RELEASE_TAGCOLAB_BACKEND_VERSIONr   environra   r:   r   is_colabr     s"     "**,U0G2::0UUr:   c                      t         j                  j                  d      dk(  xr" t         j                  j                  d      dk(  S )z
    Check if the current script is running inside a Kaggle kernel.

    Returns:
        (bool): True if running inside a Kaggle kernel, False otherwise.
    PWDz/kaggle/workingKAGGLE_URL_BASEzhttps://www.kaggle.com)r   r   r0   ra   r:   r   	is_kaggler     s6     ::>>% $55w"**..IZ:[_w:wwr:   c                  ~    t        j                  t              5  ddlm}   |        ducddd       S # 1 sw Y   yxY w)z
    Check if the current script is running inside a Jupyter Notebook. Verified on Colab, Jupyterlab, Kaggle, Paperspace.

    Returns:
        (bool): True if running inside a Jupyter Notebook, False otherwise.
    r   get_ipythonNF)r   r   	ExceptionIPythonr   r   s    r   
is_jupyterr     s0     
		Y	''}D( 
(	'	' s   3<c                      t        d      } | j                         r't        |       5 }d|j                         v cddd       S y# 1 sw Y   yxY w)z
    Determine if the script is running inside a Docker container.

    Returns:
        (bool): True if the script is running inside a Docker container, False otherwise.
    z/proc/self/cgroupdockerNF)r   r   r   r   )r   r   s     r   	is_dockerr    sC     #$D{{}$Z1qvvx' Z  Zs   AAc                      ddl } dD ])  }	 | j                  |dfd      }|j                           y y# | j                  | j                  t
        f$ r Y Ow xY w)	z
    Check internet connectivity by attempting to connect to a known online host.

    Returns:
        (bool): True if connection is successful, False otherwise.
    r   N)z1.1.1.1z8.8.8.8z	223.5.5.55      )addresstimeoutTF)socketcreate_connectionrx   r  gaierrorOSError)r  hosttest_connections      r   	is_onliner    si     1	$66bzST6UO
 !!# 2  9 		s   4 AAfilepathc                 h    ddl }|j                  j                  |       }|duxr |j                  duS )z
    Determines if the file at the given filepath is part of a pip package.

    Args:
        filepath (str): The filepath to check.

    Returns:
        (bool): True if the file is part of a pip package, False otherwise.
    r   N)importlib.utilutil	find_specorigin)r  	importlibspecs      r   is_pip_packager    s8      >>##H-D t74 77r:   dir_pathc                 \    t        j                  t        |       t         j                        S )z
    Check if a directory is writeable.

    Args:
        dir_path (str | Path): The path to the directory.

    Returns:
        (bool): True if the directory is writeable, False otherwise.
    )r   accessr   W_OK)r  s    r   is_dir_writeabler    s     99S]BGG,,r:   c                      dt         j                  v xs< dt        j                  v xs( dt	        t        j
                  d         j                  v S )z
    Determines whether pytest is currently running or not.

    Returns:
        (bool): True if pytest is running, False otherwise.
    PYTEST_CURRENT_TESTpytestr   )r   r   sysmodulesr   argvstemra   r:   r   is_pytest_runningr#    sE     "RZZ/uX5LuRZ^bcfckcklmcn^o^t^tRtur:   c                  v    dt         j                  v xr& dt         j                  v xr dt         j                  v S )z
    Determine if the current environment is a GitHub Actions CI Python runner.

    Returns:
        (bool): True if the current environment is a GitHub Actions CI Python runner, False otherwise.
    GITHUB_ACTIONS	RUNNER_OSRUNNER_TOOL_CACHEr   ra   r:   r   is_github_actions_cir(  	  s3     rzz)mkRZZ.GmL_cecmcmLmmr:   c                      t               duS )z
    Determines whether the current file is part of a git repository. If the current file is not part of a git
    repository, returns None.

    Returns:
        (bool): True if current file is part of a git repository.
    N)get_git_dirra   r:   r   
is_git_dirr+    s     =$$r:   c                  n    t        t              j                  D ]  } | dz  j                         s| c S  y)a  
    Determines whether the current file is part of a git repository and if so, returns the repository root directory. If
    the current file is not part of a git repository, returns None.

    Returns:
        (Path | None): Git root directory if found or None if not found.
    z.gitN)r   __file__r   is_dir)ds    r   r*  r*    s-     (^##J H $r:   c                      t               rbt        j                  t        j                        5  t        j
                  g d      } | j                         j                         cddd       S y# 1 sw Y   yxY w)z
    Retrieves the origin URL of a git repository.

    Returns:
        (str | None): The origin URL of the git repository or None if not git directory.
    )gitr   z--getzremote.origin.urlNr+  r   r   
subprocessCalledProcessErrorcheck_outputr   stripr  s    r   get_git_origin_urlr8  +  sU     |  !>!>?,,-\]F==?((* @? ??   5A..A7c                      t               rbt        j                  t        j                        5  t        j
                  g d      } | j                         j                         cddd       S y# 1 sw Y   yxY w)z
    Returns the current git branch name. If not in a git repository, returns None.

    Returns:
        (str | None): The current git branch name or None if not a git directory.
    )r1  z	rev-parsez--abbrev-refHEADNr2  r7  s    r   get_git_branchr<  8  sU     |  !>!>?,,-YZF==?((* @? ??r9  c                     t        j                  |       }|j                  j                         D ci c]9  \  }}|j                  t         j
                  j                  us-||j                  ; c}}S c c}}w )a  
    Returns a dictionary of default arguments for a function.

    Args:
        func (callable): The function to inspect.

    Returns:
        (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
    )inspect	signature
parametersrg   r    	Parameterempty)r~   r?  rl   rS   s       r   get_default_argsrC  E  sa     !!$'I%.%9%9%?%?%An%ATQQYYV]VgVgVmVmEmAqyyL%Annns   .A5"A5c                  $   t               rdt        j                  t        t              5  t        d      5 } t        j                  d| j                               d   cddd       cddd       S y# 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w)z
    Retrieve the Ubuntu version if the OS is Ubuntu.

    Returns:
        (str): Ubuntu version or None if not an Ubuntu OS.
    r   zVERSION_ID="(\d+\.\d+)"r   N)	r   r   r   r   r]   r   r   searchr   r   s    r   get_ubuntu_versionrF  S  sl     {  !2NC'(Ayy!;QVVXFqI )( DC ((( DCCs"   B'A0	B0A9	5BBc                    t         rt        j                         dz  dz  | z  }net        rt        j                         dz  dz  | z  }nAt        rt        j                         dz  | z  }n t        dt        j                                t        |j                        sMt        j                  d| d       t        d	      rt        d	      | z  nt               j                         | z  }|j                  d
d
       |S )z
    Get the user config directory.

    Args:
        sub_dir (str): The name of the subdirectory to create.

    Returns:
        (Path): The path to the user config directory.
    AppDataRoamingLibraryzApplication Supportz.configzUnsupported operating system: u&   WARNING ⚠️ user config directory 'z' is not writeable, defaulting to '/tmp' or CWD.Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path.z/tmpTr   )r   r   homeMACOSLINUX
ValueErrorr   r   r  r   r   warningcwdr   )sub_dirpaths     r   get_user_config_dirrS  `  s     yy{Y&2W<	yy{Y&)>>H	yy{Y&09(//:K9LMNN DKK(?v Fl l 	m)9&)AtF|g%tvzz|V]G] 	JJtdJ+Kr:   YOLO_CONFIG_DIRzsettings.yamlc                      t        |       dkD  r| ndd| d   f^ }}i ddddd	d
ddddddddddddddddddddddd d!d"d#d$d%d&d'd(d)j                  fd*|D              | z   d$   z   S )+a]  
    Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes.
    See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.

    This function can be called in two ways:
        - colorstr('color', 'style', 'your string')
        - colorstr('your string')

    In the second form, 'blue' and 'bold' will be applied by default.

    Args:
        *input (str): A sequence of strings where the first n-1 strings are color and style arguments,
                      and the last string is the one to be colored.

    Supported Colors and Styles:
        Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
        Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
                       'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
        Misc: 'end', 'bold', 'underline'

    Returns:
        (str): The input string wrapped with ANSI escape codes for the specified color and style.

    Examples:
        >>> colorstr('blue', 'bold', 'hello world')
        >>> '[34m[1mhello world[0m'
    r   bluer   r   r   z[30mredz[31mgreenz[32myellowz[33mz[34mmagentaz[35mcyanz[36mwhitez[37mbright_blackz[90m
bright_redz[91mbright_greenz[92mbright_yellowz[93mbright_bluez[94mbright_magentaz[95mbright_cyanz[96mbright_whitez[97mendz[0mz[1mz[4m)r   	underliner   c              3   (   K   | ]	  }|     y wr   ra   )r   r   colorss     r   r   zcolorstr.<locals>.<genexpr>  s     +d6!9ds   )lenrP   )inputr7   r   rh  s      @r   r   r     s(   8 !Z!^E&&%(1KMT6  z  	  	*	 
 	
  	:  	
  	  	
  	j  	
  	  	z  	*  	z   	
! " 	y# $ ' F( 77+d++9F5MIIr:   c                 P    t        j                  d      }|j                  d|       S )a\  
    Removes ANSI escape codes from a string, effectively un-coloring it.

    Args:
        input_string (str): The string to remove color and style from.

    Returns:
        (str): A new string with all ANSI escape codes removed.

    Examples:
        >>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))
        >>> 'hello world'
    z&\x1B(?:[@-Z\\\-_]|\[[0-9]*[ -/]*[@-~])r   )r   compiler   )input_stringansi_escapes     r   remove_colorstrro    s$     **FGK??2|,,r:   c                   $    e Zd ZdZddZd Zd Zy)	TryExceptzl
    YOLOv8 TryExcept class.

    Use as @TryExcept() decorator or 'with TryExcept():' context manager.
    c                      || _         || _        y)zHInitialize TryExcept class with optional message and verbosity settings.N)r   r   )r6   r   r   s      r   r4   zTryExcept.__init__  s    r:   c                      y)z?Executes when entering TryExcept context, initializes instance.Nra   rW   s    r   	__enter__zTryExcept.__enter__  s    r:   c                     | j                   r4|r2t        t        | j                   | j                  rdnd |              y)zPDefines behavior when exiting a 'with' block, prints error message if necessary.rF   r   T)r   printr   r   )r6   exc_typevalue	tracebacks       r   __exit__zTryExcept.__exit__  s5    <<E&DHH:dhhdB%?wGHIr:   N)r   T)r;   r<   r=   r>   r4   rt  rz  ra   r:   r   rq  rq    s    
r:   rq  c                       fd}|S )z^
    Multi-threads a target function and returns thread.

    Use as @threaded decorator.
    c                  Z    t        j                  | |d      }|j                          |S )z6Multi-threads a given function and returns the thread.T)targetr7   r8   daemon)r   Threadstart)r7   r8   threadr~   s      r   r   zthreaded.<locals>.wrapper  s(    !!DPTUr:   ra   )r~   r   s   ` r   threadedr    s     Nr:   c            
         d } t         d   rt        dv rt        t        j                  d         j
                  dk(  rt        st        rt               rt               s	 ddl
}|j                  ddd	t        d
| t        t        g       |j!                  dt         d   i       dD ]4  }t#        j$                  |      j'                  t"        j(                         6 yyyyyyyy# t        $ r Y yw xY w)a  
    Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and
    sync=True in settings. Run 'yolo settings' to see and update settings YAML file.

    Conditions required to send errors (ALL conditions must be met or no errors will be reported):
        - sentry_sdk package is installed
        - sync=True in YOLO settings
        - pytest is not running
        - running in a pip package installation
        - running in a non-git directory
        - running with rank -1 or 0
        - online environment
        - CLI used to run package (checked with 'yolo' as the name of the main CLI command)

    The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError
    exceptions and to exclude events with 'out of memory' in their exception message.

    Additionally, the function sets custom tags and user information for Sentry events.
    c                    d|v r%|d   \  }}}|t         t        fv sdt        |      v ryt        j                  d   t        t        j                  d         j                  t               rdnt               rdndt        d| d	<   | S )
a  
        Modify the event before sending it to Sentry based on specific exception types and messages.

        Args:
            event (dict): The event dictionary containing information about the error.
            hint (dict): A dictionary containing additional information about the error.

        Returns:
            dict: The modified event or None if the event should not be sent to Sentry.
        exc_infozout of memoryNr   r1  pipother)sys_argvsys_argv_nameinstallr   tags)
KeyboardInterruptr   r   r  r!  r   r_   r+  r  ENVIRONMENT)eventhintrw  	exc_valuetbs        r   before_sendzset_sentry.<locals>.before_send  s     &*:&6#Hi-/@AA&#i.8 !#((1+.33 *u>;K%QX	f
 r:   sync)r	   r   r   yoloNz\https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016Fg      ?
production)dsndebugtraces_sample_ratereleaseenvironmentr  ignore_errorsiduuid)
sentry_sdkzsentry_sdk.errors)SETTINGSr   r   r  r!  r_   TESTS_RUNNINGONLINEr  r+  r  ImportErrorinitr   r  r   set_userr   	getLoggersetLevelCRITICAL)r  r  loggers      r   
set_sentryr    s    *0 GO!""f,	 	n"$#,.?@ 	 	B 	T8F#345 8Ff%..w/?/?@ 8'     -    		s   C$ $	C0/C0c                   H     e Zd ZdZedf fd	Z fdZd Z fdZd Z	 xZ
S )SettingsManagera-  
    Manages Ultralytics settings stored in a YAML file.

    Args:
        file (str | Path): Path to the Ultralytics settings YAML file. Default is USER_CONFIG_DIR / 'settings.yaml'.
        version (str): Settings version. In case of local version mismatch, new default settings will be saved.
    z0.0.4c           	         ddl }ddl}ddlm} ddlm} t               }|xs
 t               }|r!t        |j                        r|j                  n|j                         }	t        |      | _        || _        i d|dt        |	dz        dt        |d	z        d
t        |dz        d|j                  t        t        j                                j#                               j%                         dddddddddddddddddddddd| _        t(        | U  |j-                  | j&                                |t.              5  | j                  j1                         s| j3                          | j5                          | j7                         | j&                  j7                         k(  }
t9        d t;        | j=                         | j&                  j=                               D              } || d   | j                        }|
r|r|s3t>        jA                  d| j                   d       | jC                          ddd       y# 1 sw Y   yxY w)z}Initialize the SettingsManager with default settings, load and validate current settings from the YAML
        file.
        r   N)check_version)torch_distributed_zero_firstsettings_versiondatasets_dirdatasetsweights_dirweightsruns_dirrunsr  r  Tapi_keyr   clearmlcometdvchubmlflowneptuneraytunetensorboardwandbc              3   N   K   | ]  \  }}t        |      t        |      u   y wr   )r   )r   rR   bs      r   r   z+SettingsManager.__init__.<locals>.<genexpr>n  s$     j?itq!Q47 2?is   #%u   WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem with your settings or a recent ultralytics package update. 
View settings with 'yolo settings' or at 'z\'
Update settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'.)"copyhashlibultralytics.utils.checksr  ultralytics.utils.torch_utilsr  r*  r   r  r   resolver   r   r   sha256r  getnoder   	hexdigestdefaultsr3   r4   deepcopyr   r   saveloadkeysru   zipvaluesr   rO  reset)r6   r   r   r  r  r  r  git_dirrootdatasets_rootcorrect_keyscorrect_typescorrect_versionr9   s                r   r4   zSettingsManager.__init__D  sN    	:N- $&(/4DT[[4QW[ddfJ	C
 :; 3ti/0 D6M*	
 GNN3t||~#6#=#=#?@JJL D r t T 4 4 d t t 4  T!$ 	t}}56)$/99##%		IIK99;$--*<*<*>>Ljs4;;=RVR_R_RfRfRh?ijjM+D1C,DdllSO ]CCG99+ Nsst
 

 0//s   C7IIc                 J    t         |   t        | j                               y)z"Loads settings from the YAML file.N)r3   updater   r   )r6   r9   s    r   r  zSettingsManager.loadx  s    y+,r:   c                 B    t        | j                  t        |              y)z,Saves the current settings to the YAML file.N)r   r   r   rW   s    r   r  zSettingsManager.save|  s    $))T$Z(r:   c                 D    t        |   |i | | j                          y)z0Updates a setting value in the current settings.N)r3   r  r  r5   s      r   r  zSettingsManager.update  s    ''		r:   c                 z    | j                          | j                  | j                         | j                          y)z.Resets the settings to default and saves them.N)clearr  r  r  rW   s    r   r  zSettingsManager.reset  s$    

DMM"		r:   )r;   r<   r=   r>   SETTINGS_YAMLr4   r  r  r  r  r?   r@   s   @r   r  r  ;  s)     *7 2h-)
r:   r  c           	      p    |st        t        dd       dz   }t        j                  d|  d| d| d       y)z_Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.N   g?u   WARNING ⚠️ 'z4' is deprecated and will be removed in 'ultralytics z' in the future. Please use 'z
' instead.)r   r   r   rO  )argnew_argr   s      r   deprecation_warnr    sH    BQ(3.
NN%cU*^_f^g h"")*6 7r:   c                     t        |       j                         j                  dd      } t        j                  j                  |       j                  d      d   S )zTStrip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.z:/z://?r   )r   as_posixreplaceurllibparseunquotespliturls    r   	clean_urlr    sF    
s)



&
&tU
3C<<$**3/22r:   c                 >    t        t        |             j                  S )zHConvert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.)r   r  r_   r  s    r   url2filer    s    	#$$$r:   zUltralytics: r  r  r  ColabKaggleJupyterDocker)imreadimshowimwrite
torch_save)NAgg)r   )	data.yamlNr   )r  Fra   )Ultralyticsr   )r   r>  logging.configr   r   r   r   r3  r  r   r  r  pathlibr   typesr   typingr   cv2matplotlib.pyplotpyplotrv   numpynptorchr   r   tqdm_originalr   r   r   r   r   r
   r-  r  FILEr   ROOTASSETSrn   minmax	cpu_countNUM_THREADSr   lowerAUTOINSTALLr/   r2   LOGGING_NAMErL  rM  r   machineARM64HELP_MSGset_printoptionsr   setNumThreadsr   r+   rB   rc   r   r   r   Filterr   r  r   	addFilterr   r   r   r   r   DEFAULT_CFG_DICTrg   rl   rS   rM   r  DEFAULT_CFG_KEYSDEFAULT_CFGr   r   r   r   r   r  r  r  r;   r  r  r#  r(  r+  r*  r8  r<  rC  rF  rS  USER_CONFIG_DIRr  r   ro  ContextDecoratorrq  r  r  r  r  r  r  PREFIXr  DATASETS_DIRWEIGHTS_DIRRUNS_DIRr   r  r  patchesr  r  r  r  r  ra   r:   r   <module>r"     s      	  	  
     !  
     & # 9299VR !<,-
 H~||A	,, !SLBLLNQ./0)")).56<<>&H
ibii-
.
4
4
6&
@.5*4X9WX ug227 	v   9 E   clJ<M<M-N O   ! $'$4

  !(1

$ %%(

! "*= *"x x:+o +8(V "4 ',L
&'.. & L' *			<	(

[]#" "JE@4P%T40 PT P  -. ""$DAq!Saggi61" % $((* %9(89
4 
Vx
4 4 * 
 $, 8S 8 8&
-uS$Y/ 
-D 
-vnd n%

+
+o
J@ yryy!23L7J7LM/11Jh-$
++ . GATNd Nb73% 
/	"H^,-8M*+$%!gY[S]S_iH!2 !#=';'= 
 9 8

*0'6'CJSZ r:   