a
    d=icj]                     @   sx  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	m
Z ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	l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 ddlmZ ddlmZ ddlmZ ddl m!Z! dZ"dZ#dZ$dZ%dZ&e'dZ(e!) Z*d'ddZ+dd Z,G dd de-Z.dd  Z/d!d" Z0d#d$ Z1d%d& Z2dS )(zfTensorBoard WSGI Application Logic.

Provides TensorBoardWSGIApp for building a TensorBoard WSGI app.
    N)parse)wrappers)errors)plugin_utilauth)context)client_feature_flags)empty_path_redirectexperiment_id)experimental_plugin)	http_util)path_prefix)security_validator)base_plugin)core_plugin)
tb_loggingz/dataz/pluginz/plugins_listingz/plugin_entry.htmlZexperimentalPluginz^[A-Za-z0-9_-]+$c              
   C   s   |du rt }i }tj|| | j|||| j| jd}g }	g }
|D ]}t|}z||}W n2 ty   t	j
dt|jd|jdd d}Y n0 |du rq<|	| t|tjst|tjr|
|j |||j< q<t|	| j||
||S )a  Constructs a TensorBoard WSGI app from plugins and data providers.

    Args:
      flags: An argparse.Namespace containing TensorBoard CLI flags.
      plugins: A list of plugins, which can be provided as TBPlugin subclasses
          or TBLoader instances or subclasses.
      data_provider: Instance of `tensorboard.data.provider.DataProvider`. May
          be `None` if `flags.generic_data` is set to `"false"` in which case
          `deprecated_multiplexer` must be passed instead.
      assets_zip_provider: See TBContext documentation for more information. If
          `None` a placeholder assets zipfile will be used containing only a
          default `index.html` file, and the actual frontend assets must be
          supplied by middleware wrapping this WSGI app.
      deprecated_multiplexer: Optional `plugin_event_multiplexer.EventMultiplexer`
          to use for any plugins not yet enabled for the DataProvider API.
          Required if the data_provider argument is not passed.
      auth_providers: Optional mapping whose values are `AuthProvider` values
        and whose keys are used by (e.g.) data providers to specify
        `AuthProvider`s via the `AuthContext.get` interface. Defaults to `{}`.
      experimental_middlewares: Optional list of WSGI middlewares (i.e.,
        callables that take a WSGI application and return a WSGI application)
        to apply directly around the core TensorBoard app itself, "inside" the
        request redirection machinery for `--path_prefix`, experiment IDs, etc.
        You can use this to add handlers for additional routes. Middlewares are
        applied in listed order, so the first element of this list is the
        innermost application. Defaults to `[]`. This parameter is experimental
        and may be reworked or removed.

    Returns:
      A WSGI application that implements the TensorBoard backend.

    :type plugins: list[base_plugin.TBLoader]
    N)data_providerflagslogdirZmultiplexerassets_zip_providerplugin_name_to_instanceZsampling_hintswindow_titlez&Failed to load plugin %s; ignoring it.__qualname__Texc_info) _placeholder_assets_zip_providerr   Z	TBContextr   Zsamples_per_pluginr   make_plugin_loaderload	Exceptionloggererrorgetattrappend
isinstancer   ZExperimentalPluginplugin_nameTensorBoardWSGIr   )r   pluginsr   r   Zdeprecated_multiplexerauth_providersexperimental_middlewaresr   r   Z	tbpluginsexperimental_pluginsplugin_specloaderplugin r/   p/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/tensorboard/backend/application.pyTensorBoardWSGIApp@   sX    *



r1   c                 C   sT   t | tjr| S t | trBt| tjr,|  S t| tjrBt| S td| f dS )aR  Returns a plugin loader for the given plugin.

    Args:
      plugin_spec: A TBPlugin subclass, or a TBLoader instance or subclass.

    Returns:
      A TBLoader for the given plugin.

    :type plugin_spec:
      Type[base_plugin.TBPlugin] | Type[base_plugin.TBLoader] |
      base_plugin.TBLoader
    :rtype: base_plugin.TBLoader
    z'Not a TBLoader or TBPlugin subclass: %rN)r%   r   ZTBLoadertype
