o
    wi	                     @  s 
  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dl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Zd dlZd dlZd dlmZm Z m!Z! d dlm"Z"m#Z# d dl$m%Z%m$Z$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,m-Z-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8Z8d dl9Z8d dl:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZBmCZC d dlDmEZEmFZF d dlGmHZHmIZI e.rd dlJmKZK d dlLmMZM e/eNge1eOe&f f ZPe6dZQe
ReSZTeU ZVdZWdZXejYZejY[ejY\e]ddZ^dZ_e`de_ Zae`e_d Zbe`e_d Zce`dZdg dZeg dZfdd!d"Zgdd&d'ZhG d(d) d)ZiG d*d+ d+ej+Zjdd-d.Zk		/ddd4d5Zldd7d8Zmeld9Znd:Zoejpqd;Zrerdurd/Zod<Zse7d=dd?d@ZtddAdBZuddDdEZvddFdGZwddIdJZxddLdMZyddOdPZzddSdTZ{ddUdVZ|	ddd]d^Z}dd`daZ~ddcddZddedfZddgdhZddidjZddkdlZddmdnZddodpZddqdrZddsdtZddudvZddwdxZddydzZdd{d|Zdd}d~ZdddZdddZdddZ	ddddZdddZdddZdddZdddZdddZdddZddddZdĐdddZdddZG dd de	jZG dd de	jZG dd de	jZG dd de	jZdddZdddZdddZdddZdddZdddZdddĄZdddɄZddd˄Zddd΄ZdddЄZ	dddd؄Zddd܄ZdddZdddZdddZdddZdddZdddZddddZdddZdؐd dZdِddZ	ddڐd
dZdېdܐddZ	ddݐddZddސddZdߐddZddd d!Zddd"d#Zdd$d%Zdd&d'Zdd)d*Zdd,d-ZG d.d/ d/Zdad0eÐd1< dd4d5ZĐdd6d7ZŐdd8d9ZƐdd<d=Z	ddd@dAZej	dddGdHZʐddIdJZːddKdLZ̐ddMdNZ͐ddOdPZΐddQdRZϐddVdWZАdېddYdZZѐdd\d]ZҐdd_d`ZӐddcddZԐddfdgZՐddidjZ֐ddldmZאddndoZؐddqdrZِdՐdsdtZڐ	vdddydzZېdd{d|Zܐdd}d~ZݐdddZސdddZߐdddZdddZdddZd dŐddZ		ddddZejd/dG dd dZdddZdddZdddZdS (      )annotationsN)IterableMappingSequence)asdictis_dataclass)datedatetime	timedelta)GzipFile)import_module)	getsizeof)
ModuleType)IOTYPE_CHECKINGCallableTextIOUnion)Any	Generator	TypeGuardTypeVar
deprecated)AuthenticationError	CommError
UsageErrorWandbCoreNotAvailableError)	terminput)
filesystemrunid)dumpdumps)FilePathStrStrPath)Response)ArtifactT
_wandb_jobi p z..z.gitz(?:__|[._]|[-]+)^$z{2,}z[^a-z0-9._\-])B   )KBi  )MBi@B )GBi ʚ;)TBl    J))PBl     I5 )EBl     NZo)r*   )KiB   )MiBi   )GiBi   @)TiBl        )PiBl           )EiBl            returnr   c                    s   dd t jD  d fdd} tjtjt}tj|dd}fd	d|D }g| D ]}|t jvr>t jd
| q0| S )a  Create a function that restores user paths after vendor imports.

    This enables us to use the vendor directory for packages we don't depend on. Call
    the returned function after imports are complete. If you don't you may modify the
    user's path which is never good.

    Usage:

    ```python
    reset_path = vendor_setup()
    # do any vendor imports...
    reset_path()
    ```
    c                 S  s   g | ]}|qS  r;   ).0	directoryr;   r;   >/home/ubuntu/.local/lib/python3.10/site-packages/wandb/util.py
<listcomp>w   s    z vendor_setup.<locals>.<listcomp>r:   Nonec                     s
    t _d S N)syspathr;   )original_pathr;   r>   reset_import_pathy      
z'vendor_setup.<locals>.reset_import_pathvendor)z	gql-0.2.0zgraphql-core-1.1watchdog_0_9_0zpromise-2.3.0c                   s   g | ]	}t j |qS r;   )osrC   joinr<   p)
vendor_dirr;   r>   r?          r,   Nr:   r@   )rB   rC   rI   abspathdirname__file__rJ   insert)rE   
parent_dirvendor_packagespackage_dirsrL   r;   )rD   rM   r>   vendor_setuph   s   
rW   namestrr   c                 C  s   t  }t| }|  |S rA   )rW   r   )rX   
reset_pathmoduler;   r;   r>   vendor_import   s   r\   c                   @  s    e Zd Zd
ddZdddZd	S )LazyModuleStater[   types.ModuleTyper:   r@   c                 C  s   || _ d| _t | _d S )NF)r[   load_started	threadingRLocklockselfr[   r;   r;   r>   __init__   s   zLazyModuleState.__init__c                 C  s   | j W | jr	 W d    d S d| _| jjd usJ | jjjd us$J | jjj| j tj| j_| jj	
d\}}}|rRtj| }t||| j W d    d S W d    d S 1 s]w   Y  d S )NT.)rb   r_   r[   __spec__loaderexec_moduletypesr   	__class____name__
rpartitionrB   modulessetattr)rd   parent_childparent_moduler;   r;   r>   load   s    

"zLazyModuleState.loadN)r[   r^   r:   r@   rO   )rl   
__module____qualname__re   rt   r;   r;   r;   r>   r]      s    
r]   c                   @  s*   e Zd ZdddZdd	d
ZdddZdS )
LazyModulerX   rY   r:   r   c                 C  s    t | d}|  t | |S N__lazy_module_state__)object__getattribute__rt   rd   rX   stater;   r;   r>   r{      s   zLazyModule.__getattribute__valuer@   c                 C  s&   t | d}|  t | || d S rx   )rz   r{   rt   __setattr__)rd   rX   r~   r}   r;   r;   r>   r      s   zLazyModule.__setattr__c                 C  s$   t | d}|  t | | d S rx   )rz   r{   rt   __delattr__r|   r;   r;   r>   r      s   zLazyModule.__delattr__NrX   rY   r:   r   )rX   rY   r~   r   r:   r@   )rX   rY   r:   r@   )rl   ru   rv   r{   r   r   r;   r;   r;   r>   rw      s    

rw   r^   c                 C  sb   zt j|  W S  ty0   tj| }|du rttj|}t||_	t
|_|t j| < | Y S w )aW  Import a module lazily, only when it is used.

    Inspired by importlib.util.LazyLoader, but improved so that the module loading is
    thread-safe. Circular dependency between modules can lead to a deadlock if the two
    modules are loaded from different threads.

    :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
    N)rB   rn   KeyError	importlibutil	find_specModuleNotFoundErrormodule_from_specr]   ry   rw   rk   )rX   specr[   r;   r;   r>   import_module_lazy   s   	

r   Trequired
str | Nonelazyboolc                 C  st   | t vr+z|st| W S t| W S  ty*   t |  d|  }|r(t| Y nw |r6| t v r8t|dS dS )aW  Return module or None. Absolute import is required.

    :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
    :param (str) required: A string to raise a ValueError if missing
    :param (bool) lazy: If True, return a lazy loader for the module.
    :return: (module|None) If import succeeds, the module will be returned.
    z Error importing optional module N)	_not_importabler   r   	Exceptionaddlogger	exceptionwandbError)rX   r   r   msgr;   r;   r>   
