a
    d=icp9                     @   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ZdZdZdd Zd	d
 Zdd Zdd Zdd Zdd Zdd Zd"ddZd#ddZdd Zdd Zdd Zd d! ZdS )$zvUtilities for using TensorBoard in notebook contexts, like Colab.

These APIs are experimental and subject to change.
    N)manager_CONTEXT_COLAB_CONTEXT_IPYTHON_CONTEXT_NONEc                  C   sz   zddl } ddl}W n ty&   Y n0 | dur8tS zddl}W n tyV   Y n 0 | }|durv|drvtS tS )a  Determine the most specific context that we're in.

    Returns:
      _CONTEXT_COLAB: If in Colab with an IPython notebook context.
      _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
        context (e.g., from running `jupyter notebook` at the command
        line).
      _CONTEXT_NONE: Otherwise (e.g., by running a Python script at the
        command-line or using the `ipython` interactive shell).
    r   NZkernel)Zgoogle.colabIPythonImportErrorget_ipythonr   Z	has_traitr   r   )Zgoogler   ipython r
   e/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/tensorboard/notebook.py_get_context(   s    r   c                 C   s   t ddS )z^Deprecated: use `%load_ext tensorboard` instead.

    Raises:
      RuntimeError: Always.
    zHUse '%load_ext tensorboard' instead of '%load_ext tensorboard.notebook'.N)RuntimeErrorr	   r
   r
   r   load_ipython_extensionO   s    r   c                 C   s   t |  dS )zLoad the TensorBoard notebook extension.

    Intended to be called from `%load_ext tensorboard`. Do not invoke this
    directly.

    Args:
      ipython: An `IPython.InteractiveShell` instance.
    N)_register_magicsr   r
   r
   r   _load_ipython_extensionZ   s    	r   c                 C   s   | j tddd dS )zaRegister IPython line/cell magics.

    Args:
      ipython: An `InteractiveShell` instance.
    linetensorboard)Z
magic_kindZ
magic_nameN)Zregister_magic_function_start_magicr   r
   r
   r   r   f   s
    r   c                 C   s   t | S )z0Implementation of the `%tensorboard` line magic.)start)r   r
   r
   r   r   s   s    r   c           	         s  t  }zddl ddl W n ty0   d Y n0 |tkrHdtd n jj jddd fdd}tj	| ddd}t
|}t|t
jrt|jjd	d
 nt|t
jrd}|j|jj|jjt|jd}|| t|jjd	dd
 nt|t
jr4dd }d|j|d|j|d|jf }|| nt|t
jr|jdurZd|jf nd}|jjtjkrzd|f }nd||jf }|t| n.t|t
j rd|j }|| nt!d| dS )ag  Launch and display a TensorBoard instance as if at the command line.

    Args:
      args_string: Command-line arguments to TensorBoard, to be
        interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
        Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
        point the logdir at the literal directory named "2>&1".
    r   NzLaunching TensorBoard...T)Z
display_idc                    s(   d u rt |  n j|  d S N)printupdatedisplayPretty)messager   handler
   r   print_or_update   s    
zstart.<locals>.print_or_update)commentsposixF)portprint_messagedisplay_handlezdReusing TensorBoard on port {port} (pid {pid}), started {delta} ago. (Use '!kill {pid}' to kill it.))r!   piddeltac                 S   s0   |dkrdS |d u rd|  S d| |  f S d S )N z
<could not read %s>z
Contents of %s:
%s)strip)namevaluer
   r
   r   format_stream   s
    zstart.<locals>.format_streamz9ERROR: Failed to launch TensorBoard (exited with %d).%s%sstderrstdoutz9%r (set by the `TENSORBOARD_BINARY` environment variable)z`tensorboard`zERROR: Could not find %s. Please ensure that your PATH contains an executable `tensorboard` program, or explicitly specify the path to a TensorBoard binary by setting the `TENSORBOARD_BINARY` environment variable.zERROR: Failed to start %s: %szUERROR: Timed out waiting for TensorBoard to start. It may still be running as pid %d.zXUnexpected result from `manager.start`: %r.
This is a TensorBoard bug; please report it.)"r   r   IPython.displayr   r   r   r   r   shlexsplitr   r   
isinstanceZStartLaunched_displayinfor!   ZStartReusedformatr$   _time_delta_from_infoZStartFailed	exit_coder+   r,   ZStartExecFailedZexplicit_binaryZos_errorerrnoENOENTtextwrapfillZStartTimedOut	TypeError)	args_stringcontextr   Zparsed_argsZstart_resulttemplater   r*   Zthe_tensorboard_binaryr
   r   r   r   x   s    	




	



r   c                 C   s"   t t | j }ttj|dS )zFormat the elapsed time for the given TensorBoardInfo.

    Args:
      info: A TensorBoardInfo value.

    Returns:
      A human-readable string describing the time since the server
      described by `info` started: e.g., "2 days, 0:48:58".
    )seconds)inttime
start_timestrdatetime	timedelta)r2   Zdelta_secondsr
   r
   r   r4      s    
r4   c                 C   s   t | |ddd dS )a  Display a TensorBoard instance already running on this machine.

    Args:
      port: The port on which the TensorBoard server is listening, as an
        `int`, or `None` to automatically select the most recently
        launched TensorBoard.
      height: The height of the frame into which to render the TensorBoard
        UI, as an `int` number of pixels, or `None` to use a default value
        (currently 800).
    TN)r!   heightr"   r#   )r1   )r!   rE   r
   r
   r   r      s    r   Fc                    s   |du rd} du rFt  }|s*tdqttt  dd d}|j n. fddt  D }|rpt|d	d dnd}|r|durd
