
    |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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m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m Z m!Z!m"Z"  e# ejH                  d	d
            Z% e# ejH                  dd
            Z&e
jN                  xs ddgZ( ee)      jU                         Z+e+jX                  d   Z-e-dz  Z.dZ/e-dz  Z0 e1d e2d ejf                         dz
              Z4 e5 ejH                  dd            jm                         dk(  Z7 e5 ejH                  dd            jm                         dk(  Z8e8rdndZ9dZ:d dD        \  Z;Z<Z=e;r ej|                         d    ndZ? ej                         dv ZA ej                         ZCej:                  ZDej                  j                  d      ZGej                  j                  dd      dk(  ZJ eKh d      ZLd ZM ej                  d!d"d#$        ej                  d! eOd%j                  &      '        ej                  d         e5e4      ej                  d(<   d)ej                  d*<   d+ej                  d,<   d-ej                  d.<    e5 ejH                  d/d            jm                         dk(  xZRrd d0lmSZS  G d1 d2eRreSj6                  nej6                        ZT G d3 d4      ZU G d5 d6      ZV G d7 d8e      ZWdud9ZXdvd:ZY eYe:e8;      ZZd<D ]0  Z[ ej                  e[      j                  ej                  dz          2 dwd=Z_ G d> d?      Z` G d@ dA      Zaeaj                  e0      Zcecj                         Ze eWdxi ecZfdBe5fdCZgdBehfdDZidE ZjdF ZkdG ZldH ZmdBehfdIZndBehfdJZodBehfdKZpdBehfdLZqerfdMe5dBehfdNZsdOee5ef   dBehfdPZtdQ ZudBehfdRZvdS ZwdT ZxdU ZydV ZzdW Z{dX Z|dydYZ} eg       Z~ eq       Z ej       Z ek       Z en       Z ep       Z el       Z es       Z eo       Z ew       Z ex       Z e ejH                  dZ      xs  e}             Zed[z  Zd\ Zd] Z G d^ d_e j                        Z G d` dae j                        Zdb Zdc Z G dd deeO      Z G df dge      ZdzdhZdi Zdj Zd{dBe5fdkZ edl      Z e       Z eedmz        Z eedn         Z eedo         Z eedp         Zerdqnerdrnerdsnerdtn ej<                         Z eu       xs  ev       Z e        e"e_        e=ree!e ce_        e_!        e_         yy)|    N)Path)Lock)SimpleNamespace)Union)unquote)__version__)imreadimshowimwrite
torch_saveRANK
LOCAL_RANK    assetsz>https://github.com/ultralytics/assets/releases/download/v0.0.0z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     Y/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/__init__.py	<genexpr>r   .   s     XA*a/Xs   !#)DarwinLinuxWindows>   arm64aarch64torchvisionTERM_PROGRAMFvscode>
   rk2118rk3562rk3566rk3568rk3576rk3588rv1103rv1106rv1103brv1106ba  
    Examples for running Ultralytics:

    1. Install the ultralytics package:

        pip install ultralytics

    2. Use the Python SDK:

        from ultralytics import YOLO

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

        # Use the model
        results = model.train(data="coco8.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):

        Ultralytics 'yolo' CLI commands use the following syntax:

            yolo TASK MODE ARGS

            Where   TASK (optional) is one of [detect, segment, classify, pose, obb]
                    MODE (required) is one of [train, val, predict, export, track, benchmark]
                    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=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01

        - Predict a YouTube video using a pretrained segmentation model at image size 320:
            yolo segment predict model=yolo11n-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=yolo11n.pt data=coco8.yaml batch=1 imgsz=640

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

        - 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profilez{:11.5g})
float_kind)r4   	formatterNUMEXPR_MAX_THREADS3TF_CPP_MIN_LOG_LEVELERRORTORCH_CPP_LOG_LEVEL5KINETO_LOG_LEVELYOLO_TQDM_RICH)richc                   ,     e Zd ZdZ fdZ fdZ xZS )TQDMa  
    A custom TQDM progress bar class that extends the original tqdm functionality.

    This class modifies the behavior of the original tqdm progress bar based on global settings and provides
    additional customization options for Ultralytics projects. The progress bar is automatically disabled when
    VERBOSE is False or when explicitly disabled.

    Attributes:
        disable (bool): Whether to disable the progress bar. Determined by the global VERBOSE setting and
            any passed 'disable' argument.
        bar_format (str): The format string for the progress bar. Uses the global TQDM_BAR_FORMAT if not
            explicitly set.

    Methods:
        __init__: Initialize the TQDM object with custom settings.
        __iter__: Return self as iterator to satisfy Iterable interface.

    Examples:
        >>> from ultralytics.utils import TQDM
        >>> for i in TQDM(range(100)):
        ...     # Your processing code here
        ...     pass
    c                     t        j                  dt        j                         t         xs |j                  dd      |d<   |j                  dt               t        | $  |i | y)a  
        Initialize a custom TQDM progress bar with Ultralytics-specific settings.

        Args:
            *args (Any): Variable length argument list to be passed to the original tqdm constructor.
            **kwargs (Any): Arbitrary keyword arguments to be passed to the original tqdm constructor.

        Notes:
            - The progress bar is disabled if VERBOSE is False or if 'disable' is explicitly set to True in kwargs.
            - The default bar format is set to TQDM_BAR_FORMAT unless overridden in kwargs.

        Examples:
            >>> from ultralytics.utils import TQDM
            >>> for i in TQDM(range(100)):
            ...     # Your code here
            ...     pass
        ignore)categorydisableF
