o
    mi=                     @   sX  U 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Zd dl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'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6Z6d dl7Z7d dl8Z8d dl9Z8d dl:m;Z;m<Z<m=Z=m>Z>m?Z? d d	l@mAZA d d
lBmCZCmDZD d dlEmFZFmGZG d dlHmIZImJZJ e(rd dlKZLd dlMZ8d dlNZ8d dlOmPZP e*eQge5eRe"f f ZSe4dZTe
UeVZWeX ZYdZZdZ[ej\]ej\^ej\_e`ddZadZbecdeb Zdecebd Zeecebd ZfecdZgear]dZhndZhg dZig dZjde*fddZkdelde)fd d!ZmG d"d# d#ZnG d$d% d%ej%Zodeldej%fd&d'Zp		(dmdeld)e0e5eleRf  d*eRde)fd+d,Zqde0d- fd.d/Zreqd0Zsd1Ztejuvd2Zwewdurd(Ztd3Zxd4eldelfd5d6Zyd7e)de)fd8d9Zzd7e)de)fd:d;Z{d<eldeRfd=d>Z|d?eldelfd@dAZ}dBelde0el fdCdDZ~	dndEeldFeldGeldHe0e* ddf
dIdJZdKe)deRfdLdMZdNeldeRfdOdPZdNeldeRfdQdRZdKe)deRfdSdTZdNeldeRfdUdVZdNeldeRfdWdXZdKe)de0e) fdYdZZdNeldeRfd[d\ZdNeldeRfd]d^ZdNeldeRfd_d`ZdNeldeRfdadbZdNeldeRfdcddZdKe)deRfdedfZdKe)deRfdgdhZdKe)de)fdidjZdKe)de)fdkdlZdKe)deRfdmdnZdKe)de)fdodpZ	dndqe+dre0e+ee+f  de3e+eRf fdsdtZdKe)de5e3e)eRf e3e5delef eRf f fdudvZdwe)de)fdxdyZdzeldeRfd{d|ZdKe)de)fd}d~ZdKe)de3e)eRf fddZdKe)delde3e)eRf fddZdodeRdeRfddZdpdedelfddZde)fddZG dd de	jZG dd de	jZG dd de	jZG dd de	jZdKe)de'el de)ddfddZdKe)de)delfddZdKe)de'el de)ddfddZdKe)de)delfddZde5eeele/e1f de5eeelf fddZdKe)de)fddZdeQdeRfddZde6jde.el fddZde)deRfddZde)de0eR fddZde)de0eR fddZ	dndeSde*eQge0eR f de0e" deSfddZdelde5dee.el f fddZde1dedefddZde/de)deRfddZdelfddZdelde)fddĄZde.el de0el fddǄZde)de)fddʄZde0el fdd̄Z	dnde*de0e5eef  de*fddЄZdddede5eef defddքZdefdd؄Zdede.e.e  fddۄZ		1dqde5eedf deRdelfdd߄Z		1dqde1el de5eedf deRdelfddZdrde1e deRde0el fddZ	dndeldelde0el ddfddZdndelde0el defddZde'deRfddZÐdndede0e.e3ele)f   delfddZĐdndelde0e.e3ele)f   defddZde0el delfddZdeldelfddZdeldeIfddZde.el deRfdd ZG dd dZdae0e e̐d< delde*ddfddZde0el delfdd	Zde0el delfd
dZϐde2deRfddZdeRfddZ	dsdede0e5e%ejf  delfddZej	dtdeJdelde0el de,e'e) ddf fddZdeRfddZdeRfddZdeRfddZdeldeRfdd Zِd!d"de+ele)f fd#d$Zڐdrdqeېd%eRdeRfd&d'Zܐd(elde)fd)d*Zdeldefd+d,Zߐd-e0e5ele-el f  de.el fd.d/Zde)deRfd0d1Zde)deRfd2d3Zde)deRfd4d5Zde)deRfd6d7Zdelde3ele0el eRf fd8d9Zde5eldf fd:d;ZdeRfd<d=Z	?dud<e5elef deld@eldelfdAdBZdeldelfdCdDZdeldelfdEdFZdGe+ele)f dHe+ele)f de+ele)f fdIdJZdKe)de)fdLdMZdqe+ele)f de+ele)f fdNdOZdqe5e+ele)f e)f de5e+ele)f e)f fdPdQZdRedSe-eT de,e.eT ddf fdTdUZdvdedelfdWdXZ		YdwdZe5e-e-e- f d[e-e- d\e0e- d]ede3e.e.e0e. f f
d^d_Zejd(d`G dadb dbZde-e fdcddZdeelddffdgdhZdelfdidjZG dkdl dle7jZdS (x      N)asdictis_dataclass)datedatetime	timedelta)import_module)	getsizeof)
ModuleType)IOTYPE_CHECKINGAnyCallableDict	GeneratorIterableListMappingOptionalSequenceTextIOTupleTypeVarUnion)AuthenticationError	CommError
UsageErrorWandbCoreNotAvailableErrorterm)_thread_local_api_settings)
filesystemrunid)dumpdumps)FilePathStrStrPath)ArtifactT
_wandb_jobi p z..z.gitz(?:__|[._]|[-]+)^$z{2,}z[^a-z0-9._\-]development
production)B   )KBi  )MBi@B )GBi ʚ;)TBl    J))PBl     I5 )EBl     NZo)r,   )KiB   )MiBi   )GiBi   @)TiBl        )PiBl           )EiBl            returnc                     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=   H/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/util.py
<listcomp>   s    z vendor_setup.<locals>.<listcomp>r<   Nc                      s
    t _d S N)syspathr=   )original_pathr=   r@   reset_import_path      
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=   )osrD   join)r>   p)
vendor_dirr=   r@   rA          r.   r<   N)rC   rD   rJ   abspathdirname__file__rK   insert)rF   
parent_dirvendor_packagespackage_dirsrL   r=   )rE   rM   r@   vendor_setup   s   
rW   namec                 C   s   t  }t| }|  |S rB   )rW   r   )rX   
reset_pathmoduler=   r=   r@   vendor_import   s   r[   c                   @   s*   e Zd ZdejddfddZdddZdS )	LazyModuleStaterZ   r<   Nc                 C   s   || _ d| _t | _d S NF)rZ   load_started	threadingRLocklockselfrZ   r=   r=   r@   __init__   s   zLazyModuleState.__init__c                 C   s   | j 7 | 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_W d    d S 1 s=w   Y  d S NT)	ra   r^   rZ   __spec__loaderexec_moduletypesr	   	__class__rc   r=   r=   r@   load   s   "zLazyModuleState.loadrO   )__name__
__module____qualname__ri   r	   rd   rl   r=   r=   r=   r@   r\      s    r\   c                   @   sF   e Zd ZdedefddZdededdfddZdeddfd	d
ZdS )
LazyModulerX   r<   c                 C   s    t | d}|  t | |S N__lazy_module_state__)object__getattribute__rl   rc   rX   stater=   r=   r@   rt      s   zLazyModule.__getattribute__valueNc                 C   s&   t | d}|  t | || d S rq   )rs   rt   rl   __setattr__)rc   rX   rw   rv   r=   r=   r@   rx      s   zLazyModule.__setattr__c                 C   s$   t | d}|  t | | d S rq   )rs   rt   rl   __delattr__ru   r=   r=   r@   ry      s   zLazyModule.__delattr__)rm   rn   ro   strr   rt   rx   ry   r=   r=   r=   r@   rp      s    rp   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)rC   modulesKeyError	importlibutil	find_specModuleNotFoundErrormodule_from_specr\   rr   rp   rj   )rX   specrZ   r=   r=   r@   import_module_lazy   s   	

r   Trequiredlazyc                 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   zimportlib.ModuleInterfacec                 C   s   t | S rB   )r   )rX   r=   r=   r@   get_optional_module   s   r   numpyFpandasi api_urlc                 C   sr   t j }|durt|dS d| v r| dddS d| v r*| dddS d| v r7| dddS | S )z5Return the frontend app url without a trailing slash.N/z://api.wandb.testz://api.z://app.z://api.wandb.://)r   envget_app_urlrz   stripreplace)r   app_urlr=   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.
    .)zbuiltins.modulez__builtin__.module)rj   rn   rm   )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.Tensorr   r   )r   is_tf_tensor_typenameis_pytorch_tensor_typenamerj   rn   splitrm   )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_uri6  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   rD   requesturl2pathname)r   rD   r=   r=   r@   local_file_uri_to_path;  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_noneD  s   
r   output_filename
source_dirarchive_namecustom_filterc           
   	      s  dddt d f fdd}t \}}zpt|d}|j|||d W d    n1 s-w   Y  tjdt| d	d	d
d$}t|d}	||		  W d    n1 sVw   Y  W d    n1 sew   Y  W t
| t
| d S W t
| t
| d S t
| t
| w )Ntar_infoztarfile.TarInfor<   c                    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 wbr   )filenamefileobjmoder   rb)r   tempfilemkstemptarfileopenr   gzipGzipFilewritereadrJ   closeremove)
r   r   r   r   r   
descriptorunzipped_filenametargzipped_tartar_filer=   r   r@   make_tarfileU  s.   
 


r   objc                 C      dd l }t| |jS r   )
tensorflow
isinstanceTensor)r   r   r=   r=   r@   is_tf_tensoro     r   r   c                 C      |  dod| v pd| v S )Ntensorflow.r   Variabler   r   r=   r=   r@   r   u     
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   s   dd l }|| S r   )jax
device_get)r   r   r=   r=   r@   get_jax_tensor  s   
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  rG   r   c                 C   r   )Nplotly.r   r   r=   r=   r@   is_plotly_typename  rG   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 rB   )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   s~   ddl }ddlm} ddlm} dtdtfdd}||_| |jkr'| 	 } | S t
| |s=t| d	r=| j} t
| |s=t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)Spinerc   r<   c                 S   sb   | j pd}t|tr|dkrd}n|dkrd}t|dkr!td|\}}|dkr/|d	kr/d
S d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   TF)	_positionr   rz   r   
ValueError)rc   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.)
matplotlibmatplotlib.figurer   matplotlib.spinesr  r   boolr  pyplotgcfr   hasattrr  r
  )r   r  r   r  r  r=   r=   r@   ensure_matplotlib_figure  s    
	


r  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   )r  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>)r  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   
r-  dvisitedc                 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)dictiditemsr   _sanitize_numpy_keysr   r*  r-  )r.  r/  out	convertedkeyrw   converted_valuer=   r=   r@   r3    s    

r3  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0t1| j2t,|  | |fS )z>Convert an object into something that's more becoming of JSON.Tr.   r       utf-8ro   rn   r   NFz.Serializing object of type {} that is {} bytes)3r   r   r   r   evalRuntimeErrorr   r   requires_graddetachAttributeErrorr  sizecpur&  r   r   r   flattentolistr   r   r*  r-  bytesdecoder   r   	isoformatcallabler  rn   ro   rz   r'  r(  r)  r0  r3  settupleenumEnumrX   r   VALUE_BYTES_LIMITr   termwarnformattyperm   )r   r5  r   r=   r=   r@   json_friendly,  s~   








rO  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| rXt | tsXt| }|S | jjdvrbt
| } | S )zJMake any value (including dict, slice, sequence, dataclass) JSON friendly.)slice_start
slice_step
slice_stop)builtins__builtin__)r   r0  r2  json_friendly_valslicestartstepstoprO  r   rz   appendr   rN  r   rj   rn   )rP  r5  r6  rw   _r=   r=   r@   rV  r  s,   

rV  aliasc                 C   s(   t | dko| d dko| dd   S )Nr  r   vr.   )r   	isnumeric)r]  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 )Nr  r  r  plotly)_typeplot)r   r   r   r  r   to_plotly_jsonr  r=   r=   r@   convert_plots  s   
re  c                 C   s8   t rt| t jr| jdkrtj| dd dfS | dfS )Nr8  )num_binsTF)r   r   r   r?  r   	Histogramto_jsonr   r=   r=   r@   maybe_compress_history  s   ri  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 )	Nr8  
      K   Z   )
rb  varmeanminmaxz10%z25%z75%z90%r?  TF)
r   r   r   r?  ro  r&  rp  aminamax
percentile)r   rj  r=   r=   r@   maybe_compress_summary  s   



rv  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 rB   )rJ   getenv)r>   ro  r=   r=   r@   r!    s    

z!launch_browser.<locals>.<genexpr>FrX   )
webbrowserrC   platformr"  getr  rX   r   )rw  _display_variables_webbrowser_names_blocklistr  launch_browserbrowserr=   r=   r@   r    s.   r     lengthc                 C   
   t | S rB   )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)rJ   r  jsonloadsenvironr
  r=   r=   r=   r@   parse_tfjob_config  s   
r  c                   @   "   e Zd ZdZdedefddZdS )WandBJSONEncoder-A JSON Encoder that handles some extra types.r   r<   c                 C   s4   t |dr	| S t|\}}|r|S tj| |S )Njson_encode)r  r  rO  r  JSONEncoderdefault)rc   r   tmp_objr5  r=   r=   r@   r    s   
zWandBJSONEncoder.defaultNrm   rn   ro   __doc__r   r  r=   r=   r=   r@   r        r  c                   @   r  )WandBJSONEncoderOldr  r   r<   c                 C   s4   t |\}}t|t|\}}|r|S tj| |S rB   )rO  rv  r   r  r  r  )rc   r   r  r5  
compressedr=   r=   r@   r    s
   zWandBJSONEncoderOld.defaultNr  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<   c                 C   s.   t |\}}t|\}}|r|S tj| |S rB   )rO  ri  r  r  r  )rc   r   r5  r  r=   r=   r@   r    s
   zWandBHistoryJSONEncoder.defaultNr  r=   r=   r=   r@   r         r  c                   @   r  )JSONEncoderUncompressedr  r   r<   c                 C   s6   t |r| S trt|tjr| }tj| |S rB   )	r   rB  r   r   r*  r&  r  r  r  )rc   r   r=   r=   r@   r    s
   zJSONEncoderUncompressed.defaultNr  r=   r=   r=   r@   r    r  r  fp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_safer     r  c                 K      t | fdti|S r  )r"   r  r   r  r=   r=   r@   json_dumps_safer!     r  c                 K   r  r  )r!   r  r  r=   r=   r@   json_dump_uncompressed'  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^  c                 C   s   t | ttfr	| S t| S )z,If v is not a basic type convert it to json.)r   r'  intr  r^  r=   r=   r@   make_json_if_not_number1  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>=  rN   z&make_safe_for_json.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r=   r  )r>   r^  r=   r=   r@   rA   B  s    z&make_safe_for_json.<locals>.<listcomp>NaNz+infInfinityz-infz	-Infinity)r   r   r2  rz   r   r'  r   r=   r=   r@   r  :  s   



r  ec                 C   sn   t | tj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 )NT  i  i  errorsr   message)	r   requests	HTTPErrorresponsestatus_coder  r  contentr   )r  bodyr=   r=   r@   no_retry_4xxN  s   r  r  c                 C   sx   g }z|   }W n ty   | Y S w d|v r:t|d tr:|d D ]}t|tr.d|i}d|v r9||d  q#|S )Nr  r  )r  r
  r   listrz   r[  )r  r  r  errorr=   r=   r@   parse_backend_error_messagesX  s   
r  c                 C   s   t | dr| j} t| tj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rAtdtj	j
 d| jj d	| jj d
| jjdkrbtjrStdtjj td| jj d	| jj d
| jjdkr~t| jrodS td| jj d	| jj d
dS )Nr   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   r   r  r  r  r  r   r   r   API_KEYreasonrunr   rD   r  LookupErrorr  r=   r=   r@   no_retry_authi  sR   

	
r  c                 C   s:   t | dr| j} t| tj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   Nr  Tr  r   r   r  r  r  r  r  r=   r=   r@   check_retry_conflict  s   
r  c                 C   sJ   t | dr| j} t| tj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   Nr  Ti  Fr  r  r=   r=   r@   check_retry_conflict_or_gone  s   
r  fallback_retry_fncheck_fncheck_timedeltac                    s&   dt dtttf f 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<   c                    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_fn)r   r   r  r   )r  r  r  r  r=   r  r@   make_check_retry_fn  s   "
r  programc                 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)rJ   rD   isfileaccessX_OKr   OSErrorreadliner   r   shlexr   r   rC   
executable)r  opened
first_liner=   r=   r@   find_runner  s   	

r  valuestarget_lengthc                 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   r'  ranger[  r  )r  r  ratioresultir=   r=   r@   
downsample  s   r  
dictionaryr6  c                 C   s   || v ot | | tjS rB   )r   numbersNumber)r  r6  r=   r=   r@   has_num     r  c                   C   s"   t jdur
t jjjS tjddS )zLog file path used in error messages.

    It would probably be better if this pointed to a log file in a
    run directory.
    Nr   zdebug-internal.log)r   r  	_settingslog_internalrJ   rD   rK   r=   r=   r=   r@   get_log_file_path  s   

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)rematch)r  r=   r=   r@   docker_image_regex  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   r[  r  )	r  	bool_args	last_flaglast_argpossible_imagesr  argmost_likelyimgr=   r=   r@   image_from_docker_args  s:   


r
  r   c                 C   r  rB   )yaml	safe_load)r   r=   r=   r@   	load_yamlP  rG   r  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	t d
t dt ddt d}ztj|dddd| id}|  W n t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 r   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.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containerStatusesr   imageIDzdocker-pullable://z&Error checking kubernetes for image id)rJ   rD   existsr   r   FileNotFoundErrorr   warningPermissionErrorgetuidr   rL  rM  r  r  r  raise_for_statusRequestExceptionrz   r  r   r
  r|   
IndexErrorr   )
token_path
token_filetokenr  current_uidr  
k8s_serverresr=   r=   r@   image_id_from_k8sT  sf   






r(  targetr  c              	      s\   t   dddtdtdtffdddtdtdtttdf td	 f f 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<   c              
      sL   z|   |i | W d S  ty% } z|  | W Y d }~d S d }~ww rB   )putr   )r*  r  r  r  )r)  r=   r@   wrapped_target  s   z"async_call.<locals>.wrapped_targetthreading.Thread)Nr.  c                     st   t j f|  |d}d|_|  z d}t|tr'|t	 d ||fW S  t
jy9   d |f Y S w )N)r)  r  r  Tr  )r_   ThreaddaemonrX  r  r   r   with_tracebackrC   exc_infoqueueEmpty)r  r  threadr  )r*  r  r-  r=   r@   wrapper  s   

zasync_call.<locals>.wrapper)r3  Queuer   r   r   r   )r)  r  r6  r=   )r*  r)  r  r-  r@   
async_call  s   r8  r*  r+  	max_itemsqueue_timeoutc              	   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 re   )r  r3  r4  r  
get_nowaitr[  )r*  r9  r:  r&  r2  r\  r=   r=   r@   read_many_from_queue  s   r<  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   r?  class_countc                    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  r@  r=   r@   rA     s    z class_colors.<locals>.<listcomp>r.   )r  rC  r=   rC  r@   class_colors  s   
rD  input_timeoutjupyterc                 C   sl   t }tj}| d urddlm} tj|j| d}t dkrd}| d}|t kr.||}|S |||d}|S )Nr   )timed_input)r  Windowsr   z: Enter your choice: )rF  )	inputr   
LOG_STRINGwandb.sdk.librG  	functoolspartialr  system)rE  rF  input_fnpromptrG  textchoicer=   r=   r@   _prompt_choice  s   
rS  choicesc                 C   s   t | D ]\}}td|d  d|  qd}|dk s$|t| d kr^t||d}|s-qd}zt|d }W n	 ty@   Y nw |dk sM|t| d krRtd |dk s$|t| d ks$| | }td| |S )	z.Allow a user to choose from a list of options.(r.   z) r   )rE  rF  zInvalid choicez
You chose )r  r   termlogr   rS  r  r
  rL  )rT  rE  rF  r  rR  idxr  r=   r=   r@   prompt_choices  s&   
rY  shape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     rV  )r.   r  r]  segmentation_maskN)r   )rZ  r[  r=   r=   r@   guess_data_type  s   r_  	dest_path
source_urlapi_keyc                 C   s   d }t jsd|p	df}tj||t jt jddd}|  tj| v r*t	tj
|  t| d}|jddD ]}|| q6W d    d S 1 sIw   Y  d S )	Napir   T   authr  cookiesstreamr  r   r6   )
chunk_size)r   rg  r  r  r  r  rJ   sepr   mkdir_exists_okrD   rQ   
fsync_openiter_contentr   )r`  ra  rb  rf  r  r   r  r=   r=   r@   download_file_from_url   s&   
"rn  c                 C   s>   d }t jsd|p	df}tj| |t jt jddd}|  |jS )Nrc  r   Trd  re  )r   rg  r  r  r  r  r  )ra  rb  rf  r  r=   r=   r@   download_file_into_memory7  s   ro  obc                 C   s   t | do|  S )Nisatty)r  rq  )rp  r=   r=   r@   rq  G  r   rq  r?  unitsc                 C   sX   |pt }|d \}}tt| | d}|dk st|dkr#| | S t| |dd  S )Nr   r.   r6   )POW_10_BYTESroundr'  r   to_human_size)r?  rr  unitrw   factorr=   r=   r@   ru  K  s   
ru  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>   rv  rw   r=   r=   r@   r  X  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  )rs  r  compilerM  rK   keys
IGNORECASEr  r
  r'  grouprx  r  )r?  rr  
