a
    d=ic?                     @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ eddZeeedd d	d dZeeeeedZed
efdefdefdefdefdefdefdeffZedeZdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zed$d%Z ed&d%Z!ed'd(Z"ed)d*Z#ed+d,Z$ej%d-d.fd/d0Z&d1d2 Z'd3d4 Z(dS )5z>Private utilities for managing multiple TensorBoard processes.    N)version)
tb_logging
_FieldType)serialized_typeruntime_type	serializedeserializec                 C   s   | S N nr
   r
   d/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/tensorboard/manager.py<lambda>2       r   c                 C   s   | S r	   r
   r   r
   r
   r   r   3   r   r   
start_timepidportZpath_prefixlogdirdb	cache_keyTensorBoardInfoc                 C   s   | j rd| j  S d| j S dS )zFormat the data location for the given TensorBoardInfo.

    Args:
      info: A TensorBoardInfo value.

    Returns:
      A human-readable string describing the logdir or database connection
      used by the server: e.g., "logdir /tmp/logs".
    zdb %sz	logdir %sN)r   r   infor
   r
   r   data_source_from_infoO   s    

r   c                    s   t D ]8}t | }tt ||jstd||jt |f q jtjkr^tdtj jf  fddt D }tj|dddS )a  Convert a `TensorBoardInfo` to string form to be stored on disk.

    The format returned by this function is opaque and should only be
    interpreted by `_info_from_string`.

    Args:
      info: A valid `TensorBoardInfo` object.

    Raises:
      ValueError: If any field on `info` is not of the correct type.

    Returns:
      A string representation of the provided `TensorBoardInfo`.
    %expected %r of type %s, but found: %rz*expected 'version' to be %r, but found: %rc                    s"   i | ]}|t | t |qS r
   )_TENSORBOARD_INFO_FIELDSr   getattr).0kr   r
   r   
<dictcomp>z   s   z#_info_to_string.<locals>.<dictcomp>T   )	sort_keysindent)	r   
isinstancer   r   
ValueErrorr   VERSIONjsondumps)r   key
field_type
json_valuer
   r   r   _info_to_string_   s$    

r+   c                 C   s   zt | }W n  ty.   td| f Y n0 t|tsHtd|f tt}t|}|| }|rvtdt|f i }tD ]F}t| }t|| |jstd||j|| f |	|| ||< q~t
f i |S )a  Parse a `TensorBoardInfo` object from its string representation.

    Args:
      info_string: A string representation of a `TensorBoardInfo`, as
        produced by a previous call to `_info_to_string`.

    Returns:
      A `TensorBoardInfo` value.

    Raises:
      ValueError: If the provided string is not valid JSON, or if it is
        missing any required fields, or if any field is of incorrect type.
    zinvalid JSON: %rznot a JSON object: %rz TensorBoardInfo missing keys: %rr   )r&   loadsr$   r#   dict	frozensetr   sortedr   r   r   )Zinfo_stringr*   Zexpected_keysZactual_keysZmissing_keysfieldsr(   r)   r
   r
   r   _info_from_string   s0    
r1   c                 C   sR   t |ttfstd|f | ||d}ttj|dddd}t	|
dS )a  Compute a `TensorBoardInfo.cache_key` field.

    The format returned by this function is opaque. Clients may only
    inspect it by comparing it for equality with other results from this
    function.

    Args:
      working_directory: The directory from which TensorBoard was launched
        and relative to which paths like `--logdir` and `--db` are
        resolved.
      arguments: The command-line args to TensorBoard, as `sys.argv[1:]`.
        Should be a list (or tuple), not an unparsed string. If you have a
        raw shell command, use `shlex.split` before passing it to this
        function.
      configure_kwargs: A dictionary of additional argument values to
        override the textual `arguments`, with the same semantics as in
        `tensorboard.program.TensorBoard.configure`. May be an empty
        dictionary.

    Returns:
      A string such that if two (prospective or actual) TensorBoard
      invocations have the same cache key then it is safe to use one in
      place of the other. The converse is not guaranteed: it is often safe
      to change the order of TensorBoard arguments, or to explicitly set
      them to their default values, or to move them between `arguments`
      and `configure_kwargs`, but such invocations may yield distinct
      cache keys.
    z^'arguments' should be a list of arguments, but found: %r (use `shlex.split` if given a string)working_directory	argumentsconfigure_kwargsT),:)r!   