get_module   s   





r    importlib.ModuleInterface | Nonec                 C  s   t | S rA   )r   )rX   r;   r;   r>   get_optional_module   s   r   numpyFpandasi z@Read the `app_url` setting from the appropriate Settings object.api_urlc                 C  s$   t j  }rt|dS t| S )z8Returns the URL for the W&B UI without a trailing slash./)r   envget_app_urlrY   stripapi_to_app_url)r   app_urlr;   r;   r>   r      s   r   c                 C  sR   d| v r|  dddS d| v r|  dddS d| v r'|  dddS | S )zConvert the API URL to an app (UI) URL.

    Unlike the deprecated `app_url()`, this is a pure function: it does
    not consult environment variables.
    z://api.wandb.testz://api.z://app.r   z://api.wandb.://)replacer   )r   r;   r;   r>   r     s   r   oc                 C  s&   | j jd | j j }|dv r| jS |S )z~Determine types based on type names.

    Avoids needing to to import (and therefore depend on) PyTorch, TensorFlow, etc.
    rf   )zbuiltins.modulez__builtin__.module)rk   ru   rl   )r   instance_namer;   r;   r>   get_full_typename  s   r   c                 C  s>   t | }t|r
dS t|rdS | jjdd d | jj S )Nztensorflow.Tensorztorch.Tensorrf   r   )r   is_tf_tensor_typenameis_pytorch_tensor_typenamerk   ru   splitrl   )r   typenamer;   r;   r>   get_h5_typename$  s   r   stringc                 C  s   t j| }t|jdkS Nr   )urllibparseurlparselenscheme)r   
parsed_urir;   r;   r>   is_uri.  s   r   uric                 C  s(   |  drtj| jn| }tj|S )zcConvert URI to local filesystem path.

    No-op if the uri does not have the expected scheme.
    zfile:)
startswithr   r   r   rC   requesturl2pathname)r   rC   r;   r;   r>   local_file_uri_to_path3  s   r   path_or_uric                 C  s>   t j| }t|jdks|jdkrt|jdkrt| S dS )zReturn path if local, None otherwise.

    Return None if the argument is a local path (not a scheme or file:///). Otherwise
    return `path_or_uri`.
    r   fileN)r   r   r   r   r   netlocr   )r   r   r;   r;   r>   get_local_path_or_none<  s   
r   rC   	int | strc                 C  s   t td|  S )a  Verify that the given path does not contain any invalid characters for a Windows filename.

    Windows filenames cannot contain the following characters:
    < > : " \ / | ? *

    For more details, refer to the official documentation:
    https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions

    Args:
        path: The file path to check, which can be either an integer or a string.

    Returns:
        bool: True if the path does not contain any invalid characters, False otherwise.
    z
[<>:"\\?*])r   researchrC   r;   r;   r>   check_windows_valid_filenameM  s   r   c                 C  st   t  }|dkrt| std|  d|dkr!t| dtj} | tj} | 	tj}dd |D }tj
|S )a  Makes the provide path safe for file upload.

    The filename is made safe by:
    1. Removing any leading slashes to prevent writing to absolute paths
    2. Replacing '.' and '..' with underscores to prevent directory traversal attacks

    Raises:
        ValueError: If running on Windows and the key contains invalid filename characters
                   (\, :, *, ?, ", <, >, |)
    WindowszPath zO is invalid. Please remove invalid filename characters (\, :, *, ?, ", <, >, |)r   c                 S  s,   g | ]}|t jt jfv r|d dn|qS )rf   rq   )rI   curdirpardirr   rK   r;   r;   r>   r?   ~  s     z.make_file_path_upload_safe.<locals>.<listcomp>)platformsystemr   
ValueErrorrY   r   rI   seplstripr   rJ   )rC   sys_platformpaths
safe_pathsr;   r;   r>   make_file_path_upload_safe_  s   
r   output_filename
source_dirarchive_namecustom_filterCallable | Noner@   c              
     s4  d fdd}t  \}}zt|d}|j|||d W d    n1 s'w   Y  t| d	<}td
|d	dd$}	t|d}
|	|
  W d    n1 sRw   Y  W d    n1 saw   Y  W d    n1 spw   Y  W t	| t
| d S W t	| t
| d S t	| t
| w )Ntar_infotarfile.TarInfor:   tarfile.TarInfo | Nonec                   s   d| _  d u r	| S  | S r   )mtime)r   r   r;   r>   _filter_timestamps  s   z(make_tarfile.<locals>._filter_timestampsw)arcnamefilterwb r   )filenamefileobjmoder   rb)r   r   r:   r   )tempfilemkstemptarfileopenr   r   writereadrI   closeremove)r   r   r   r   r   
descriptorunzipped_filenametarout_filegzipped_tartar_filer;   r   r>   make_tarfile  s8     


r   objc                 C     dd l }t| |jS r   )
tensorflow
isinstanceTensor)r   r   r;   r;   r>   is_tf_tensor     r   r   c                 C     |  dod| v pd| v S )Ntensorflow.r   Variabler   r   r;   r;   r>   r        
r   c                 C     |  dod| v S )Nr   EagerTensorr   r   r;   r;   r>   is_tf_eager_tensor_typename     r  c                 C  r   r   )torchr   r   )r   r  r;   r;   r>   is_pytorch_tensor  r   r  c                 C  r   )Nztorch.r   r   r   r   r;   r;   r>   r     r   r   c                 C  r   )Nzjaxlib.Arrayr   r   r;   r;   r>   is_jax_tensor_typename  r  r  c                 C     dd l }|| S r   )jax
device_get)r   r  r;   r;   r>   get_jax_tensor     
r
  c                 C  r   )Nzfastai.r   r   r   r;   r;   r>   is_fastai_tensor_typename  r  r  c                 C  r   )Nzpandas.	DataFramer   r   r;   r;   r>   is_pandas_data_frame_typename  r  r  c                 C  
   |  dS )Nzmatplotlib.r   r   r;   r;   r>   is_matplotlib_typename  rF   r  c                 C  r  )Nplotly.r   r   r;   r;   r>   is_plotly_typename  rF   r  c                 C  s   |  do	| dS )Nr  z.Figure)r   endswithr   r;   r;   r>   is_plotly_figure_typename     r  c                 C  s   t ot| t jS rA   )npr   ndarrayr   r;   r;   r>   is_numpy_array     r  c                 C  s$   t rdd l}t| |jS tt| S r   )pd_availabler   r   r  r  r   )r   pdr;   r;   r>   is_pandas_data_frame  s   r  c                 C  sv   ddl }ddlm} ddlm} dd	d
}||_| |jkr#|  } | S t| |s9t	| dr9| j
} t| |s9td| S )zExtract the current figure from a matplotlib object.

    Return the object itself if it's a figure.
    Raises ValueError if the object can't be converted.
    r   N)Figure)Spinerd   r   r:   r   c                 S  s^   | j pd}t|tr|dkrd}n|dkrd}t|dkr!td|\}}t|dko-|d	kS )