units_dictregexr  rw  rv  r=   r=   r@   from_human_sizeV  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uncategorizedr   r  r\  )wandb.sdk.lib.gitlibr  root_dirto_native_slash_pathrJ   rD   basenamerz   isabsrK   curdirrQ   rP   r   relpathr   rj  )r  r  r  	repo_nameprog_dirprojectsub_pathr=   r=   r@   auto_project_namef  s$   
r  rD   c                 C   s   t  dkr| dd} | S )NrH  \r   )r  rN  r   rD   r=   r=   r@   to_forward_slash_path  s   r  c                 C   s   t | dtjS )Nr   )r#   r   rJ   rj  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   rL  )r  r=   r=   r@   check_and_warn_old  s   
r  c                   @   s   e Zd ZdddZdededdfddZdd	d
ZdddZ	ddede	e de	d  fddZ
dedefddZdeedf fddZdedefddZdS )ImportMetaHookr<   Nc                 C   s   t  | _t  | _d S rB   )r0  r{   	on_importrk   r=   r=   r@   rd     s   zImportMetaHook.__init__fullnamer  c                 C   s   | j |g | d S rB   )r  
setdefaultr[  )rc   r  r  r=   r=   r@   r     r  zImportMetaHook.addc                 C   s   t jd|  d S r   )rC   	meta_pathrS   rk   r=   r=   r@   install  r   zImportMetaHook.installc                 C   s   t j|  d S rB   )rC   r  r   rk   r=   r=   r@   	uninstall  r   zImportMetaHook.uninstallrD   c                 C   s   || j v r| S d S rB   )r  )rc   r  rD   r=   r=   r@   find_module  s   
zImportMetaHook.find_modulec                 C   sH   |    t|}|   || j|< | j|}|r"|D ]}|  q|S rB   )r  r}   r   r  r{   r  r  )rc   r  mod
on_importsr$  r=   r=   r@   load_module  s   