bar_formatN)
warningsfilterwarningstqdmTqdmExperimentalWarningVERBOSEget
setdefaultTQDM_BAR_FORMATsuper__init__selfargskwargs	__class__s      r   rR   zTQDM.__init__   sY    $ 	43O3OP 'KG6::i+Gy,8$)&)    c                      t         |          S )z6Return self as iterator to satisfy Iterable interface.)rQ   __iter__rT   rW   s    r   rZ   zTQDM.__iter__   s    w!!rX   )__name__
__module____qualname____doc__rR   rZ   __classcell__rW   s   @r   rC   rC      s    0*." "rX   rC   c                   H    e Zd ZdZd
dZd
dZd
dZddZd
dZd
dZ	ddZ
y	)DataExportMixina  
    Mixin class for exporting validation metrics or prediction results in various formats.

    This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results
    from classification, object detection, segmentation, or pose estimation tasks into various formats: Pandas
    DataFrame, CSV, XML, HTML, JSON and SQLite (SQL).

    Methods:
        to_df: Convert summary to a Pandas DataFrame.
        to_csv: Export results as a CSV string.
        to_xml: Export results as an XML string (requires `lxml`).
        to_html: Export results as an HTML table.
        to_json: Export results as a JSON string.
        tojson: Deprecated alias for `to_json()`.
        to_sql: Export results to an SQLite database.

    Examples:
        >>> model = YOLO("yolo11n.pt")
        >>> results = model("image.jpg")
        >>> df = results.to_df()
        >>> print(df)
        >>> csv_data = results.to_csv()
        >>> results.to_sql(table_name="yolo_results")
    c                 N    ddl }|j                  | j                  ||            S )ag  
        Create a pandas DataFrame from the prediction results summary or validation metrics.

        Args:
            normalize (bool, optional): Normalize numerical values for easier comparison.
            decimals (int, optional): Decimal places to round floats.

        Returns:
            (DataFrame): DataFrame containing the summary data.
        r   N	normalizedecimals)pandas	DataFramesummary)rT   rf   rg   pds       r   to_dfzDataExportMixin.to_df   s#     	||DLL9xLPQQrX   c                 D    | j                  ||      j                         S )z
        Export results to CSV string format.

        Args:
           normalize (bool, optional): Normalize numeric values.
           decimals (int, optional): Decimal precision.

        Returns:
           (str): CSV content as string.
        re   )rl   to_csvrT   rf   rg   s      r   rn   zDataExportMixin.to_csv   s      zzIzAHHJJrX   c                 h    | j                  ||      }|j                  rdS |j                  d      S )a/  
        Export results to XML format.

        Args:
            normalize (bool, optional): Normalize numeric values.
            decimals (int, optional): Decimal precision.

        Returns:
            (str): XML string.

        Notes:
            Requires `lxml` package to be installed.
        re   z4<?xml version="1.0" encoding="utf-8"?>
<root></root>etree)parser)rl   emptyto_xml)rT   rf   rg   dfs       r   rt   zDataExportMixin.to_xml   s8     ZZ)hZ?JL((FqXZXaXaipXaXqqrX   c                 h    | j                  ||      }|j                  rdS |j                  |      S )a`  
        Export results to HTML table format.

        Args:
            normalize (bool, optional): Normalize numeric values.
            decimals (int, optional): Decimal precision.
            index (bool, optional): Whether to include index column in the HTML table.

        Returns:
            (str): HTML representation of the results.
        re   z<table></table>)index)rl   rs   to_html)rT   rf   rg   rw   ru   s        r   rx   zDataExportMixin.to_html  s3     ZZ)hZ?$&HH I"**5*2IIrX   c                 P    t         j                  d       | j                  ||      S )z Deprecated version of to_json().zA'result.tojson()' is deprecated, replace with 'result.to_json()'.)LOGGERwarningto_jsonro   s      r   tojsonzDataExportMixin.tojson  s     Z[||Ix00rX   c                 J    | j                  ||      j                  dd      S )a  
        Export results to JSON format.

        Args:
            normalize (bool, optional): Normalize numeric values.
            decimals (int, optional): Decimal precision.

        Returns:
            (str): JSON-formatted string of the results.
        re   records   )orientindent)rl   r|   ro   s      r   r|   zDataExportMixin.to_json  s)     zzIzAIIQZcdIeerX   c           
      8   | j                  ||      }|j                  s|j                  j                  ryddl}|j	                  |      }|j                         }g }	|j                  D ]  }
||
   j                         j                  s ||
   j                         j                  d   nd}t        |t              rd}nt        |t        t        f      rd}nd}|	j                  d|
 d|         |j                  d| d       |j                  d	| d
dj                  |	       d       |j                         D ]  \  }}|D cg c])  }t        |t              rt!        j"                  |      n|+ }}dj                  d |j                  D              }dj                  d |j                  D              }|j                  d| d| d| d|        |j%                          |j'                          t(        j+                  d| d| d       yc c}w )a>  
        Save results to an SQLite database.

        Args:
            normalize (bool, optional): Normalize numeric values.
            decimals (int, optional): Decimal precision.
            table_name (str, optional): Name of the SQL table.
            db_path (str, optional): SQLite database file path.
        Nr   r   TEXTREAL"z" zDROP TABLE IF EXISTS "zCREATE TABLE "z)" (id INTEGER PRIMARY KEY AUTOINCREMENT, z, )c              3   (   K   | ]
  }d | d   yw)r   N )r   cols     r   r   z)DataExportMixin.to_sql.<locals>.<genexpr>K  s     $FCqQZ$Fs   c              3       K   | ]  }d   yw)?Nr   )r   _s     r   r   z)DataExportMixin.to_sql.<locals>.<genexpr>L  s     $=QS$=s   zINSERT INTO "z" (z
) VALUES (zResults saved to SQL table 'z' in 'z'.)rl   rs   columnssqlite3connectcursordropnailoc
isinstancedictfloatintappendexecutejoiniterrowsjsondumpscommitcloserz   info)rT   rf   rg   
table_namedb_pathru   r   connr   r   r   
sample_valcol_typer   rowvvaluescolumn_namesplaceholderss                      r   to_sqlzDataExportMixin.to_sql&  s    ZZ	8,88rzz''w' :: 	2C9;C9I9O9OC)..q1UWJ*d+!J5!!NNQse2hZ01	2 	/
|1=>
|3\]a]f]fgn]o\ppqrskkm 	kFAsKNOaz!T':djjmAOFO99$F2::$FFL99$="**$==LNN]:,c,zR^Q__`acij		k 	