zReturn True if directly on axes frame.

        This is useful for determining if a spine is the edge of an
        old style MPL plot. If so, this function will return True.
        )outwardg        center)axes      ?zero)datar      zposition should be 2-tupler   r   )	_positionr   rY   r   r   r   )rd   positionposition_typeamountr;   r;   r>   is_frame_like  s   

z/ensure_matplotlib_figure.<locals>.is_frame_likefigurezHOnly matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted.)rd   r   r:   r   )
matplotlibmatplotlib.figurer  matplotlib.spinesr  r+  pyplotgcfr   hasattrr,  r   )r   r-  r  r  r+  r;   r;   r>   ensure_matplotlib_figure  s   


r3  c                 C  s   t | } tddd}|| S )Nplotly.toolsplotly is required to log interactive plots, install with: `pip install plotly` or convert the plot to an image with `wandb.Image(plt)`r   )r3  r   mpl_to_plotlyr   toolsr;   r;   r>   matplotlib_to_plotly  s   
r:  c                 C  s   t | } tdd | jD S )Nc                 s  s    | ]
}t |jd kV  qdS )r   N)r   images)r<   axr;   r;   r>   	<genexpr>#  s    z-matplotlib_contains_images.<locals>.<genexpr>)r3  anyr"  r  r;   r;   r>   matplotlib_contains_images!  s   r?  c                 C  sR   |   } t| trt| rd } | S t| tjr'| jjdks#| jdkr't| } | S )Nfbfloat16)	itemr   floatmathisnanr  genericdtypekindr  r;   r;   r>   _numpy_generic_convert&  s   
rI  ddictvisiteddict[int, dict] | Nonetuple[dict, bool]c                 C  s   t  }d}|du rt| |i}nt| |v r|t|  dfS ||t| < |  D ]$\}}t|t r<t||\}}||O }t|tjrHt|}d}|||< q(||fS )zReturns a dictionary where all NumPy keys are converted.

    Args:
        d: The dictionary to sanitize.

    Returns:
        A sanitized dictionary, and a boolean indicating whether anything was
        changed.
    FNT)rK  iditemsr   _sanitize_numpy_keysr  rF  rI  )rJ  rL  out	convertedkeyr~   converted_valuer;   r;   r>   rQ  6  s    

rQ  2tuple[Any, bool] | tuple[None | str | float, bool]c                 C  s&  d}t | }t|r|  } n]t|r'z|  } W nR ty&   |  } Y nFw t|s/t|rdz	| jr7| 	 } W n	 t
yA   Y nw z| j} W n	 tyP   Y nw |  r^|  	  } n|  dfS t|rlt| } t| r| jdkr||  d } n{| jdkr|  } nqtrt| tjrt| } ndt| tr| d} nYt| ttfr|  } nMt| rt| drt| dr| j d| j  nt!| } n1t| t"rt#$| rd	} n$t| t%rtrt&| \} }nt| t'rt(| } nt| t)j*r| j+} nd
}t,| t-krt./dt0| j1 dt,|  d | |fS )z>Convert an object into something that's more becoming of JSON.Tr,   r       utf-8rv   ru   rf   NFzSerializing object of type z	 that is z bytes)2r   r  r   r   evalRuntimeErrorr   r  requires_graddetachAttributeErrorr%  sizecpurB  r  r
  r  flattentolistr  r   rF  rI  bytesdecoder	   r   	isoformatcallabler2  ru   rv   rY   rC  rD  rE  rK  rQ  settupleenumEnumrX   r   VALUE_BYTES_LIMITr   termwarntyperl   )r   rS  r   r;   r;   r>   json_friendly[  sz   








rm  valc                 C  s   t | tri }|  D ]
\}}t|||< q|S t | tr)t| j| j| jd}|S t| \} }t | t	rIt | t
sIg }| D ]	}|t| q=|S t| rZt | tsZt| }t|S | jjdvrdt
| } | S )zJMake any value (including dict, slice, sequence, dataclass) JSON friendly.)slice_start
slice_step
slice_stop)builtins__builtin__)r   rK  rP  json_friendly_valslicestartstepstoprm  r   rY   appendr   rl  r   rk   ru   )rn  rS  rT  r~   rq   r;   r;   r>   rt    s,   

rt  aliasc                 C  s(   t | dko| d dko| dd   S )Nr&  r   vr,   )r   	isnumeric)rz  r;   r;   r>   alias_is_version_index  s   (r}  c                 C  s@   t t| rtddd}|| } tt| rd|  dS | S )Nr4  r5  r6  plotly)_typeplot)r  r   r   r7  r  to_plotly_jsonr8  r;   r;   r>   convert_plots  s   
r  tuple[Any, bool]c                 C  s8   t rt| t jr| jdkrtj| dd dfS | dfS )NrW  )num_binsTF)r  r   r  r^  r   	Histogramto_jsonr  r;   r;   r>   maybe_compress_history  s   r  h5_typenamec                 C  s   t rAt| t jrA| jdkrA|t |  t |  t |  t |  t 	| dt 	| dt 	| dt 	| d| jd
dfS | dfS )	NrW  
      K   Z   )
r  varmeanminmaxz10%z25%z75%z90%r^  TF)
r  r   r  r^  r  rB  r  aminamax
percentile)r   r  r;   r;   r>   maybe_compress_summary  s   



r  attempt_launch_browserc                 C  s   g d}g d}ddl }| }|rGdtjv r tdd |D s d}z| }t|d	r4|j|v r7d}W |S W |S W |S  |jyF   d}Y |S w |S )
z%Decide if we should launch a browser.)DISPLAYWAYLAND_DISPLAY
MIR_SOCKET)zwww-browserlynxlinkselinksw3mr   Nlinuxc                 s  s    | ]}t |V  qd S rA   )rI   getenv)r<   r  r;   r;   r>   r=    s    

z!launch_browser.<locals>.<genexpr>FrX   )
webbrowserrB   r   r>  getr2  rX   r   )r  _display_variables_webbrowser_names_blocklistr  launch_browserbrowserr;   r;   r>   r    s.   r     lengthintc                 C  s
   t | S rA   )r   generate_idr  r;   r;   r>   r    s   
r  c                   C  s6   t drz	tt jd W S  ty   Y dS w dS )zCAttempt to parse TFJob config, returning False if it can't find it.	TF_CONFIGF)rI   r  jsonloadsenvironr   r;   r;   r;   r>   parse_tfjob_config	  s   
r  c                   @     e Zd ZdZdddZdS )	WandBJSONEncoder-A JSON Encoder that handles some extra types.r   r   r:   c                 C  s4   t |dr	| S t|\}}|r|S tj| |S )Njson_encode)r2  r  rm  r  JSONEncoderdefault)rd   r   tmp_objrS  r;   r;   r>   r    s   
zWandBJSONEncoder.defaultNr   r   r:   r   rl   ru   rv   __doc__r  r;   r;   r;   r>   r        r  c                   @  r  )	WandBJSONEncoderOldr  r   r   r:   c                 C  s4   t |\}}t|t|\}}|r|S tj| |S rA   )rm  r  r   r  r  r  )rd   r   r  rS  
compressedr;   r;   r>   r  %  s
   zWandBJSONEncoderOld.defaultNr  r  r;   r;   r;   r>   r  "  r  r  c                   @  r  )	WandBHistoryJSONEncoderA JSON Encoder that handles some extra types.

    This encoder turns numpy like objects with a size > 32 into histograms.
    r   r   r:   c                 C  s.   t |\}}t|\}}|r|S tj| |S rA   )rm  r  r  r  r  )rd   r   rS  r  r;   r;   r>   r  3  s
   zWandBHistoryJSONEncoder.defaultNr  r  r;   r;   r;   r>   r  -      r  c                   @  r  )	JSONEncoderUncompressedr  r   r   r:   c                 C  sN   t |r| S trt|tjr| S tr t|tjr | }tj	| |S rA   )