zImportMetaHook.load_module.c                 C   s
   t | jS rB   )rH  r{   rk   r=   r=   r@   get_modules  rG   zImportMetaHook.get_modulesrZ   c                 C   s
   | j | S rB   )r{   rb   r=   r=   r@   r     rG   zImportMetaHook.get_modulerO   rB   )rm   rn   ro   rd   rz   r   r   r  r  r   r  r	   r  r   r  r   r=   r=   r=   r@   r    s     



r  _import_hookr  r  c                 C   s&   t d u rt a t   t | | d S rB   )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   rz   r   )rD   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   rD   rz   )rD   r  r   r=   r=   r@   uri_from_path  s   "r  rh  c                 C   s    t | dd}|r| dv S dS )z)Return True if the stream supports UTF-8.encodingN>   utf_8r9  F)getattrlower)rh  r  r=   r=   r@   is_unicode_safe  s   r  c                  C   s0   zt dd} |   W dS  ty   Y dS w )z9Attempt to open a DNS connection to Googles root servers.)z8.8.8.85   r  TF)socketcreate_connectionr   r  )sr=   r=   r@   _has_internet  s   r  randc                    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)rR  r>   r\  r  r=   r@   r!    s    z$rand_alphanumeric.<locals>.<genexpr>)r   	termerrorrandomrK   r  )r  r  r=   r  r@   rand_alphanumeric  s   
r  r   r   r  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   flushrJ   fsyncfileno)rD   r   r  r$  r=   r=   r@   rl    s   "rl  c                   C   s   t dd updtjv S )NKAGGLE_KERNEL_RUN_TYPEkaggle_environments)rJ   r  rC   r{   r=   r=   r=   r@   
_is_kaggle  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  rJ   rD   r  
expanduserrK   rC   r{   r=   r=   r=   r@   _is_likely_kaggle  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)rC   r{   r  r  r  r  r  )r  r  r  r=   r=   r@   _is_databricks
  s   