2:,fWIRPQ Ps   .HN)F   )Fr   F)Fr   resultsz
results.db)r\   r]   r^   r_   rl   rn   rt   rx   r}   r|   r   r   rX   r   rc   rc      s0    2RKr"J1
f+RrX   rc   c                   "    e Zd ZdZd Zd Zd Zy)SimpleClassa  
    A simple base class for creating objects with string representations of their attributes.

    This class provides a foundation for creating objects that can be easily printed or represented as strings,
    showing all their non-callable attributes. It's useful for debugging and introspection of object states.

    Methods:
        __str__: Return a human-readable string representation of the object.
        __repr__: Return a machine-readable string representation of the object.
        __getattr__: Provide a custom attribute access error message with helpful information.

    Examples:
        >>> class MyClass(SimpleClass):
        ...     def __init__(self):
        ...         self.x = 10
        ...         self.y = "hello"
        >>> obj = MyClass()
        >>> print(obj)
        __main__.MyClass object with attributes:

        x: 10
        y: 'hello'

    Notes:
        - This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
        - The string representation includes the module and class name of the object.
        - Callable attributes and attributes starting with an underscore are excluded from the string representation.
    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.r   : .z objectz object with attributes:


)dirgetattrcallable
startswithr   r   r]   rW   r\   reprr   r   )rT   attrar   ss        r   __str__zSimpleClass.__str__r  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krX   c                 "    | j                         S )z>Return a machine-readable string representation of the object.)r   rT   s    r   __repr__zSimpleClass.__repr__  s    ||~rX   c                 j    | j                   j                  }t        d| d| d| j                         )IProvide a custom attribute access error message with helpful information.'' object has no attribute 'z'. See valid attributes below.
)rW   r\   AttributeErrorr_   rT   r   names      r   __getattr__zSimpleClass.__getattr__  s9    ~~&&q&A$GghlhthtguvwwrX   N)r\   r]   r^   r_   r   r   r   r   rX   r   r   r   T  s    :lxrX   r   c                   *    e Zd ZdZd Zd Zd ZddZy)IterableSimpleNamespacea  
    An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.

    This class extends the SimpleNamespace class with additional methods for iteration, string representation,
    and attribute access. It is designed to be used as a convenient container for storing and accessing
    configuration parameters.

    Methods:
        __iter__: Return an iterator of key-value pairs from the namespace's attributes.
        __str__: Return a human-readable string representation of the object.
        __getattr__: Provide a custom attribute access error message with helpful information.
        get: Retrieve the value of a specified key, or a default value if the key doesn't exist.

    Examples:
        >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
        >>> for k, v in cfg:
        ...     print(f"{k}: {v}")
        a: 1
        b: 2
        c: 3
        >>> print(cfg)
        a=1
        b=2
        c=3
        >>> cfg.get("b")
        2
        >>> cfg.get("d", "default")
        'default'

    Notes:
        This class is particularly useful for storing configuration parameters in a more accessible
        and iterable format compared to a standard dictionary.
    c                 F    t        t        |       j                               S )zFReturn an iterator of key-value pairs from the namespace's attributes.)itervarsitemsr   s    r   rZ   z IterableSimpleNamespace.__iter__  s    DJ$$&''rX   c                 `    dj                  d t        |       j                         D              S )r   r   c              3   0   K   | ]  \  }}| d |   yw)=Nr   )r   kr   s      r   r   z2IterableSimpleNamespace.__str__.<locals>.<genexpr>  s     C1A3asCs   )r   r   r   r   s    r   r   zIterableSimpleNamespace.__str__  s$    yyCT
0@0@0BCCCrX   c           	      `    | j                   j                  }t        d| d| dt         d      )r   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
            )rW   r\   r   DEFAULT_CFG_PATHr   s      r   r   z#IterableSimpleNamespace.__getattr__  sD    ~~&&V.tf 5 
 	
rX   Nc                     t        | ||      S )zXReturn the value of the specified key if it exists; otherwise, return the default value.)r   )rT   keyr3   s      r   rN   zIterableSimpleNamespace.get  s    tS'**rX   r   )r\   r]   r^   r_   rZ   r   r   rN   r   rX   r   r   r     s     D(D

+rX   r   c                 "      ddi  fd}|S )a  
    Decorator to temporarily set rc parameters and the backend for a plotting function.

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

    Returns:
        (Callable): Decorated function with temporarily set rc parameters and backend.

    Examples:
        >>> @plt_settings({"font.size": 12})
        >>> def plot_function():
        ...     plt.figure()
        ...     plt.plot([1, 2, 3])
        ...     plt.show()

        >>> with plt_settings({"font.size": 12}):
        ...     plt.figure()
        ...     plt.plot([1, 2, 3])
        ...     plt.show()
    z	font.size   c                       fd}|S )zEDecorator to apply temporary rc parameters and backend to a function.c                     ddl m} |j                         }j                         |j                         k7  }|r"|j	                  d       |j                         	 |j                        5   | i |}ddd       |r"|j	                  d       |j                  |       S # 1 sw Y   /xY w# |r#|j	                  d       |j                  |       w w xY w)zTSet rc parameters and backend, call the original function, and restore the settings.r   Nall)matplotlib.pyplotpyplotget_backendlowerr   switch_backend
rc_context)	rU   rV   pltoriginal_backendswitchresultbackendfuncrcparamss	         r   wrapperz0plt_settings.<locals>.decorator.<locals>.wrapper  s    +"0]]_(8(>(>(@@F		% ""7+9^^H- 3!4262F3 IIe$&&'78M3 3 IIe$&&'78 s$   B2 /	B&8B2 &B/+B2 2'Cr   )r   r   r   r   s   ` r   	decoratorzplt_settings.<locals>.decorator  s    	( rX   r   )r   r   r   s   `` r   plt_settingsr     s"    . $2 rX   c                 V   |rt         dv rt        j                  nt        j                  } G d dt        j                        } |d      }t
        rt        t        j                  d      rt        j                  j                  dk7  r	 t        t        j                  d      r!t        j                  j                  d       nRt        t        j                  d	      r8d
dl}|j                  t        j                  j                  d      t        _        t        j                  t        j                        }|j!                  |       |j#                  |       t        j$                  |       }|j#                  |       |j'                  |       d|_        |S # t        $ r Y w xY w)a  
    Set up logging with UTF-8 encoding and configurable verbosity.

    This function configures logging for the Ultralytics library, setting the appropriate logging level and
    formatter based on the verbosity flag and the current process rank. It handles special cases for Windows
    environments where UTF-8 encoding might not be the default.

    Args:
        name (str): Name of the logger.
        verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise.

    Returns:
        (logging.Logger): Configured logger object.

    Examples:
        >>> set_logging(name="ultralytics", verbose=True)
        >>> logger = logging.getLogger("ultralytics")
        >>> logger.info("This is an info message")

    Notes:
        - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
        - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
        - The function sets up a StreamHandler with the appropriate formatter and level.
        - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
       r   r   c                        e Zd Z fdZ xZS )$set_logging.<locals>.PrefixFormatterc                 .   |j                   t        j                  k(  r!t        sdnd}| d|j                   |_        n=|j                   t        j
                  k(  r t        sdnd}| d|j                   |_        t        |   |      }t        |      S )z0Format log records with prefixes based on level.u   WARNING ⚠️WARNING u	   ERROR ❌r<   )	levelnologgingr   WINDOWSmsgr<   rQ   formatemojis)rT   recordprefixformatted_messagerW   s       r   r   z+set_logging.<locals>.PrefixFormatter.format  s     ~~018)i &xq5