r  ra  r  r   numberrB  rF  r  r  r  )rd   r   r;   r;   r>   r  A  s   zJSONEncoderUncompressed.defaultNr  r  r;   r;   r;   r>   r  ;  r  r  fpIO[str]kwargsc                 K     t | |fdti|S z5Convert obj to json, with some extra encodable types.cls)r    r  r   r  r  r;   r;   r>   json_dump_saferK     r  c                 K     t | fdti|S r  )r!   r  r   r  r;   r;   r>   json_dumps_saferP     r  c                 K  r  r  )r    r  r  r;   r;   r>   json_dump_uncompressedV  r  r  c                 K  r  )zKConvert obj to json, with some extra encodable types, including histograms.r  )r!   r  r  r;   r;   r>   json_dumps_safer_history[  r  r  r{  &int | float | str | Mapping | Sequenceint | float | strc                 C  s   t | ttfr	| S t| S )z,If v is not a basic type convert it to json.)r   rC  r  r  r{  r;   r;   r>   make_json_if_not_number`  s   r  c                 C  s|   t | trdd |  D S t | tr| S t | tr!dd | D S t | tr<| | kr,dS | tdkr4dS | tdkr<d	S | S )
zKReplace invalid json floats with strings. Also converts to lists and dicts.c                 S  s   i | ]	\}}|t |qS r;   make_safe_for_json)r<   kr{  r;   r;   r>   
<dictcomp>l  rN   z&make_safe_for_json.<locals>.<dictcomp>c                 S  s   g | ]}t |qS r;   r  )r<   r{  r;   r;   r>   r?   q  s    z&make_safe_for_json.<locals>.<listcomp>NaNz+infInfinityz-infz	-Infinity)r   r   rP  rY   r   rC  r  r;   r;   r>   r  i  s   



r  er   c                 C  sx   ddl m} t| |sdS | jd usJ d| jj  kr dk r)n dS | jjdkr+dS t| jj}t|d d d )	Nr   	HTTPErrorT  i  i  errorsmessage)	requestsr  r   responsestatus_coder  r  contentr   )r  r  bodyr;   r;   r>   no_retry_4xx}  s   
r  r  r$   	list[str]c                 C  s   ddl m} z|  }W n |y   g  Y S w t|tsg S ddd}|d }r6||}|r4|gS g S |d	 }rVt|trVg }|D ]}||}|rS|| qF|S g S )zReturns error messages stored in a backend response.

    If the response is not in an expected format, an empty list is returned.

    Args:
        response: A response to an HTTP request to the W&B server.
    r   )JSONDecodeErrorerrorr   r:   r   c                 S  s8   t | tr| S t | tr| d }rt |tr|S d S )Nr  )r   rY   rK  r  )r  r  r;   r;   r>   get_message  s   
z1parse_backend_error_messages.<locals>.get_messager  N)r  r   r:   r   )r  r  r  r   rK  r  listry  )r  r  r%  r  r  r  r  messagesr;   r;   r>   parse_backend_error_messages  s*   


r  c                 C  s
  ddl m} t| dr| j} t| |sdS | jd u rdS | jjdv r$dS | jjdvr,dS | jjdkrFtd	tj	j
 d
| jj d| jj d| jjdkrgtjrXtdtjj td| jj d| jj d| jjdkrt| jrtdS td| jj d| jj ddS )Nr   r  r   T)r    F)      r  z@The API key you provided is either invalid or missing.  If the `aZ  ` environment variable is set, make sure it is correct. Otherwise, to resolve this issue, you may try running the 'wandb login --relogin' command. If you are using a local server, make sure that you're using the correct hostname. If you're not sure, you can try logging in again using the 'wandb login --relogin --host [hostname]' command.(Error z: )r  zPermission denied to access zIt appears that you do not have permission to access the requested resource. Please reach out to the project owner to grant you access. If you have the correct permissions, verify that there are no issues with your networking setup.(Error r  zUFailed to find resource. Please make sure you have the correct resource path. (Error )r  r  r2  r   r   r  r  r   r   r   API_KEYreasonrunr   rC   r  LookupErrorr  r  r;   r;   r>   no_retry_auth  sT   


	
r  bool | Nonec                 C  sD   ddl m} t| dr| j} t| |r | jdur | jjdkr dS dS )zCheck if the exception is a conflict type so it can be retried.

    Returns:
        True - Should retry this operation
        False - Should not retry this operation
        None - No decision, let someone else decide
    r   r  r   Nr  Tr  r  r2  r   r   r  r  r  r;   r;   r>   check_retry_conflict  s   

r  c                 C  sT   ddl m} t| dr| j} t| |r(| jdur(| jjdkr dS | jjdkr(dS dS )	zCheck if the exception is a conflict or gone type, so it can be retried or not.

    Returns:
        True - Should retry this operation
        False - Should not retry this operation
        None - No decision, let someone else decide
    r   r  r   Nr  Ti  Fr  r  r;   r;   r>   check_retry_conflict_or_gone  s   
r  fallback_retry_fnCheckRetryFnTypecheck_fn"Callable[[Exception], bool | None]check_timedeltatimedelta | Nonec                   s   d fdd}|S )	aQ  Return a check_retry_fn which can be used by lib.Retry().

    Args:
        fallback_fn: Use this function if check_fn didn't decide if a retry should happen.
        check_fn: Function which returns bool if retry should happen or None if unsure.
        check_timedelta: Optional retry timeout if we check_fn matches the exception
    r  r   r:   bool | timedeltac                   s0    | }|d u r| S |du rdS rS dS )NFTr;   )r  checkr  r   r  r;   r>   check_retry_fn&  s   z+make_check_retry_fn.<locals>.check_retry_fnN)r  r   r:   r  r;   )r  r  r   r  r;   r  r>   make_check_retry_fn  s   
r  programNone | list | list[str]c                 C  sz   t j| r;t | t js;zt| }W n
 ty   Y dS w |  }|	dr2t
|dd S | dr;tjgS dS )zReturn a command that will run program.

    Args:
        program: The string name of the program to try to run.

    Returns:
        commandline list of strings to run the program (eg. with subprocess.call()) or None
    Nz#!r&  .py)rI   rC   isfileaccessX_OKr   OSErrorreadliner   r   shlexr   r  rB   
executable)r  opened
first_liner;   r;   r>   find_runner3  s   	

r  valuesr   target_lengthr  c                 C  sl   |dkst dt| } t| |k r| S tt| d |d  }g }t|D ]}|| t||   q&|S )zDownsample 1d values to target_length, including start and end.

    Algorithm just rounds index down.

    Values can be any sequence, including a generator.
    r,   ztarget_length must be > 1)r   r  r   rC  rangery  r  )r  r  ratioresultir;   r;   r>   
downsampleJ  s   r  
dictionaryr   rT  c                 C  s   || v ot | | tjS rA   )r   numbersNumber)r  rT  r;   r;   r>   has_num]     r  imagec                 C  s   | rt d| S dS )z)Regex match for valid docker image names.z^(?:(?=[^:\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![._-]))*)(?::(?![.-])[a-zA-Z0-9_.-]{1,128})?$N)r   match)r   r;   r;   r>   docker_image_regexa  s   r"  argsc           	      C  s  g d}d}d}g }t | dkr| d dkr| d t| D ]A\}}|dr-|}|}qd|v r7|| qt|r`||d krG|| qd	|v rQ|| q||v r`||d
 kr`|| qd}|D ]}d|v ssd|v ssd|v rw|} nqe|du rt |dkr|d }|S )a  Scan docker run args and attempt to find the most likely docker image argument.

    It excludes any arguments that start with a dash, and the argument after it if it
    isn't a boolean switch. This can be improved, we currently fallback gracefully when
    this fails.
    )z-tz--ttyz--rmz--privilegedz--oom-kill-disablez--no-healthcheckz-iz--interactivez--initz--helpz--detachz-dz--sig-proxyz-itz-itdr   r   r  -z@sha256:r&  =r,   N:@r   )r   pop	enumerater   ry  r"  )	r#  	bool_args	last_flaglast_argpossible_imagesr  argmost_likelyimgr;   r;   r>   image_from_docker_argsk  s:   