jt |t||j|jd}t	| n t
tttttit  }| ||dS )aY  Internal version of `display`.

    Args:
      port: As with `display`.
      height: As with `display`.
      print_message: True to print which TensorBoard instance was selected
        for display (if applicable), or False otherwise.
      display_handle: If not None, an IPython display handle into which to
        render TensorBoard.
    Ni   z6Can't display TensorBoard: no known instances running.c                 S   s   | j S r   rA   xr
   r
   r   <lambda>      z_display.<locals>.<lambda>)keyc                    s   g | ]}|j  kr|qS r
   r!   ).0irL   r
   r   
<listcomp>  rJ   z_display.<locals>.<listcomp>c                 S   s   | j S r   rF   rG   r
   r
   r   rI     rJ   zWSelecting TensorBoard with {data_source} (started {delta} ago; port {port}, pid {pid}).)data_sourcer%   r!   r$   )r!   rE   r#   )r   get_all
ValueErrormaxr!   r3   data_source_from_infor4   r$   r   r   _display_colabr   _display_ipythonr   _display_clir   )r!   rE   r"   r#   infosr2   r   fnr
   rL   r   r1     s:    	
r1   c           	      C   sj   ddl }d}dd|  fdd| fg}|D ]\}}|||}q(|j|}|rZ|| n|j| dS )a]  Display a TensorBoard instance in a Colab output frame.

    The Colab VM is not directly exposed to the network, so the Colab
    runtime provides a service worker tunnel to proxy requests from the
    end user's browser through to servers running on the Colab VM: the
    output frame may issue requests to https://localhost:<port> (HTTPS
    only), which will be forwarded to the specified port on the VM.

    It does not suffice to create an `iframe` and let the service worker
    redirect its traffic (`<iframe src="https://localhost:6006">`),
    because for security reasons service workers cannot intercept iframe
    traffic. Instead, we manually fetch the TensorBoard index page with an
    XHR in the output frame, and inject the raw HTML into `document.body`.

    By default, the TensorBoard web app requests resources against
    relative paths, like `./data/logdir`. Within the output frame, these
    requests must instead hit `https://localhost:<port>/data/logdir`. To
    redirect them, we change the document base URI, which transparently
    affects all requests (XHRs and resources alike).
    r   Na  
        (async () => {
            const url = new URL(await google.colab.kernel.proxyPort(%PORT%, {'cache': true}));
            url.searchParams.set('tensorboardColab', 'true');
            const iframe = document.createElement('iframe');
            iframe.src = url;
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('height', '%HEIGHT%');
            iframe.setAttribute('frameborder', 0);
            document.body.appendChild(iframe);
        })();
    %PORT%%d%HEIGHT%)r-   replacer   Z
Javascriptr   )	r!   rE   r#   r   shellreplacementskvscriptr
   r
   r   rU   9  s    

rU   c                 C   s   dd l }dtd}d}tjd}|d urz|dd|  }dtj	|d	d
fdt
|fdd| fddt
|fg}n@dtj	|d	d
fdt
|fdd| fdd|  fdt
dfg}|D ]\}}	|||	}q|j|}
|r||
 n|j|
 d S )Nr   ztensorboard-frame-{:08x}@   a  
      <iframe id="%HTML_ID%" width="100%" height="%HEIGHT%" frameborder="0">
      </iframe>
      <script>
        (function() {
          const frame = document.getElementById(%JSON_ID%);
          const url = new URL(%URL%, window.location);
          const port = %PORT%;
          if (port) {
            url.port = port;
          }
          frame.src = url;
        })();
      </script>
    ZTENSORBOARD_PROXY_URLrZ   r[   z	%HTML_ID%T)quotez	%JSON_ID%r\   )rZ   0z%URL%/)r-   r3   randomgetrandbitsosenvirongetr]   htmlescapejsondumpsr   HTMLr   )r!   rE   r#   r   Zframe_idr^   	proxy_urlr_   r`   ra   Ziframer
   r
   r   rV   j  s0    
	

rV   c                 C   s   ~~d|  }t | d S )Nz2Please visit http://localhost:%d in a web browser.)r   )r!   rE   r#   r   r
   r
   r   rW     s    rW   c                  C   sV   t  } | std dS td | D ],}d}t|j|jt |t||jd q$dS )a  Print a listing of known running TensorBoard instances.

    TensorBoard instances that were killed uncleanly (e.g., with SIGKILL
    or SIGQUIT) may appear in this list even if they are no longer
    running. Conversely, this list may be missing some entries if your
    operating system's temporary directory has been cleared since a
    still-running TensorBoard instance started.
    z'No known TensorBoard instances running.NzKnown TensorBoard instances:z?  - port {port}: {data_source} (started {delta} ago; pid {pid}))r!   rP   r%   r$   )r   rQ   r   r3   r!   rT   r4   r$   )rX   r2   r=   r
   r
   r   list  s     	rr   )NN)NNFN)__doc__rC   r6   rl   rn   ri   rg   r.   r8   r@   r   r   r   r   r   r   r   r   r   r   r   r4   r   r1   rU   rV   rW   rr   r
   r
   r
   r   <module>   s4   'q

410