r  c                 C   s(   t j| }|dp|dp|dkS )Nr  
Dockerfilezrequirements.txt)rJ   rD   r  r   r   )rD   r   r=   r=   r@   !_is_py_requirements_or_dockerfile  s   
r  artifactr%   c                 C   s$   dd| j | j| jdd | jdS )NartifactVersionv0r  r   )rb  _versionr1  versionsequenceNameusedAs)r1  source_versionsource_namer   use_as)r  r=   r=   r@   artifact_to_json#  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   r0  #check_dict_contains_nested_artifactr   r%   _is_artifact_string)r.  r  r&  contains_artifactsr=   r=   r@   r  .  s   

r  configc                 C   s   t j| d }|dkr't| }t|W  d    S 1 s w   Y  d S |dkrFt| }t|W  d    S 1 s?w   Y  d S zt| W S  t	yV   Y d S w )NrV  z.jsonz.yaml)
rJ   rD   splitextr   r  rl   r  r  r  r
  )r  extr$  r=   r=   r@   load_json_yaml_dict9  s   
$
$r  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
  rH  reversed)rD   wordspadded_wordsr=   r=   r@   _parse_entity_project_itemH  s   
r  aliasesc              
   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: `Optional[Union[str, List[str]]]`

    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   rz   r  rG  	TypeErrorr
  )r  excr=   r=   r@   _resolve_aliasesb  s   