r2  r   c                 C  r  r   )yaml	safe_load)r   r3  r;   r;   r>   	load_yaml  r  r5  c            	   
   C  s  d} t j| s
dS zt| }| }W d   n1 sw   Y  W n? ty7   td|  d Y dS  tyc } z!t 	 }d|  d| d| d}t| t
| W Y d}~dS d}~ww |shdS d	dl}d
t dt dt ddt d}z|j|dddd| id}|  W n |jy   Y dS w zt| d d d	 d dW S  tttfy   td Y dS w )a	  Ping the k8s metadata service for the image id.

    Specify the KUBERNETES_NAMESPACE environment variable if your pods are not in the
    default namespace:

    - name: KUBERNETES_NAMESPACE valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
    z3/var/run/secrets/kubernetes.io/serviceaccount/tokenNzToken file not found at rf   z!Unable to read the token file at z due to permission error (z).The current user id is zQ. Consider changing the securityContext to run the container as the current user.r   z*https://{}:{}/api/v1/namespaces/{}/pods/{}KUBERNETES_SERVICE_HOSTKUBERNETES_PORT_443_TCP_PORTKUBERNETES_NAMESPACEr  HOSTNAMEz4/var/run/secrets/kubernetes.io/serviceaccount/ca.crt   AuthorizationzBearer )verifytimeoutheadersstatuscontainerStatusesimageIDzdocker-pullable://z&Error checking kubernetes for image id)rI   rC   existsr   r   FileNotFoundErrorr   warningPermissionErrorgetuidr   rk  r  formatr  r  raise_for_statusRequestExceptionrY   r  r   r   r   
IndexErrorr   )	
token_path
token_filetokenr  current_uidrD  r  
k8s_serverresr;   r;   r>   image_id_from_k8s  sh   






rQ  targetr=  int | float | Nonec                   s,   t   dfddd fd
d}|S )a  Wrap a method to run in the background with an optional timeout.

    Returns a new method that will call the original with any args, waiting for upto
    timeout seconds. This new method blocks on the original and returns the result or
    None if timeout was reached, along with the thread. You can check thread.is_alive()
    to determine if a timeout was reached. If an exception is thrown in the thread, we
    reraise it.
    qqueue.Queuer#  r   r  r:   c              
     sL   z|   |i | W d S  ty% } z|  | W Y d }~d S d }~ww rA   )putr   )rT  r#  r  r  )rR  r;   r>   wrapped_target  s   z"async_call.<locals>.wrapped_targetBtuple[Exception, threading.Thread] | tuple[None, threading.Thread]c                    sv   t j f|  |d}d|_|  z d}W n tjy(   d |f Y S w t|tr7|	t
 d ||fS )N)rR  r#  r  Tr&  )r`   Threaddaemonrv  r  queueEmptyr   r   with_tracebackrB   exc_info)r#  r  threadr  )rT  r=  rW  r;   r>   wrapper  s   
zasync_call.<locals>.wrapperN)rT  rU  r#  r   r  r   r:   r   )r#  r   r  r   r:   rX  )r[  Queue)rR  r=  r`  r;   )rT  rR  r=  rW  r>   
async_call  s   	rb  rT  rU  	max_itemsqueue_timeoutint | floatc              	   C  sv   z|  d|}W n tjy   g  Y S w |g}t|D ]}z|  }W n tjy2   | Y   S w || q|S NT)r  r[  r\  r  
get_nowaitry  )rT  rc  rd  rB  rP  rq   r;   r;   r>   read_many_from_queue
  s   rh  rC  c                   C  s   t  S )z|Get a time value for interval comparisons.

    When possible it is a monotonic clock to prevent backwards time issues.
    )time	monotonicr;   r;   r;   r>   stopwatch_now  s   rk  class_countlist[list[int]]c                   s$   g dg fddt  d D  S )N)r   r   r   c                   s"   g | ]}t | d   d d qS )g      ?)colorsys
hsv_to_rgb)r<   r  rl  r;   r>   r?   %  s    z class_colors.<locals>.<listcomp>r,   )r  rp  r;   rp  r>   class_colors#  s   
rq  choicesSequence[str]input_timeoutfloat | Nonec                 C  s   t | dkr
| d S t| D ]\}}td|d  d|  q	 td|d}|s*q d}tt t|d }W d	   n1 sBw   Y  |dk sS|t | d krYt	d
 q | | }td| |S )aG  Prompt the user to choose from a list of options.

    If exactly one choice is given, it is returned immediately.

    Raises:
        TimeoutError: if input_timeout is specified and expires.
        NotATerminalError: if the output device is not capable.
        KeyboardInterrupt: if the user aborts by pressing Ctrl+C.
    r,   r   (z) TzEnter your choice: )r=  NzInvalid choicez
You chose )
r   r*  r   termlogr   
contextlibsuppressr   r  rk  )rr  rt  r  
choice_strchoiceidxr  r;   r;   r>   prompt_choices+  s$   
r~  shapeSequence[int]riskyc                 C  sH   t | dv rdS |rt | dkrdS t | dkr"| d dv r dS dS d	S )
zInfer the type of data based on the shape of the tensors.

    Args:
        shape (Sequence[int]): The shape of the data
        risky(bool): some guesses are more likely to be wrong.
    )r,   r&  labelr:  r      rw  )r,   r:  r  segmentation_maskN)r   )r  r  r;   r;   r>   guess_data_typeR  s   r  	dest_path