7==0,3 &xq5
 !&v 6+,,rX   )r\   r]   r^   r   r`   ra   s   @r   PrefixFormatterr     s    	- 	-rX   r   z%(message)sencodingutf-8reconfigurer   bufferr   NF)r   r   INFOr<   	Formatterr   hasattrsysstdoutr   r   ioTextIOWrapperr  	ExceptionStreamHandlersetFormattersetLevel	getLogger
addHandler	propagate)r   verboselevelr   r8   r  stream_handlerloggers           r   set_loggingr    s5   4 $GLLW]]E-'++ -  .I 73::z2szz7J7Jg7U
	szz=1

&&&8X.--cjj.?.?'-R

 **3::6N	*E" t$F
OOE
n%FM  		s   
BF 	F('F()r  )
sentry_sdkzurllib3.connectionpoolc                 R    t         r | j                         j                  dd      S | S )z7Return platform-dependent emoji-safe version of string.asciirE   )r   encodedecode)strings    r   r   r   J  s"    8?6==?!!'84KVKrX   c                       e Zd ZdZd Zd Zy)ThreadingLockeda)  
    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.

    Examples:
        >>> from ultralytics.utils import ThreadingLocked
        >>> @ThreadingLocked()
        >>> def my_function():
        ...    # Your code here
    c                 6    t        j                         | _        y)z5Initialize the decorator class with a threading lock.N)	threadingr   lockr   s    r   rR   zThreadingLocked.__init__`  s    NN$	rX   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)z8Apply thread-safety to the decorated function or method.N)r  )rU   rV   frT   s     r   	decoratedz+ThreadingLocked.__call__.<locals>.decoratedh  s.      *$)&)* * *s    ))	functoolsr!  )rT   r#  r!  r$  s   ``  r   __call__zThreadingLocked.__call__d  s$    #	q	* 
	*
 rX   Nr\   r]   r^   r_   rR   r&  r   rX   r   r  r  O  s     %
rX   r  c                   ^    e Zd ZdZdZed        Zd Zedd       Zed	d       Z	ed        Z
y)
YAMLa  
    YAML utility class for efficient file operations with automatic C-implementation detection.

    This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation
    (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method
    usage without explicit instantiation. The class handles file path creation, validation, and character encoding
    issues automatically.

    The implementation prioritizes performance through:
        - Automatic C-based loader/dumper selection when available
        - Singleton pattern to reuse the same instance
        - Lazy initialization to defer import costs until needed
        - Fallback mechanisms for handling problematic YAML content

    Attributes:
        _instance: Internal singleton instance storage.
        yaml: Reference to the PyYAML module.
        SafeLoader: Best available YAML loader (CSafeLoader if available).
        SafeDumper: Best available YAML dumper (CSafeDumper if available).

    Examples:
        >>> data = YAML.load("config.yaml")
        >>> data["new_value"] = 123
        >>> YAML.save("updated_config.yaml", data)
        >>> YAML.print(data)
    Nc                 J    | j                    |        | _         | j                   S )z+Initialize singleton instance on first use.)	_instance)clss    r   _get_instancezYAML._get_instance  s!     == ECM}}rX   c                     ddl }|| _         	 |j                  | _        |j                  | _        y# t
        t        f$ r% |j                  | _        |j                  | _        Y yw xY w)zEInitialize with optimal YAML implementation (C-based when available).r   N)yamlCSafeLoader
SafeLoaderCSafeDumper
SafeDumperr   ImportError)rT   r/  s     r   rR   zYAML.__init__  sU    		."..DO"..DO, 	."ooDO"ooDO	.s   "0 1A$#A$c           
         | j                         }|i }t        |      }|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                  |       |j                   j#                  ||dd|j$                  	       ddd       y# 1 sw Y   yxY w)
z
        Save Python object as YAML file.

        Args:
            file (str | Path): Path to save YAML file.
            data (dict | None): Dict or compatible object to save.
            header (str): Optional string to add at file beginning.
        NTparentsexist_okwrE   r   errorsr   F)	sort_keysallow_unicodeDumper)r-  r   parentmkdirr   r   strboollisttupler   typer   r   openwriter/  dumpr3  )	r,  filedataheaderinstancevalid_typesr   r   r#  s	            r   savez	YAML.save  s     $$&<D Dz$6 5#tT5$T
JJJL 	!DAqa-a&Q	!
 $Hw? 	i1MMtQ%tT\TgTgh	i 	i 	is   .>C55C>c                 r   | j                         }t        |      j                  d      s
J d|        t        |dd      5 }|j	                         }ddd       	 |j
                  j                  |j                        xs i }d
|j                         v r*|j                         D ci c]  \  }}||d
k(  rdn| }}}|rt        |      |d<   |S # 1 sw Y   xY w# t        $ rE t        j                  dd	      }|j
                  j                  ||j                        xs i }Y w xY wc c}}w )a  
        Load YAML file to Python object with robust error handling.

        Args:
            file (str | Path): Path to YAML file.
            append_filename (bool): Whether to add filename to returned dict.

        Returns:
            (dict): Loaded YAML content.
        )z.yamlz.ymlzNot a YAML file: rE   r   r:  N)LoaderzJ[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+r   None	yaml_file)r-  rA  endswithrF  readr/  loadr1  r	  resubr   r   )	r,  rI  append_filenamerL  r#  r   rJ  r   r   s	            r   rU  z	YAML.load  s2    $$&4y!!"34P8I$6PP4 $x': 	aA		K==%%a0C0C%DJD T[[]">BjjlKdaAqF{t1KDK #D	D#	 	  	KdfhjklA==%%a0C0C%DJD	K Ls%   C+C" -D3C"AD0/D0c                    | j                         }t        |t        t        f      r| j	                  |      n|}|j
                  j                  |ddd|j                        }t        j                  dt        dd|       d|        y	)
z
        Pretty print YAML file or object to console.

        Args:
            yaml_file (str | Path | dict): Path to YAML file or dict to print.
        FTr   )r<  r=  widthr>  z
Printing 'boldblackz'

N)r-  r   rA  r   rU  r/  rH  r3  rz   r   colorstr)r,  rR  rL  	yaml_dictrH  s        r   printz
YAML.print  s~     $$& ,6i#t+MCHHY'S\	 }}!!)uDXZckcvcv!wj&'9!E FeD6RSrX   )	data.yamlNr   )r`  F)r\   r]   r^   r_   r+  classmethodr-  rR   rN  rU  r_  r   rX   r   r)  r)  q  sf    6 I . i i:    D T TrX   r)  returnc                  F    t        j                         j                         S )z
    Read the device model information from the system and cache it for quick access.

    Returns:
        (str): Kernel release information.
    )r   releaser   r   rX   r   read_device_modelre    s     ##%%rX   c                      	 t        d      5 } d| j                         v cddd       S # 1 sw Y   yxY w# t        $ r Y yw xY w)zi
    Check if the OS is Ubuntu.

    Returns:
        (bool): True if OS is Ubuntu, False otherwise.
    /etc/os-releasez	ID=ubuntuNF)rF  rT  FileNotFoundErrorr#  s    r   	is_ubunturj    sF    #$ 	+!&&(*	+ 	+ 	+ s#   5 )	5 25 5 	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osenvironr   rX   r   is_colabrq    s"     "**,U0G2::0UUrX   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)ro  rp  rN   r   rX   r   	is_kaggleru    s6     ::>>% $55w"**..IZ:[_w:wwrX   c                      t         xs t        S )a  
    Check if the current script is running inside a Jupyter Notebook.

    Returns:
        (bool): True if running inside a Jupyter Notebook, False otherwise.

    Notes:
        - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
        - "get_ipython" in globals() method suffers false positives when IPython package installed manually.
    )IS_COLAB	IS_KAGGLEr   rX   r   