r  c                 C   s   t | tjS rB   )r   r   r%   r  r=   r=   r@   _is_artifact_object  s   r  c                 C   s   t | to	| dS )Nwandb-artifact://)r   rz   r   r  r=   r=   r@   r    r   r  c                 C   s   t | to| ddkS )Nrb  r  )r   r0  r  r  r=   r=   r@   _is_artifact_version_weave_dict  r  r  c                 C   s   t | pt| pt| S rB   )r  r  r  r  r=   r=   r@   _is_artifact_representation  s
   r  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   rD   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 rB   )r   rc  max_cli_versionrz   )r  r=   r=   r@   _get_max_cli_version  s   
r  c                   C   s    t jd uo	t jjjpt  jjS rB   )r   r  settings_offlinesetupr=   r=   r=   r@   _is_offline  s   
r  r9  strictr  c                 C   s6   t | tr| ||S t | tr| S tdt| )zCoerce s to str.znot expecting type )r   rC  rD  rz   r  rN  )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_\-.]r\     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
   r  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.
    )r2  r   r0  r  merge_dictsr  extend)r  r  r6  rw   node
dest_valuer=   r=   r@   r    s   








r  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 rB   r=   )r>   ar=   r=   r@   r!    s    zcoalesce.<locals>.<genexpr>N)next)r  r=   r=   r@   coalesce   s   r  c                 C   sL   |   D ]\}}t|trt| qt|dr#t|| |< t| |  q| S )Nr{  )r2  r   r0  recursive_cast_dictlike_to_dictr  )r.  r  r^  r=   r=   r@   r    s   