source_urlapi_keyc                 C  s   dd l }d|pdf}|j||ddd}|  tj| v r%ttj|  t	| d}|j
dd	D ]}|| q1W d    d S 1 sDw   Y  d S )
Nr   apir   T   authstreamr=  r   r4   )
chunk_size)r  r  rH  rI   r   r   mkdir_exists_okrC   rQ   
fsync_openiter_contentr   )r  r  r  r  r  r  r   r%  r;   r;   r>   download_file_from_urlj  s    
"r  rb  c                 C  s4   dd l }d|pdf}|j| |ddd}|  |jS )Nr   r  r   Tr  r  )r  r  rH  r  )r  r  r  r  r  r;   r;   r>   download_file_into_memory  s   r  obr   c                 C  s   t | do|  S )Nisatty)r2  r  )r  r;   r;   r>   r    r  r  r^  unitslist[tuple[str, Any]] | Nonec                 C  sX   |pt }|d \}}tt| | d}|dk st|dkr#| | S t| |dd  S )Nr   r,   r4   )POW_10_BYTESroundrC  r   to_human_size)r^  r  unitr~   factorr;   r;   r>   r    s   
r  c                 C  s   |pt }dd |D }tdd| tj}t|| }|s&tdt	|
d|
dr:||
d  nd}}t|| S )Nc                 S  s   i | ]	\}}|  |qS r;   )upper)r<   r  r~   r;   r;   r>   r    rN   z#from_human_size.<locals>.<dictcomp>z(\d+\.?\d*)\s*({})?|z/size must be of the form `10`, `10B` or `10 B`.r,   r&  )r  r   compilerG  rJ   keys
IGNORECASEr!  r   rC  groupr  r  )r^  r  
units_dictregexr!  r  r  r;   r;   r>   from_human_size  s   r  c                 C  s   ddl m} | j}|d u rdS t|}tj|}| d u r"t|S tj| s0tj	tj
| } tjtj| }||sCt|S |}tj||}|dkrV|d| 7 }t|tjdS )Nr   )GitRepouncategorizedrf   r%  rq   )wandb.sdk.lib.gitlibr  root_dirto_native_slash_pathrI   rC   basenamerY   isabsrJ   r   rQ   rP   r   relpathr   r   )r  r  r  	repo_nameprog_dirprojectsub_pathr;   r;   r>   auto_project_name  s$   
r  c                 C  s   t  dkr| dd} | S )Nr   \r   )r   r   r   r   r;   r;   r>   to_forward_slash_path  s   r  r"   c                 C  s   t | dtjS )Nr   )r"   r   rI   r   r   r;   r;   r>   r    r  r  filesc                 C  s$   d| v rt d t d dS dS )Nzwandb-metadata.jsonz8These runs were logged with a previous version of wandb.zGRun pip install wandb<0.10.0 to get the old library and sync your runs.TF)r   rk  )r  r;   r;   r>   check_and_warn_old  s   
r  c                   @  s`   e Zd ZdddZdd	d
ZdddZdddZ	d d!ddZd"ddZd#ddZ	d$ddZ
dS )%ImportMetaHookr:   r@   c                 C  s   t  | _t  | _d S rA   )rK  rn   	on_importrd   r;   r;   r>   re     s   zImportMetaHook.__init__fullnamerY   r  r   c                 C  s   | j |g | d S rA   )r  
setdefaultry  )rd   r  r  r;   r;   r>   r     r  zImportMetaHook.addc                 C  s   t jd|  d S r   )rB   	meta_pathrS   r  r;   r;   r>   install  r  zImportMetaHook.installc                 C  s   t j|  d S rA   )rB   r  r   r  r;   r;   r>   	uninstall  r  zImportMetaHook.uninstallNrC   r   ImportMetaHook | Nonec                 C  s   || j v r| S d S rA   )r  )rd   r  rC   r;   r;   r>   find_module  s   
zImportMetaHook.find_moduler   c                 C  sH   |    t|}|   || j|< | j|}|r"|D ]}|  q|S rA   )r  r   r   r  rn   r  r  )rd   r  mod
on_importsr@  r;   r;   r>   load_module  s   

zImportMetaHook.load_moduletuple[str, ...]c                 C  s
   t | jS rA   )rg  rn   r  r;   r;   r>   get_modules  rF   zImportMetaHook.get_modulesr[   c                 C  s
   | j | S rA   )rn   rc   r;   r;   r>   r     rF   zImportMetaHook.get_modulerO   r  rY   r  r   r:   r@   rA   )r  rY   rC   r   r:   r  )r  rY   r:   r   )r:   r  )r[   rY   r:   r   )rl   ru   rv   re   r   r  r  r  r  r  r   r;   r;   r;   r>   r    s    





r  r  _import_hookr  r  c                 C  s&   t d u rt a t   t | | d S rA   )r  r  r  r   )r  r  r;   r;   r>   add_import_hook  s   r  c                 C  s   t j| }t|jS )zReturn the host of the path.)r   r   r   rY   r   )rC   urlr;   r;   r>   host_from_path  s   
r  c                 C  s6   t j| }|jd dkr|jn|jdd }t|S )zReturn the URI of the path.r   r   r,   N)r   r   r   rC   rY   )rC   r  r   r;   r;   r>   uri_from_path  s   "r  r  r   c                 C  s    t | dd}|r| dv S dS )z)Return True if the stream supports UTF-8.encodingN>   utf_8rX  F)getattrlower)r  r  r;   r;   r>   is_unicode_safe  s   r  rand!ModuleType | random.Random | Nonec                   s.   t d  pt d fddt| D S )Nz8rand_alphanumeric is deprecated, use 'secrets.token_hex'r   c                 3  s    | ]}  d V  qdS )0123456789ABCDEFN)r|  r<   rq   r  r;   r>   r=  %  s    z$rand_alphanumeric.<locals>.<genexpr>)r   	termerrorrandomrJ   r  )r  r  r;   r  r>   rand_alphanumeric   s   
r  r   r#   r   r  Generator[IO[Any], None, None]c                 c  sR    t | ||d}|V  |  t|  W d   dS 1 s"w   Y  dS )zFOpen a path for I/O and guarantee that the file is flushed and synced.)r  N)r   flushrI   fsyncfileno)rC   r   r  r@  r;   r;   r>   r  (  s   "r  c                   C  s   t dd updtjv S )NKAGGLE_KERNEL_RUN_TYPEkaggle_environments)rI   r  rB   rn   r;   r;   r;   r>   
_is_kaggle4  s   r  c                  C  s0   zt dd} |   W dS  ty   Y dS w )zReturns whether we have internet access.

    Checks for internet access by attempting to open a DNS connection to
    Google's root servers.
    )z8.8.8.85   r#  FT)socketcreate_connectionr   r  )sr;   r;   r>   _has_internet;  s   
r  c                	   C  s0   t  ptjtjtjdddpdtjv S )N~z.kagglezkaggle.jsonkaggle)r  rI   rC   rB  
expanduserrJ   rB   rn   r;   r;   r;   r>   _is_likely_kaggleJ  s   r  c                  C  sP   dt jv r&t jd } t| dr&| j}t|dr&|j}t|dr&t|jdkS dS )NdbutilsshellscappNamezDatabricks ShellF)rB   rn   r2  r  r  r   r  )r  r  r  r;   r;   r>   _is_databricksU  s   




r  c                 C  s(   t j| }|dp|dp|dkS )Nr	  
Dockerfilezrequirements.txt)rI   rC   r  r  r   )rC   r   r;   r;   r>   !_is_py_requirements_or_dockerfilee  s   
r  artifactr%   dict[str, Any]c                 C  s$   dd| j | j| jdd | jdS )NartifactVersionv0r'  r   )r  _versionrO  versionsequenceNameusedAs)rO  source_versionsource_namer   use_as)r  r;   r;   r>   artifact_to_jsonn  s   r  nestedc                 C  sP   |   D ]!}t|trt|d}|r dS qt|tjs t|r%|r% dS qdS )NTF)r  r   rK  #check_dict_contains_nested_artifactr   r%   _is_artifact_string)rJ  r  rB  contains_artifactsr;   r;   r>   r  y  s   

r  configc                 C  s   dd l }tj| d }|dkr+t| }t|W  d    S 1 s$w   Y  d S |dkrJt| }||W  d    S 1 sCw   Y  d S zt| W S  t	yZ   Y d S w )Nr   rw  z.jsonz.yaml)
r3  rI   rC   splitextr   r  rt   r4  r  r   )r   r3  extr@  r;   r;   r>   load_json_yaml_dict  s   
$
$r  rg  c                 C  s@   |  d}t|dkrtddgdt|  | }tt|S )a  Parse paths with the following formats: {item}, {project}/{item}, & {entity}/{project}/{item}.

    Args:
        path: `str`, input path; must be between 0 and 3 in length.

    Returns:
        tuple of length 3 - (item, project, entity)

    Example:
        alias, project, entity = _parse_entity_project_item("myproj/mymodel:best")

        assert entity   == ""
        assert project  == "myproj"
        assert alias    == "mymodel:best"

    r   r:  zYInvalid path: must be str the form {item}, {project}/{item}, or {entity}/{project}/{item}r   )r   r   r   rg  reversed)rC   wordspadded_wordsr;   r;   r>   _parse_entity_project_item  s   
r  aliasesstr | Iterable[str] | Nonec              
   C  sR   | pdg} t | tr| g} z
tt| dhB W S  ty( } ztd|d}~ww )a.  Add the 'latest' alias and ensure that all aliases are unique.

    Takes in `aliases` which can be None, str, or List[str] and returns list[str].
    Ensures that "latest" is always present in the returned list.

    Args:
        aliases: `aliases: str | Iterable[str] | None`

    Returns:
        list[str], with "latest" always present.

    Usage:

    ```python
    aliases = _resolve_aliases(["best", "dev"])
    assert aliases == ["best", "dev", "latest"]

    aliases = _resolve_aliases("boom")
    assert aliases == ["boom", "latest"]
    ```
    latestz"`aliases` must be Iterable or NoneN)r   rY   r  rf  	TypeErrorr   )r  excr;   r;   r>   _resolve_aliases  s   


r  TypeGuard[wandb.Artifact]c                 C  s   t | tjS rA   )r   r   r%   r  r;   r;   r>   _is_artifact_object  s   r  TypeGuard[str]c                 C  s   t | to	| dS )Nwandb-artifact://)r   rY   r   r  r;   r;   r>   r    r  r  TypeGuard[dict]c                 C  s   t | to| ddkS )Nr  r  )r   rK  r  r  r;   r;   r>   _is_artifact_version_weave_dict  r  r  c                 C  s   t | pt| pt| S rA   )r  r  r  r  r;   r;   r>   _is_artifact_representation  s
   r  tuple[str, str | None, bool]c                 C  s   |  dstd|  | tdd  }d }tj|}|jdkr5|j d|j }|j	ddd  }n|	d}|d dkrG|d |d	fS t|d
k rTtd|  |d d
 \}}}| d| d| |dfS )Nr  zInvalid artifact string: r   r   r   r,   r   _idTr:  F)
r   r   r   r   r   r   r   r   rC   r   )r{  parsed_vbase_uriurl_infopartsentityr  name_and_alias_or_versionr;   r;   r>   parse_artifact_string  s   


r  c                  C  s   t j } | d urt| S d S rA   )r   r  max_cli_versionrY   )r  r;   r;   r>   _get_max_cli_version  s   
r  rX  strictstr | bytesr  c                 C  s6   t | tr| ||S t | tr| S tdt| )zCoerce s to str.znot expecting type )r   rb  rc  rY   r  rl  )r   r  r  r;   r;   r>   ensure_text  s
   

r"  c                 C  s,   t dd| }t|dkr|S t dd|S )z0Make an artifact name safe for use in artifacts.z[^a-zA-Z0-9_\-.]rq      z(^.{63}).*(.{63}$)z\g<1>..\g<2>)r   subr   )rX   cleanedr;   r;   r>   make_artifact_name_safe  s   r&  c                 C  s@   t d|  }td|}td|}td|}|r|S dS )z3Make a docker image name safe for use in artifacts.__r   r   )RE_DOCKER_IMAGE_NAME_CHARSr$  r  %RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT$RE_DOCKER_IMAGE_NAME_SEPARATOR_START"RE_DOCKER_IMAGE_NAME_SEPARATOR_END)rX   
safe_charsdedupedtrimmed_starttrimmedr;   r;   r>   make_docker_image_name_safe  s
   r0  sourcedestinationc                 C  s   |   D ]<\}}t|tr"||}t|trt|| q|||< qt|tr<||}t|tr7|| q|||< q|||< q|S )a  Recursively merge two dictionaries.

    This mutates the destination and its nested dictionaries and lists.

    Instances of `dict` are recursively merged and instances of `list`
    are appended to the destination. If the destination type is not
    `dict` or `list`, respectively, the key is overwritten with the
    source value.

    For all other types, the source value overwrites the destination value.
    )rP  r   rK  r  merge_dictsr  extend)r1  r2  rT  r~   node
dest_valuer;   r;   r>   r3  #  s   








r3  r/  c                  G  s   t dd | D dS )zXReturn the first non-none value in the list of arguments.

    Similar to ?? in C#.
    c                 s  s    | ]	}|d ur|V  qd S rA   r;   )r<   ar;   r;   r>   r=  L  s    zcoalesce.<locals>.<genexpr>N)next)r/  r;   r;   r>   coalesceG  s   r9  c                 C  sL   |   D ]\}}t|trt| qt|dr#t|| |< t| |  q| S )Nr  )rP  r   rK  recursive_cast_dictlike_to_dictr2  )rJ  r  r{  r;   r;   r>   r:  O  s   


r:  dict[str, Any] | Anyc                 C  sl   t | ts| S t | tr4i }|  D ]\}}t|}|d ur-t |tr)t|dks-|||< q|r2|S d S d S r   )r   rK  rP  remove_keys_with_none_valuesr   )rJ  new_dictr  r{  new_vr;   r;   r>   r<  Y  s   

r<  niterableIterable[T]Generator[list[T], None, None]c                 c  s@    t |}tt|| }|r|V  tt|| }|sd S d S rA   )iterr  	itertoolsislice)r?  r@  r  batchr;   r;   r>   batchedg  s   rG     c                 C  s   d dd t| D S )zGenerate a random string of a given length.

    :param length: Length of the string to generate.
    :return: Random string.
    r   c                 s  s"    | ]}t tjtj V  qd S rA   )secretsr|  r   ascii_lowercasedigitsr  r;   r;   r>   r=  u  s    
z random_string.<locals>.<genexpr>)rJ   r  r  r;   r;   r>   random_stringo  s   
rL    xsIterable | Iterable[Iterable]ysIterable[Iterable]r  Iterable | Nonesample_sizetuple[list, list, list | None]c                 C  s   t | }t |}|rt |nd}t t t| t| }|t | }t jjt|||d}||  }	||  }
|rH||  nd}|	|
|fS )zSample from a list of lists with weights that decay exponentially.

    May be used with the wandb.plot.line_series function.
    N)r^  rL   )	r  arrayexparanger   sumr  r|  ra  )rN  rP  r  rS  xs_arrayys_array
keys_arrayweightssampled_indices
sampled_xs
sampled_yssampled_keysr;   r;   r>   %sample_with_exponential_decay_weightsz  s   



ra  )frozenc                   @  s"   e Zd ZU dZded< ded< dS )InstalledDistributionzAn installed distribution.

    Attributes:
        key: The distribution name as it would be imported.
        version: The distribution's version string.
    rY   rT  r  N)rl   ru   rv   r  __annotations__r;   r;   r;   r>   rc    s   
 rc  Iterable[InstalledDistribution]c               	   c  sb    ddl m}  |  D ]$}tttt t|jd |j	dV  W d   n1 s)w   Y  q
dS )z2Return the working set of installed distributions.r   )distributionsName)rT  r  N)
importlib.metadatarf  ry  rz  r   UnicodeDecodeErrorr  rc  metadatar  )rf  rJ  r;   r;   r>   working_set  s   
rk  c                  C  s>   t tjd d } |  std|  dt  dt| S )zReturns the path to the wandb-core binary.

    Returns:
        str: The path to the wandb-core package.

    Raises:
        WandbCoreNotAvailableError: If wandb-core was not built for the current system.
    binz
wandb-corezFile not found: zA. Please contact support at support@wandb.com. Your platform is: rf   )pathlibPathrR   rp   rB  r   r   rY   )bin_pathr;   r;   r>   get_core_path  s   	rp  time_strc                 C  sf   ddl }| sdS |d| }|std|  dt|d}|d}ddd	d
ddd}|||  S )a  Parse a time period string and return seconds.

    Args:
        time_str: Time period string like "10s", "5m", "8h", "8d", "6M", "1y"
            Accepted values are:
            - s (seconds)
            - m (minutes)
            - h (hours)
            - d (days)
            - M (months)
            - y (years)

    Returns:
        Number of seconds in the time period

    Raises:
        ValueError: If the format is invalid

    Examples:
        >>> parse_time_period("10s")
        10
        >>> parse_time_period("5m")
        300
        >>> parse_time_period("8d")
        691200
        >>> parse_time_period("6M")
        15552000
        >>> parse_time_period("1y")
        31536000
    r   Nz^(\d+)([smhdMy])$zInvalid time period format: zw. Expected format: <number><unit> where unit is s (seconds), m (minutes), h (hours), d (days), M (months), or y (years)r,   r&  <   i  iQ i ' i3)r  mhrJ  My)r   r!  r   r  r  )rq  r   r!  r*  r  conversionsr;   r;   r>   time_string_to_seconds  s$   

	rx  )r:   r   r   )rX   rY   r:   r^   rf  )rX   rY   r   r   r   r   r:   r   )r:   r   )r   rY   r:   rY   )r   r   r:   r   )r   rY   r:   r   )r   rY   r:   rY   )r   rY   r:   r   )rC   r   r:   r   )rC   rY   r:   rY   rA   )
r   rY   r   rY   r   rY   r   r   r:   r@   )r   r   r:   r   )r   rY   r:   r   r  )rJ  rK  rL  rM  r:   rN  )r   r   r:   rV  )rn  r   r:   r   )rz  rY   r:   r   )r   r   r:   r  )r   r   r  rY   r:   r  )T)r  r   r:   r   )r  )r  r  r:   rY   )r:   r   )r   r   r  r  r  r   r:   r@   )r   r   r  r   r:   rY   )r{  r  r:   r  )r  r   r:   r   )r  r$   r:   r  )r  r   r:   r   )r  r   r:   r  )r  r  r  r  r   r  r:   r  )r  rY   r:   r  )r  r   r  r  r:   r  )r  r   rT  r   r:   r   )r   rY   r:   r   )r#  r  r:   r   )r   r   r:   r   )r:   r   )rR  r   r=  rS  r:   r   )rT  rU  rc  r  rd  re  r:   r  )r:   rC  )rl  r  r:   rm  )rr  rs  rt  ru  r:   rY   )F)r  r  r  r   r:   r   )r  rY   r  rY   r  r   r:   r@   )r  rY   r  r   r:   rb  )r  r   r:   r   )r^  r  r  r  r:   rY   )r^  rY   r  r  r:   r  )r  r   r:   rY   )rC   rY   r:   r"   )r  r  r:   r   r  )rC   r   r:   rY   )r  r   r:   r   )r  N)r  r  r  r  r:   rY   )r   N)rC   r#   r   rY   r  r   r:   r  )r:   r   )rC   rY   r:   r   )r  r%   r:   r  )rJ  rK  r  r   r:   r   )r   rY   r:   r   )rC   rY   r:   rg  )r  r	  r:   r  )r{  r   r:   r  )r{  r   r:   r  )r{  r   r:   r  )r{  r   r:   r   )r{  rY   r:   r  )rX  r   )r   r!  r  rY   r  rY   r:   rY   )rX   rY   r:   rY   )r1  r  r2  r  r:   r  )r/  r   r:   r   )rJ  r  r:   r  )rJ  r;  r:   r;  )r?  r  r@  rA  r:   rB  )rH  )NrM  )
rN  rO  rP  rQ  r  rR  rS  r  r:   rT  )r:   re  )r:   rY   )rq  rY   r:   r  )
__future__r   rn  ry  dataclassesrh  r   importlib.utilrD  r  loggingrD  r  rI   rm  r   r[  r  r   rI  r  r  r   rB   r   r   r`   ri  rj   r   collections.abcr   r   r   r   r   r	   r   r
   gzipr   r   r   r   typingr   r   r   r   r   typing_extensionsr   r   r   r   r   r   	wandb.envwandb.errorsr   r   r   r   wandb.errors.termr   wandb.sdk.libr   r   wandb.sdk.lib.json_utilr    r!   wandb.sdk.lib.pathsr"   r#   r  r$   wandb.sdk.artifacts.artifactr%   r   r   r  r&   	getLoggerrl   r   rf  r   LAUNCH_JOB_ARTIFACT_SLOT_NAMEMAX_LINE_BYTESrC   rB  rJ   rQ   rR   IS_GITDOCKER_IMAGE_NAME_SEPARATORr  r*  r+  r)  r(  r  POW_2_BYTESrW   r\   r]   rw   r   r   r   r  r  r   r   pandas_specrj  r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r
  r  r  r  r  r  r  r  r3  r:  r?  rI  rQ  rm  rt  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"  r2  r5  rQ  rb  rh  rk  rq  r~  r  r  r  r  r  r  r  r  r  r  r  r  rd  r  r  r  r  r  contextmanagerr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"  r&  r0  r3  r9  r:  r<  rG  rL  ra  	dataclassrc  rk  rp  rx  r;   r;   r;   r>   <module>   s   
 

$

	+	,%D	34
5>&
'
'	!
	$