issubclassZTBPluginZBasicLoader	TypeError)r,   r/   r/   r0   r      s    

r   c                   @   sR   e Zd ZdZdddZdd Zejjdd	 Z	ejjd
d Z
dd Zdd ZdS )r'   z=The TensorBoard WSGI app that delegates to a set of TBPlugin. Nc                 C   s0  || _ || _|| _t|pd| _|p&i | _t|p2g | _| jdrRt	d| j t
t | jt
t | ji| _i }t }| j D ]}	|	jdu rt	d|	 t|	jst	d|	|	jf |	j|v rt	d|	j ||	j z|	 }
W nX ty> } z>t|	tju r
 td|	jt| W Y d}~q|W Y d}~n
d}~0 0 |
 D ]\}}|dsnt	d	|	j|f t|	tju r|}nt
t d |	j | }|d
r|dd }d|v rt	d|	j|f |||< n&d|v rt	d|	j|f || j|< qHq|t !t"| dd dd| _#| $ | _%dS )al  Constructs TensorBoardWSGI instance.

        Args:
          plugins: A list of base_plugin.TBPlugin subclass instances.
          path_prefix: A prefix of the path when app isn't served from root.
          data_provider: `tensorboard.data.provider.DataProvider` or
            `None`; if present, will inform the "active" state of
            `/plugins_listing`.
          experimental_plugins: A list of plugin names that are only provided
              experimentally. The corresponding plugins will only be activated for
              a user if the user has specified the plugin with the experimentalPlugin
              query parameter in the URL.
          auth_providers: Optional mapping whose values are `AuthProvider`
            values and whose keys are used by (e.g.) data providers to specify
            `AuthProvider`s via the `AuthContext.get` interface.
            Defaults to `{}`.
          experimental_middlewares: Optional list of WSGI middlewares to apply
            directly around the core TensorBoard app itself. Defaults to `[]`.
            This parameter is experimental and may be reworked or removed.

        Returns:
          A WSGI application for the set of all TBPlugin instances.

        Raises:
          ValueError: If some plugin has no plugin_name
          ValueError: If some plugin has an invalid plugin_name (plugin
              names must only contain [A-Za-z0-9_.-])
          ValueError: If two plugins have the same plugin_name
          ValueError: If some plugin handles a route that does not start
              with a slash

        :type plugins: list[base_plugin.TBPlugin]
        r/   /z!Trailing slash in path prefix: %rNzPlugin %s has no plugin_namezPlugin %s has invalid name %rzDuplicate plugins for name %szPlugin %s failed. Exception: %szKPlugin named %r handles invalid route %r: route does not start with a slashz/**z]Plugin %r handles invalid route '%s*': Only trailing wildcards are supported (i.e., `/.../*`)zZPlugin %r handles invalid route %r: Only trailing wildcards are supported (i.e., `/.../*`)c                 S   s   t | d S )Nr   )len)xr/   r/   r0   <lambda>=      z*TensorBoardWSGI.__init__.<locals>.<lambda>T)keyreverse)&_plugins_path_prefix_data_provider	frozenset_experimental_plugins_auth_providerslist_extra_middlewaresendswith
ValueErrorDATA_PREFIXPLUGINS_LISTING_ROUTE_serve_plugins_listingPLUGIN_ENTRY_ROUTE_serve_plugin_entryexact_routessetr&   _VALID_PLUGIN_REmatchaddZget_plugin_appsr    r2   r   
CorePluginr!   warningstritems
startswithPLUGIN_PREFIXcollectionsOrderedDictsortedprefix_routes_create_wsgi_app_app)selfr(   r   r   r+   r)   r*   Zunordered_prefix_routesZplugin_names_encounteredr.   Zplugin_appseZrouteapppathr/   r/   r0   __init__   s    *




"


zTensorBoardWSGI.__init__c                 C   sh   | j }| jD ]}||}qt|| j}t|}t|}t	|}t
|| j}t|}t|}|S )z.Apply middleware to create the final WSGI app.)_route_requestrF   _auth_context_middlewarerD   r	   ZClientFeatureFlagsMiddlewarer
   ZEmptyPathRedirectMiddlewarer   ZExperimentIdMiddlewarer   ZPathPrefixMiddlewarer@   r   ZSecurityValidatorMiddleware_handling_errors)r_   ra   Z
middlewarer/   r/   r0   r]   D  s    





z TensorBoardWSGI._create_wsgi_appc                    s   |j d  fdd| jD }|s.t t|dkrPdj |d}t||d }| j	}|sxt
j|dd	d
dS t|jrtdtd| }d|}t|d }t|d}	tdj |d}
t
j||
d|	gdS )zServes a HTML for iframed plugin entry point.

        Args:
          request: The werkzeug.Request object.

        Returns:
          A werkzeug.Response object.
        namec                    s   g | ]}|j  kr|qS r/   )r&   ).0r.   rg   r/   r0   
<listcomp>]  s   z7TensorBoardWSGI._serve_plugin_entry.<locals>.<listcomp>   zGPlugin invariant error: multiple plugins with name {name} found: {list})rg   rE   r   zPlugin is not module loadable
text/plaini  codez/Expected es_module_path to be non-absolute path.z(import({}).then((m) => void m.render());zutf-8asciiz
            <!DOCTYPE html>
            <head><base href="plugin/{name}/" /></head>
            <body><script type="module">{script_content}</script></body>
            )rg   script_contentz	text/html)Zcsp_scripts_sha256s)argsgetr?   r   ZNotFoundErrorr9   formatAssertionErrorfrontend_metadataes_module_pathr   RespondurlparsenetlocrH   jsondumpshashlibsha256encodedigestbase64	b64encodedecodetextwrapdedent)r_   requestr(   reasonr.   module_pathZmodule_jsonrq   r   Z
script_shahtmlr/   ri   r0   rM   R  sJ    



z#TensorBoardWSGI._serve_plugin_entryc              
   C   s,  t  }t|j}t|j}t| jdurB| jj||dpFt nt }| j	t|j
t }| jD ]}|j|v rxqft|tju rqftt| |@ }|sz0t }	| }t |	 }
td|j|
 W n( ty   d}tjd|jdd Y n0 | }|j||jd}|jdur*|j|d	< n
|j|d	< |j}|j}|j }|r|durdt!d
|j |dur|t!d|j ddi}n|dur|durtd|j qfn^|dur|du rd|d}n>|du r|durdd"|j#t$t%d|j|gd}nddi}||d< |||j< qft&'||dS )zServes an object mapping plugin name to whether it is enabled.

        Args:
          request: The werkzeug.Request object.

        Returns:
          A werkzeug.Response object.
        Nr   z5Plugin listing: is_active() for %s took %0.3f secondsFz<Plugin listing: is_active() for %s failed (marking inactive)Tr   )disable_reloadenabled
remove_domtab_namez6Plugin %r declared as both Angular built-in and legacyz7Plugin %r declared as both Angular built-in and iframedr2   ZNG_COMPONENTz7Plugin %r declared as both legacy and iframed; skippingZCUSTOM_ELEMENT)r2   element_nameZIFRAMEr5   r6   )r2   r   NONEloading_mechanismzapplication/json)(rY   rZ   r   r   environr   rB   rA   Zlist_pluginsrC   rr   getlist EXPERIMENTAL_PLUGINS_QUERY_PARAMr?   r&   r2   r   rS   boolZdata_plugin_namestime	is_activer!   infor    r"   rv   r   r   r   rw   r   is_ng_componentrH   joinZscript_rootrI   rX   r   rx   )r_   r   responsectxZeidZplugins_with_dataZplugins_to_skipr.   r   startelapsedZplugin_metadataZoutput_metadataZes_module_handlerr   r   r   r/   r/   r0   rK     s    





z&TensorBoardWSGI._serve_plugins_listingc                 C   s   |  ||S )a%  Central entry point for the TensorBoard application.

        This __call__ method conforms to the WSGI spec, so that instances of this
        class are WSGI applications.

        Args:
          environ: See WSGI spec (PEP 3333).
          start_response: See WSGI spec (PEP 3333).
        )r^   )r_   r   start_responser/   r/   r0   __call__  s    
zTensorBoardWSGI.__call__c                 C   s   t |}t|j}t|j}|| jv r:| j| ||S | jD ]"}||r@| j| ||  S q@t	d| t
j|dddd||S dS )a  Delegate an incoming request to sub-applications.

        This method supports strict string matching and wildcard routes of a
        single path component, such as `/foo/*`. Other routing patterns,
        like regular expressions, are not supported.

        This is the main TensorBoard entry point before middleware is
        applied. (See `_create_wsgi_app`.)

        Args:
          environ: See WSGI spec (PEP 3333).
          start_response: See WSGI spec (PEP 3333).
        zpath %s not found, sending 404z	Not foundrl   i  rm   N)r   Requestry   rb   _clean_pathrN   r\   rW   r!   rT   r   rx   )r_   r   r   r   
parsed_urlZ
clean_pathr   r/   r/   r0   rd     s     





zTensorBoardWSGI._route_request)r5   NNNN)__name__
__module__r   __doc__rc   r]   r   r   ZapplicationrM   rK   r   rd   r/   r/   r/   r0   r'      s        
 
:
wr'   c                    s    fdd}|S )Nc              
      sh   z | |W S  t jyb } z<t| }tj|t|d|j|jd}|| |W  Y d }~S d }~0 0 d S )Nrl   )rn   headers)	r   ZPublicErrorr   r   r   rx   rU   Z	http_coder   )r   r   r`   r   Z	error_appwsgi_appr/   r0   wrapper6  s    
z!_handling_errors.<locals>.wrapperr/   )r   r   r/   r   r0   rf   5  s    rf   c                    s    fdd}|S )Nc                    s<   t | } t | }t| j|d}t| | | |S )Nr   )dictr   ZAuthContextr   Zfrom_environreplaceZset_in_environ)r   r   Zauth_ctxr   r)   r   r/   r0   r   J  s
    z)_auth_context_middleware.<locals>.wrapperr/   )r   r)   r   r/   r   r0   re   I  s    re   c                 C   s"   | dkr|  dr| dd S | S )zRemoves a trailing slash from a non-root path.

    Arguments:
      path: The path of a request.

    Returns:
      The route to use to serve the request.
    r6   Nr7   )rG   )rb   r/   r/   r0   r   T  s    	r   c                  C   sF   t  } tj| dd}|dd W d   n1 s80    Y  | S )zDDefines a default assets zip provider containing a dummy index.html.w)modez
index.htmlz"TensorBoard placeholder index.htmlN)ioBytesIOzipfileZipFilewritestr)Zmemfilezfr/   r/   r0   r   b  s    *r   )NNNNN)3r   r   rY   r}   r   r{   rer   r   urllibr   ry   r   Zwerkzeugr   Ztensorboardr   r   r   r   Ztensorboard.backendr	   r
   r   r   r   r   r   Ztensorboard.pluginsr   Ztensorboard.plugins.corer   Ztensorboard.utilr   rI   rX   rJ   rL   r   compilerP   Z
get_loggerr!   r1   r   objectr'   rf   re   r   r   r/   r/   r/   r0   <module>   s^   
     
V   