r  c                 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   r0  r2  remove_keys_with_none_valuesr   )r.  new_dictr  r^  new_vr=   r=   r@   r    s   

r  niterablec                 c   s@    t |}tt|| }|r|V  tt|| }|sd S d S rB   )iterr  	itertoolsislice)r  r  r  batchr=   r=   r@   batched"  s   r     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 rB   )secretsrR  r   ascii_lowercasedigitsr  r=   r=   r@   r!  0  s    
z random_string.<locals>.<genexpr>)rK   r  r  r=   r=   r@   random_string*  s   
r    xsysr{  sample_sizec                 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  rR  rB  )r  r   r{  r!  xs_arrayys_array
keys_arrayweightssampled_indices
sampled_xs
sampled_yssampled_keysr=   r=   r@   %sample_with_exponential_decay_weights5  s   


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

    Attributes:
        key: The distribution name as it would be imported.
        version: The distribution's version string.
    r6  r  N)rm   rn   ro   r  rz   __annotations__r=   r=   r=   r@   r0  L  s   
 r0  c               
   c   sN    ddl m}  |  D ]}zt|jd |jdV  W q
 ttfy$   Y q
w dS )z2Return the working set of installed distributions.r   )distributionsName)r6  r  N)importlib.metadatar2  r0  metadatar  r|   UnicodeDecodeError)r2  r.  r=   r=   r@   working_setY  s   
	r7  r  zpackaging.version.Versionc                 C   s<   zddl m} W || S  ty   ddlm} Y || S w )a!  Parse a version string into a version object.

    This function is a wrapper around the `packaging.version.parse` function, which
    is used to parse version strings into version objects. If the `packaging` library
    is not installed, it falls back to the `pkg_resources` library.
    r   )r   )parse_version)packaging.versionr   ImportErrorpkg_resourcesr8  )r  r8  r=   r=   r@   r8  l  s   r8  c                  C   sf   t jdd} | rtd|  d | S ttjd d }|	 s/t