is_jupyterry  )  s      y rX   c                  &    dt         j                  v S )z
    Check if the current script is running inside a RunPod container.

    Returns:
        (bool): True if running in RunPod, False otherwise.
    RUNPOD_POD_IDrn  r   rX   r   	is_runpodr|  7  s     bjj((rX   c                  `    	 t         j                  j                  d      S # t        $ r Y yw 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/.dockerenvF)ro  pathexistsr	  r   rX   r   	is_dockerr  A  s,    ww~~m,, s   ! 	--c                      dt         v S )z
    Determine if the Python environment is running on a Raspberry Pi.

    Returns:
        (bool): True if running on a Raspberry Pi, False otherwise.
    rpiDEVICE_MODELr   rX   r   is_raspberrypir  N  s     L  rX   c                      dt         v S )z
    Determine if the Python environment is running on an NVIDIA Jetson device.

    Returns:
        (bool): True if running on an NVIDIA Jetson device, False otherwise.
    tegrar  r   rX   r   	is_jetsonr  X  s     l""rX   c                      	 t        t        j                  dd            j                         dk7  sJ ddl} dD ]&  }| j                  |dfd	      j                           y
 y# t        $ r Y yw 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.
    YOLO_OFFLINEr   r   r   N)z1.1.1.1z8.8.8.8P   g       @)addresstimeoutTF)rA  ro  getenvr   socketcreate_connectionr   r	  )r  dnss     r   	is_onliner  b  sw    299^R01779VCCC) 	C$$c2Y$DJJL	  s   AA$ "A$ $	A0/A0filepathc                 h    ddl }|j                  j                  |       }|duxr |j                  duS )z
    Determine 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  t  s8      >>##H-D t74 77rX   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.
    )ro  accessrA  W_OK)r  s    r   is_dir_writeabler    s     99S]BGG,,rX   c                      dt         j                  v xs2 dt        j                  v xs dt	        t
        d         j                  v S )z
    Determine whether pytest is currently running or not.

    Returns:
        (bool): True if pytest is running, False otherwise.
    PYTEST_CURRENT_TESTpytestr   )ro  rp  r  modulesr   ARGVstemr   rX   r   is_pytest_runningr    s?     "RZZ/qX5LqRZ^bcghicj^k^p^pRpqrX   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 runner.

    Returns:
        (bool): True if the current environment is a GitHub Actions runner, False otherwise.
    GITHUB_ACTIONSGITHUB_WORKFLOW	RUNNER_OSrn  r   rX   r   is_github_action_runningr    s4     rzz)k.?2::.MkR]acakakRkkrX   c                  n    t        t              j                  D ]  } | dz  j                         s| c S  y)z
    Determine whether the current file is part of a git repository and if so, return the repository root directory.

    Returns:
        (Path | None): Git root directory if found or None if not found.
    z.gitN)r   __file__r7  is_dir)ds    r   get_git_dirr    s2     (^## J HrX   c                      t         duS )z
    Determine whether the current file is part of a git repository.

    Returns:
        (bool): True if current file is part of a git repository.
    N)GIT_DIRr   rX   r   
is_git_dirr    s     $rX   c                      t         r6	 t        j                  g d      } | j                         j	                         S y# t        j
                  $ r Y yw xY w)z
    Retrieve the origin URL of a git repository.

    Returns:
        (str | None): The origin URL of the git repository or None if not git directory.
    )gitconfigz--getzremote.origin.urlN
IS_GIT_DIR
subprocesscheck_outputr  stripCalledProcessErrorr  s    r   get_git_origin_urlr    sQ     	,,-\]F==?((**  ,, 		   4> AAc                      t         r6	 t        j                  g d      } | j                         j	                         S y# t        j
                  $ r Y yw xY w)z
    Return the current git branch name. If not in a git repository, return None.

    Returns:
        (str | None): The current git branch name or None if not a git directory.
    )r  z	rev-parsez--abbrev-refHEADNr  r  s    r   get_git_branchr    sQ     	,,-YZF==?((**  ,, 		r  c                     t        j                  |       }|j                  j                         D ci c]9  \  }}|j                  t         j
                  j                  us-||j                  ; c}}S c c}}w )a  
    Return 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
parametersr   r3   	Parameterrs   )r   r  r   r   s       r   get_default_argsr    s[     !!$'I%.%9%9%?%?%AnTQQYYV]VgVgVmVmEmAqyyLnnns   .A5"A5c                      t               r=	 t        d      5 } t        j                  d| j	                               d   cddd       S y# 1 sw Y   yxY w# t
        t        f$ r Y yw xY w)z
    Retrieve the Ubuntu version if the OS is Ubuntu.

    Returns:
        (str): Ubuntu version or None if not an Ubuntu OS.
    rg  zVERSION_ID="(\d+\.\d+)"r   N)rj  rF  rV  searchrT  rh  r   ri  s    r   get_ubuntu_versionr    sm     {	'( JAyy!;QVVXFqIJ J J J!>2 		s-   A 'A		A 	AA A A'&A'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
    Return the appropriate config directory based on the environment operating system.

    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: z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/tmpTr6  )r   r   homeMACOSLINUX
ValueErrorr   r   r  r?  rz   r{   cwdr@  )sub_dirr~  s     r   get_user_config_dirr    s     yy{Y&2W<	yy{Y&)>>H	yy{Y&09(//:K9LMNN DKK(%dV ,a a	
 *:&)AtF|g%tvzz|V]G] 	JJtdJ+KrX   YOLO_CONFIG_DIRzsettings.jsonc                      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|  
    Color a string based on the provided color and style arguments using ANSI escape codes.

    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 | Path): 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.

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

    Notes:
        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'

    Examples:
        >>> colorstr("blue", "bold", "hello world")
        >>> "\033[34m\033[1mhello world\033[0m"

    References:
        https://en.wikipedia.org/wiki/ANSI_escape_code
    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   r   )r   r   colorss     r   r   zcolorstr.<locals>.<genexpr>_  s     +6!9+s   )lenr   )inputrU   r  r  s      @r   r]  r]  *  s(   > !Z!^E&&%(1KMT6z 	 	*	
 	
 	: 	
 	 	
 	j 	
 	 	z 	* 	z  	
!" 	y#$ 'F* 77+d++9F5MIIrX   c                 P    t        j                  d      }|j                  d|       S )a[  
    Remove 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\[[0-9;]*[A-Za-z]r   )rV  compilerW  )input_stringansi_escapes     r   remove_colorstrr  b  s$     **56K??2|,,rX   c                   $    e Zd ZdZddZd Zd Zy)	TryExcepta"  
    Ultralytics TryExcept class for handling exceptions gracefully.

    This class can be used as a decorator or context manager to catch exceptions and optionally print warning messages.
    It allows code to continue execution even when exceptions occur, which is useful for non-critical operations.

    Attributes:
        msg (str): Optional message to display when an exception occurs.
        verbose (bool): Whether to print the exception message.

    Examples:
        As a decorator:
        >>> @TryExcept(msg="Error occurred in func", verbose=True)
        >>> def func():
        >>> # Function logic here
        >>>     pass

        As a context manager:
        >>> with TryExcept(msg="Error occurred in block", verbose=True):
        >>> # Code block here
        >>>     pass
    c                      || _         || _        y)zHInitialize TryExcept class with optional message and verbosity settings.N)r   r  )rT   r   r  s      r   rR   zTryExcept.__init__  s    rX   c                      y)z=Execute when entering TryExcept context, initialize instance.Nr   r   s    r   	__enter__zTryExcept.__enter__  s    rX   c                     | j                   r5|r3t        j                  | j                   | j                  rdnd |        y)zNDefine behavior when exiting a 'with' block, print error message if necessary.r   r   T)r  rz   r{   r   )rT   exc_typevalue	tracebacks       r   __exit__zTryExcept.__exit__  s4    <<ENNdhhZb'A%IJrX   N)r   T)r\   r]   r^   r_   rR   r  r  r   rX   r   r  r  t  s    .
rX   r  c                       e Zd ZdZddZd Zy)Retrya  
    Retry class for function execution with exponential backoff.

    This decorator can be used to retry a function on exceptions, up to a specified number of times with an
    exponentially increasing delay between retries. It's useful for handling transient failures in network
    operations or other unreliable processes.

    Attributes:
        times (int): Maximum number of retry attempts.
        delay (int): Initial delay between retries in seconds.

    Examples:
        Example usage as a decorator:
        >>> @Retry(times=3, delay=2)
        >>> def test_func():
        >>> # Replace with function logic that may raise exceptions
        >>>     return True
    c                 .    || _         || _        d| _        y)zBInitialize Retry class with specified number of retries and delay.r   N)timesdelay	_attempts)rT   r  r  s      r   rR   zRetry.__init__  s    

rX   c                       fd}|S )z<Decorator implementation for Retry with exponential backoff.c            	         d_         j                   j                  k  r
	  | i |S yy# t        $ r}xj                   dz  c_         t        j	                  dj                    dj                   d|        j                   j                  k\  r|t        j                  j                  dj                   z  z         Y d}~nd}~ww xY wj                   j                  k  r̌)z2Apply retries to the decorated function or method.r   r   zRetry /z	 failed: r   N)r  r  r	  rz   r{   timesleepr  )rU   rV   er   rT   s      r   wrapped_funcz$Retry.__call__.<locals>.wrapped_func  s    DN..4::-A000 . ! ANNa'NNNVDNN+;1TZZL	RSQT#UV~~3JJtzzQ->?@@A ..4::-s   - 	CBCCr   )rT   r   r
  s   `` r   r&  zRetry.__call__  s    	A rX   N)   r   r'  r   rX   r   r  r    s    &rX   r  c                       fd}|S )a  
    Multi-thread a target function by default and return the thread or function result.

    This decorator provides flexible execution of the target function, either in a separate thread or synchronously.
    By default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument
    which is removed from kwargs before calling the function.

    Args:
        func (callable): The function to be potentially executed in a separate thread.

    Returns:
        (callable): A wrapper function that either returns a daemon thread or the direct function result.

    Examples:
        >>> @threaded
        ... def process_data(data):
        ...     return data
        >>>
        >>> thread = process_data(my_data)  # Runs in background thread
        >>> result = process_data(my_data, threaded=False)  # Runs synchronously, returns function result
    c                      |j                  dd      r+t        j                  | |d      }|j                          |S  | i |S )zaMulti-thread a given function based on 'threaded' kwarg and return the thread or function result.threadedT)targetrU   rV   daemon)popr  Threadstart)rU   rV   threadr   s      r   r   zthreaded.<locals>.wrapper  sF    ::j$'%%TVTXYFLLNM(((rX   r   )r   r   s   ` r   r  r    s    .) NrX   c                  ^   t         d   r?t        dvs7t        t        d         j                  dk7  st
        st        rt        rt        ry	 ddl	} d }| j                  dddd	t        t               rd