separatorszutf-8ascii)r#   listtuple	TypeErrorbase64	b64encoder&   r'   encodestrdecode)r3   r4   r5   Zdatumrawr
   r
   r   r      s    c               
   C   sr   t jt d} zt |  W n@ ty` } z(|jtjkrJt j	| rJn W Y d}~nd}~0 0 t 
| d | S )aE  Get path to directory in which to store info files.

    The directory returned by this function is "owned" by this module. If
    the contents of the directory are modified other than via the public
    functions of this module, subsequent behavior is undefined.

    The directory will be created if it does not exist.
    z.tensorboard-infoNi  )ospathjointempfile
gettempdirmakedirsOSErrorerrnoEEXISTisdirchmod)rD   er
   r
   r   _get_info_dir   s    	rO   c                   C   s   t jt dt   S )zGet path to info file for the current process.

    As with `_get_info_dir`, the info directory will be created if it
    does not exist.
    zpid-%d.info)rC   rD   rE   rO   getpidr
   r
   r
   r   _get_info_file_path   s    rQ   c                 C   sF   dt |  }tt d}|| W d   n1 s80    Y  dS )aY  Write TensorBoardInfo to the current process's info file.

    This should be called by `main` once the server is ready. When the
    server shuts down, `remove_info_file` should be called.

    Args:
      tensorboard_info: A valid `TensorBoardInfo` object.

    Raises:
      ValueError: If any field on `info` is not of the correct type.
    z%s
wN)r+   openrQ   write)Ztensorboard_infopayloadoutfiler
   r
   r   write_info_file   s    rW   c               
   C   sJ   zt t  W n4 tyD }  z| jtjkr.n W Y d} ~ n
d} ~ 0 0 dS )zRemove the current process's TensorBoardInfo file, if it exists.

    If the file does not exist, no action is taken and no error is
    raised.
    N)rC   unlinkrQ   rI   rJ   ENOENT)rN   r
   r
   r   remove_info_file  s    rZ   c                  C   s   t  } g }t| D ]}tj| |}z4t|}| }W d   n1 sN0    Y  W n@ ty } z(|jtj	krW Y d}~qn W Y d}~n
d}~0 0 zt
|}W n& ty   t jd|dd Y q0 || q|S )aF  Return TensorBoardInfo values for running TensorBoard processes.

    This function may not provide a perfect snapshot of the set of running
    processes. Its result set may be incomplete if the user has cleaned
    their /tmp/ directory while TensorBoard processes are running. It may
    contain extraneous entries if TensorBoard processes exited uncleanly
    (e.g., with SIGKILL or SIGQUIT).

    Entries in the info directory that do not represent valid
    `TensorBoardInfo` values will be silently ignored.

    Returns:
      A fresh list of `TensorBoardInfo` objects.
    Nzinvalid info file: %rT)exc_info)rO   rC   listdirrD   rE   rS   readIOErrorrJ   EACCESr1   r$   r   Z
get_loggerdebugappend)info_dirresultsfilenamefilepathinfilecontentsrN   r   r
   r
   r   get_all  s*    
*rh   StartReusedr   StartLaunchedStartFailed	exit_codestdoutstderrStartExecFailedZos_errorZexplicit_binaryStartTimedOutr   <   )secondsc              
   C   st  t t | i d}t|}|r(t|dS tjdd\}}tjdd\}}t }tj	dd}	zz&t
j|	du rrdn|	g|  ||d	}
W nF ty } z.t||	d
W  Y d}~W t| t| S d}~0 0 W t| t| nt| t| 0 d}||  }t |k rht| |
 }|durLt|t|t|dS t|}|rt|dS qt|
jdS )a  Start a new TensorBoard instance, or reuse a compatible one.

    If the cache key determined by the provided arguments and the current
    working directory (see `cache_key`) matches the cache key of a running
    TensorBoard process (see `get_all`), that process will be reused.

    Otherwise, a new TensorBoard process will be spawned with the provided
    arguments, using the `tensorboard` binary from the system path.

    Args:
      arguments: List of strings to be passed as arguments to
        `tensorboard`. (If you have a raw command-line string, see
        `shlex.split`.)
      timeout: `datetime.timedelta` object describing how long to wait for
        the subprocess to initialize a TensorBoard server and write its
        `TensorBoardInfo` file. If the info file is not written within
        this time period, `start` will assume that the subprocess is stuck
        in a bad state, and will give up on waiting for it and return a
        `StartTimedOut` result. Note that in such a case the subprocess
        will not be killed. Default value is 60 seconds.

    Returns:
      A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut`
      object.
    r2   r   z.tensorboard-stdout-)prefixz.tensorboard-stderr-ZTENSORBOARD_BINARYNtensorboard)rn   ro   rq   g      ?rl   rs   )r   rC   getcwd_find_matching_instanceri   rF   mkstemptimeenvironget
subprocessPopenrI   rp   closetotal_secondssleeppollrk   _maybe_read_filerj   rr   r   )r4   timeoutZthis_cache_keymatchZ	stdout_fdZstdout_pathZ	stderr_fdZstderr_pathZstart_time_secondsZexplicit_tbprN   Zpoll_interval_secondsZend_time_secondsZsubprocess_resultr   r
   r
   r   startv  sT    







r   c                    s8   t  } fdd|D }t|dd dD ]
}|  S dS )zFind a running TensorBoard instance compatible with the cache key.

    Returns:
      A `TensorBoardInfo` object, or `None` if none matches the cache key.
    c                    s   g | ]}|j  kr|qS r
   r   )r   r   r   r
   r   
<listcomp>  r   z+_find_matching_instance.<locals>.<listcomp>c                 S   s   | j S r	   )r   )xr
   r
   r   r     r   z)_find_matching_instance.<locals>.<lambda>)r(   N)rh   r/   )r   infos
candidates	candidater
   r   r   ry     s
    ry   c              
   C   sz   z6t | }| W  d   W S 1 s*0    Y  W n> tyt } z&|jtjkr`W Y d}~dS W Y d}~n
d}~0 0 dS )zRead the given file, if it exists.

    Args:
      filename: A path to a file.

    Returns:
      A string containing the file contents, or `None` if the file does
      not exist.
    N)rS   r]   r^   rJ   rY   )rd   rf   rN   r
   r
   r   r     s    

,r   ))__doc__r=   collectionsdatetimerJ   r&   rC   r~   rF   r{   rw   r   Ztensorboard.utilr   
namedtupler   intZ	_type_intr@   Z	_type_strOrderedDictr   r   r   r+   r1   r   rO   rQ   rW   rZ   rh   ri   rj   rk   rp   rr   	timedeltar   ry   r   r
   r
   r
   r   <module>   s   	",/	1G