d| dt  d	t|S )
at  Returns the path to the wandb-core binary.

    The path can be set explicitly via the _WANDB_CORE_PATH environment
    variable. Otherwise, the path to the binary in the current package
    is returned.

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

    Raises:
        WandbCoreNotAvailableError: If wandb-core was not built for the current system.
    _WANDB_CORE_PATHr   z-Using wandb-core from path `_WANDB_CORE_PATH=z>`. This is a development feature and may not work as expected.binz
wandb-corezFile not found: zA. Please contact support at support@wandb.com. Your platform is: r   )rJ   r  r  r   rL  pathlibPathrR   parentr  r   r  rz   )path_from_envbin_pathr=   r=   r@   get_core_path{  s   
rC  c                       s"   e Zd ZdZd fdd	Z  ZS )NonOctalStringDumperzPrevents strings containing non-octal values like "008" and "009" from being converted to numbers in in the yaml string saved as the sweep config.Nc                    s@   |dkr| drt|dkrt j||ddS t |||S )Nztag:yaml.org,2002:str0r.   ')style)r   r   superrepresent_scalar)rc   tagrw   rG  rj   r=   r@   rI    s   z%NonOctalStringDumper.represent_scalarrB   )rm   rn   ro   r  rI  __classcell__r=   r=   rK  r@   rD    r  rD  re   rB   )T)r  r]   )F)r  N)r   N)r9  r  )r  )Nr  )rA  
contextlibdataclassesrI  rL  r   r}   importlib.utilr  r  loggingr(  r  rJ   r>  r  r3  r  r  r  r  r  r   rC   r   r   r_   r=  ri   r   r   r   r   r   r   r   r   r	   typingr
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   	wandb.envwandb.errorsr   r   r   r   r   (wandb.sdk.internal.thread_local_settingsr   rK  r   r    wandb.sdk.lib.json_utilr!   r"   wandb.sdk.lib.pathsr#   r$   r9  	packaging"wandb.sdk.internal.settings_staticwandb.sdk.wandb_settingswandb.sdk.artifacts.artifactr%   r   r  CheckRetryFnTyper&   	getLoggerrm   r   rG  r   LAUNCH_JOB_ARTIFACT_SLOT_NAMEMAX_LINE_BYTESrD   r  rK   rQ   rR   IS_GITDOCKER_IMAGE_NAME_SEPARATORrz  r  r  r  r  
SENTRY_ENVrs  POW_2_BYTESrW   rz   r[   r\   rp   r   r   r   r   r   r~   r   pandas_specrK  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  r3  r'  rO  rV  r`  re  ri  rv  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  Responser  r  r  r  r  r  r  r  r  r  r  r
  r  r(  r8  r<  r?  rD  rS  rY  r_  rn  rC  ro  rq  ru  r  r  r  r  r  r  r  r1  r  r  r  r  r  Randomr  contextmanagerrl  r  r  r  r  r  r0  r  r  rH  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r.  	dataclassr0  r7  r8  rC  DumperrD  r=   r=   r=   r@   <module>   s  
 D
 

$


	
	0

%$
F
	
2
 
5=
&

	

"
**
'"	 ,!$

	


$&
0"