nd|t        t        g       | j!                  dt         d   i       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.

    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)
    syncr   r   yoloNc                     d|v r%|d   \  }}}|t         t        hv sdt        |      v ryt        d   t	        t        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 | None): The modified event or None if the event should not be sent to Sentry.
        exc_infozout of memoryNr   r  pipother)sys_argvsys_argv_nameinstallro  tags)	KeyboardInterruptrh  rA  r  r   r   r  IS_PIP_PACKAGEENVIRONMENT)eventhintr  	exc_valuer   s        r   before_sendzset_sentry.<locals>.before_send  sw     %)*%5"Hi-/@AA_X[\eXfEf Q!$q']// *uW	
f rX   z_https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016Fg      ?runpod
production)dsndebugauto_enabling_integrationstraces_sample_raterd  environmentr&  ignore_errorsiduuid)SETTINGSr   r   r  r   TESTS_RUNNINGONLINEr!  r  r  r4  initr   r|  r   rh  set_user)r  r&  s     r   
set_sentryr6    s    $ VwQ='0 OOm#( )H(*;<  	 x/01K  s   B   	B,+B,c                   ~     e Zd ZdZddeeef   f fdZd Zd Z	e
d        Z fdZ fdZd	 Z fd
Z fdZ xZS )JSONDicta  
    A dictionary-like class that provides JSON persistence for its contents.

    This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are
    modified. It ensures thread-safe operations using a lock and handles JSON serialization of Path objects.

    Attributes:
        file_path (Path): The path to the JSON file used for persistence.
        lock (threading.Lock): A lock object to ensure thread-safe operations.

    Methods:
        _load: Load the data from the JSON file into the dictionary.
        _save: Save the current state of the dictionary to the JSON file.
        __setitem__: Store a key-value pair and persist it to disk.
        __delitem__: Remove an item and update the persistent storage.
        update: Update the dictionary and persist changes.
        clear: Clear all entries and update the persistent storage.

    Examples:
        >>> json_dict = JSONDict("data.json")
        >>> json_dict["key"] = "value"
        >>> print(json_dict["key"])
        value
        >>> del json_dict["key"]
        >>> json_dict.update({"new_key": "new_value"})
        >>> json_dict.clear()
    	file_pathc                     t         |           t        |      | _        t	               | _        | j                          y)zMInitialize a JSONDict object with a specified file path for JSON persistence.N)rQ   rR   r   r9  r   r  _load)rT   r9  rW   s     r   rR   zJSONDict.__init__O  s+    iF	

rX   c                    	 | j                   j                         rCt        | j                         5 }| j                  t	        j
                  |             ddd       yy# 1 sw Y   yxY w# t        j                  $ r& t        j                  d| j                    d       Y yt        $ r/}t        j                  d| j                    d|        Y d}~yd}~ww xY w)z5Load the data from the JSON file into the dictionary.NzError decoding JSON from z$. Starting with an empty dictionary.zError reading from r   )r9  r  rF  updater   rU  JSONDecodeErrorrz   r{   r	  errorrT   r#  r	  s      r   r;  zJSONDict._loadV  s    	F~~$$&$..) .QKK		!-. . '. .## 	mNN6t~~6FFjkl 	FLL.t~~.>bDEE	Fs:   /A, %A A,  A)%A, )A, ,6C$C,%CCc                 |   	 | j                   j                  j                  dd       t        | j                   dd      5 }t	        j
                  t        |       |d| j                         ddd       y# 1 sw Y   yxY w# t        $ r/}t        j                  d	| j                    d
|        Y d}~yd}~ww xY w)z:Save the current state of the dictionary to the JSON file.Tr6  r9  r   r   r   )r   r3   NzError writing to r   )r9  r?  r@  rF  r   rH  r   _json_defaultr	  rz   r?  r@  s      r   _savezJSONDict._savea  s    	DNN!!''t'DdnncG< O		$t*a4;M;MNO O O 	DLL,T^^,<BqcBCC	Ds5   ?B -A7.B 7B <B  B 	B;%B66B;c                 |    t        | t              rt        |       S t        dt	        |       j
                   d      )z*Handle JSON serialization of Path objects.zObject of type z is not JSON serializable)r   r   rA  	TypeErrorrE  r\   )objs    r   rB  zJSONDict._json_defaultj  s7     c4 s8O/$s)*<*<)==VWXXrX   c                     | j                   5  t        | 	  ||       | j                          ddd       y# 1 sw Y   yxY w)z+Store a key-value pair and persist to disk.N)r  rQ   __setitem__rC  )rT   r   r  rW   s      r   rH  zJSONDict.__setitem__q  s7    YY 	GU+JJL	 	 	s	   !8Ac                     | j                   5  t        | 	  |       | j                          ddd       y# 1 sw Y   yxY w)z1Remove an item and update the persistent storage.N)r  rQ   __delitem__rC  )rT   r   rW   s     r   rJ  zJSONDict.__delitem__w  s5    YY 	G$JJL	 	 		    7A c                 ~    t        j                  t        |       dd| j                        }d| j                   d| S )zEReturn a pretty-printed JSON string representation of the dictionary.r   F)r   ensure_asciir3   z
JSONDict("z"):
)r   r   r   rB  r9  )rT   contentss     r   r   zJSONDict.__str__}  s9    ::d4jPTPbPbcDNN+5
;;rX   c                     | j                   5  t        |   |i | | j                          ddd       y# 1 sw Y   yxY w)z*Update the dictionary and persist changes.N)r  rQ   r=  rC  rS   s      r   r=  zJSONDict.update  s9    YY 	GND+F+JJL	 	 	rK  c                     | j                   5  t        | 	          | j                          ddd       y# 1 sw Y   yxY w)z4Clear all entries and update the persistent storage.N)r  rQ   clearrC  r[   s    r   rQ  zJSONDict.clear  s1    YY 	GMOJJL	 	 	s   6?)z	data.json)r\   r]   r^   r_   r   rA  r   rR   r;  rC  staticmethodrB  rH  rJ  r   r=  rQ  r`   ra   s   @r   r8  r8  2  s]    8%T	"2 	FD Y Y<
 rX   r8  c                   D     e Zd ZdZedf fd	Zd Zd Z fdZd Z	 xZ
S )SettingsManagerao  
    SettingsManager class for managing and persisting Ultralytics settings.

    This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default
    values. It validates settings on initialization and provides methods to update or reset settings. The settings
    include directories for datasets, weights, and runs, as well as various integration flags.

    Attributes:
        file (Path): The path to the JSON file used for persistence.
        version (str): The version of the settings schema.
        defaults (dict): A dictionary containing default settings.
        help_msg (str): A help message for users on how to view and update settings.

    Methods:
        _validate_settings: Validate the current settings and reset if necessary.
        update: Update settings, validating keys and types.
        reset: Reset the settings to default and save them.

    Examples:
        Initialize and update settings:
        >>> settings = SettingsManager()
        >>> settings.update(runs_dir="/new/runs/dir")
        >>> print(settings["runs_dir"])
        /new/runs/dir
    z0.0.6c                    ddl }ddl}ddlm} t        xs
 t               }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        |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ddddd| _        d| j                   d| _         |t$              5  t&        | Q  | j                         | j                  j+                         r| s5t,        j/                  d| d| j"                          | j1                          | j3                          ddd       y# 1 sw Y   yxY w) zLInitialize the SettingsManager with default settings and load user settings.r   N)torch_distributed_zero_firstsettings_versiondatasets_dirdatasetsweights_dirweightsruns_dirrunsr0  r  Tapi_keyr   openai_api_keyclearmlcometdvchubmlflowneptuneraytunetensorboardFwandb)
vscode_msgopenvino_msgz7
View Ultralytics Settings with 'yolo settings' or at 'z'
Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings.z#Creating new Ultralytics Settings vu
    file ✅ )hashlibr0  ultralytics.utils.torch_utilsrV  r  r   r  r?  resolverI  versionrA  sha256getnoder  	hexdigestdefaultshelp_msgr   rQ   rR   r  rz   r   reset_validate_settings)	rT   rI  rn  rk  r0  rV  rootdatasets_rootrW   s	           r   rR   zSettingsManager.__init__  s	   N $&(/4DT[[4QW[ddfJ	

C
 :;
 3ti/0
 D6M*	

 GNN3t||~#6#=#=#?@JJL
 D
 r
 b
 t
 T
 4
 4
 d
 t
 t
  5!
" U#
$  '
. Gtyyk RZ Z 	 **5 	&GTYY'99##%TA'*UYUbUbTcde

##%	& 	& 	&s   6A;F::Gc                 Z    t         j                               t         j                  j                               k(  }t         fd j                  j	                         D              } j                  dd       j                  k(  }|r|r|s2t        j                  d j                           j                           j                  d       j                  d      k(  rGt        j                  d j                  d       d j                  d       d	 j                          y
y
)z5Validate the current settings and reset if necessary.c              3   l   K   | ]+  \  }}t        j                  |      t        |             - y wr   )r   rN   rE  )r   r   r   rT   s      r   r   z5SettingsManager._validate_settings.<locals>.<genexpr>  s(     _AJtxx{DG<_s   14rW  r   zUltralytics settings reset to default values. This may be due to a possible problem with your settings or a recent ultralytics package update. rX  r\  z#Ultralytics setting 'datasets_dir: z$' must be different than 'runs_dir: z?'. Please change one to avoid possible issues during training. N)	frozensetkeysrr  r   r   rN   rn  rz   r{   rs  rt  )rT   correct_keyscorrect_typescorrect_versions   `   r   ru  z"SettingsManager._validate_settings  s     -4==;M;M;O1PP_I\I\I^__((#5r:dllJ?NNNNRmm_^ JJL88N#txx
';;NN5dhh~6N5O P559XXj5I4J KOOS}}o_ <rX   c                 *    | j                  ||i       y)zUpdate one key: value pair.N)r=  )rT   r   r  s      r   rH  zSettingsManager.__setitem__  s    S%L!rX   c                    |D ]$  }t        |t              s|j                  |       & |j                         D ]  \  }}|| j                  vrt        d| d| j                         t        | j                  |         }t        ||      rTt        d| d|j                   dt        |      j                   d| j                          t        |   |i | y)z+Update settings, validating keys and types.zNo Ultralytics setting 'z'. zUltralytics setting 'z' must be 'z' type, not 'N)r   r   r=  r   rr  KeyErrorrs  rE  rE  r\   rQ   )rT   rU   rV   argr   r   trW   s          r   r=  zSettingsManager.update  s     	#C#t$c"	# LLN 	DAq%!9!COPPT]]1%&Aa#+A3k!**]SWXYSZScScRddghlhuhugvw 	 	''rX   c                 Z    | j                          | j                  | j                         y)z,Reset the settings to default and save them.N)rQ  r=  rr  r   s    r   rt  zSettingsManager.reset  s    

DMM"rX   )r\   r]   r^   r_   SETTINGS_FILErR   ru  rH  r=  rt  r`   ra   s   @r   rT  rT    s)    4 *7 /&b("(#rX   rT  c                 P    d|  d}|	|d| dz  }t         j                  |       y)z_Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.r   z5' is deprecated and will be removed in in the future.Nz Use 'z
' instead.)rz   r{   )r  new_argr   s      r   deprecation_warnr    s6    cUG
HCy
++
NN3rX   c                     t        |       j                         j                  dd      } t        |       j	                  dd      d   S )zTStrip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.z:/z://r   r   r   )r   as_posixreplacer   spliturls    r   	clean_urlr    s=    
s)



&
&tU
3C3<c1%a((rX   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    	#$$$rX   c                    t         rt        j                  d   nt        j                  d   dz  }|dz  }t        |j	                  |  d            xr% | |j                         r|j                  d      ndv}d}|rdS t        d	       d
| S )zWDisplay a message to install Ultralytics-Snippets for VS Code if not already installed.r   r   z.vscode/extensionsz	.obsolete*r   r   z0https://docs.ultralytics.com/integrations/vscodezVS Code:u+    view Ultralytics VS Code Extension ⚡ at )r   USER_CONFIG_DIRr7  anyglobr  	read_textr]  )extr~  obs_file	installedr  s        r   ri  ri    s    *1O##A&7N7Nq7QUiiDk!HDIIQi()scYaYhYhYj(:L:LW:Upr.sI
<C2i8J#7"88cdgch iirX   zUltralytics: zpersistent_cache.jsonrX  rZ  r\  ColabKaggleJupyterDocker)NAgg)LOGGING_NAMET)r   r   )Ultralyticsr   )z ultralytics.ultralytics-snippets)
contextlibimportlib.metadatar  r  r   r   ro  r   rV  r  r  r  r  rI   pathlibr   r   typesr   typingr   urllib.parser   cv2numpynptorchrK   r   r   ultralytics.utils.patchesr	   r
   r   r   r   r  r   r   argvr  r  rm  FILEr7  ROOTASSETS
ASSETS_URLr   minmax	cpu_countNUM_THREADSrA  r   AUTOINSTALLrM   rP   r  r  r  r   mac_verMACOS_VERSIONmachineARM64python_versionPYTHON_VERSIONTORCH_VERSIONmetadatarn  TORCHVISION_VERSIONrp  rN   	IS_VSCODErz  
RKNN_CHIPSHELP_MSGset_printoptionsr   r   setNumThreads	TQDM_RICHrA   rC   rc   r   r   r   r  rz   r  r  r  CRITICALr   r  r)  rU  DEFAULT_CFG_DICTr{  DEFAULT_CFG_KEYSDEFAULT_CFGre  rB  rj  rq  ru  ry  r|  r  r  r  r  r\   r  r  r  r  r  r  r  r  r  r  r  r  r3  rw  rx  	IS_DOCKER	IS_JETSON
IS_JUPYTERr!  IS_RASPBERRYPIr  r  r  r  r]  r  ContextDecoratorr  r  r  r6  r8  rT  r  r  r  ri  PREFIXr1  PERSISTENT_CACHEDATASETS_DIRWEIGHTS_DIRRUNS_DIRr   r"  r2  rN  r   rX   r   <module>r     s        	  	  
      !    
    # I I 9299VR !<,-
 xxB8H~||A	M
,, !SLBLLNQ./0)")).56<<>&H
ibii-
.
4
4
6&
@.5*4X9WX ug).   "1%D22(((*!!((00? JJNN>51X=	
7t   9 E   cTZ=N=N-O P   ! $'$4

  !%(

! "$+

  !!$

 IBII.67==?6II9I2"	499tyy 2"jSR SRl3x 3xl9+o 9+x3lER 
\7	34 =FGf&&w'7'7!';<=L
 DCT CTN 99-. #((* %9(89&3 &4 Vx!)
4 
! !#4 #4 $ $, 8S 8 8&
-uS$Y/ 
-D 
-rl$ l	oD !"	:K	K	K	\
!!
-\
yryy!23L7J7LM/15Jp-$%
++ %P*J'' *Z FC2LZt Zzv#h v#r)%
j# j 
/	"O.EEF H^,-8M*+$%    
  
  
		  "#A'?'A 
 

*0'6'CJSZ rX   