
    1Vh-                         d 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ZdZdZ G d dej.                        Zy)zThe TensorBoard Custom Scalars plugin.

This plugin lets the user create scalars plots with custom run-tag combinations
by specifying regular expressions.

See `http_api.md` in this directory for specifications of the routes for
this plugin.
    N)wrappers)plugin_util)	http_util)tf)provider)base_plugin)
layout_pb2)metadata)scalars_pluginregex_validtag_to_events<   c                       e Zd ZdZej
                  Zd Zd Zd Z	d Z
d Zej                  j                  d        Zd Zej                  j                  d	        Zd
 Zej                  j                  d        Zd Zy)CustomScalarsPluginz%CustomScalars Plugin for TensorBoard.c                 j    |j                   | _        |j                  | _        |j                  | _        y)z}Instantiates ScalarsPlugin via TensorBoard core.

        Args:
          context: A base_plugin.TBContext instance.
        N)logdir_logdirdata_provider_data_providerplugin_name_to_instance_plugin_name_to_instance)selfcontexts     g/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/plugins/custom_scalar/custom_scalars_plugin.py__init__zCustomScalarsPlugin.__init__8   s+     ~~%33(/(G(G%    c                 v    t         j                  | j                  v r| j                  t         j                     S y)z~Tries to get the scalars plugin.

        Returns:
          The scalars plugin. Or None if it is not yet registered.
        N)scalars_metadataPLUGIN_NAMEr   r   s    r   _get_scalars_pluginz'CustomScalarsPlugin._get_scalars_pluginB   s3     ''4+H+HH001A1M1MNNr   c                 J    | j                   | j                  | j                  dS )N)z/download_dataz/layoutz/scalars)download_data_routelayout_routescalars_router    s    r   get_plugin_appsz#CustomScalarsPlugin.get_plugin_appsN   s'    "66((**
 	
r   c                      y)z?Plugin is active if there is a custom layout for the dashboard.F r    s    r   	is_activezCustomScalarsPlugin.is_activeU   s    r   c                 0    t        j                  dd      S )Nztf-custom-scalar-dashboardzCustom Scalars)element_nametab_name)r   FrontendMetadatar    s    r   frontend_metadataz%CustomScalarsPlugin.frontend_metadataY   s    ++5%
 	
r   c                    t        j                  |j                        }|j                  j	                  d      }|j                  j	                  d      }t        j
                  |j                        }|j                  j	                  d      }	 | j                  |||||      \  }}t        j                  |||      S # t        $ r,}	t        j                  |t        |	      dd      cY d }	~	S d }	~	ww xY w)Nruntagformat
text/plain  requestcontentcontent_typecode)r   r   environargsgetexperiment_iddownload_data_impl
ValueErrorr   Respondstr)
r   r6   ctxr0   r1   
experimentresponse_formatbody	mime_typees
             r   r#   z'CustomScalarsPlugin.download_data_route_   s    !!'//2llu%llu% ..w?
!,,**84
	"55S#z?OD)   $	::  	$$A)	 	s   C   	C5	!C0*C50C5c                 t    | j                         }|st        d      |j                  |||||      \  }}||fS )a\  Provides a response for downloading scalars data for a data series.

        Args:
          ctx: A tensorboard.context.RequestContext value.
          run: The run.
          tag: The specific tag.
          experiment: An experiment ID, as a possibly-empty `str`.
          response_format: A string. One of the values of the OutputFormat enum
            of the scalar plugin.

        Raises:
          ValueError: If the scalars plugin is not registered.

        Returns:
          2 entities:
            - A JSON object response body.
            - A mime type (string) for the response.
        z\Failed to respond to request for /download_data. The scalars plugin is oddly not registered.)r!   r?   scalars_impl)	r   rB   r0   r1   rC   rD   scalars_plugin_instancerE   rF   s	            r   r>   z&CustomScalarsPlugin.download_data_impls   sV    & #'":":"<&B  2>>c:
i Yr   c                    t        j                  |j                        }|j                  j	                  d      }|j                  j	                  d      }t        j
                  |j                        }d}	 | j                  ||||      }t        j                  |||      S # t        $ r,}t        j                  |t        |      dd      cY d}~S d}~ww xY w)a  Given a tag regex and single run, return ScalarEvents.

        This route takes 2 GET params:
        run: A run string to find tags for.
        tag: A string that is a regex used to find matching tags.
        The response is a JSON object:
        {
          // Whether the regular expression is valid. Also false if empty.
          regexValid: boolean,

          // An object mapping tag name to a list of ScalarEvents.
          payload: Object<string, ScalarEvent[]>,
        }
        r1   r0   application/jsonr3   r4   r5   N)r   r   r:   r;   r<   r=   rI   r?   r   r@   rA   )	r   r6   rB   tag_regex_stringr0   rC   rF   rE   rG   s	            r   r%   z!CustomScalarsPlugin.scalars_route   s      !!'//2"<<++E2llu% ..w?
&		$$S#/?LD   $	::  	$$A)	 	s   8B# #	C,!CCCc                 t   |st         dt        i iS 	 t        j                  |      }| j
                  j                  ||t        j                  t        j                  |g            }d}	 ||   }|r|| j                         }	|	st        d      t        j                  j                   }
|j#                         D ci c],  }|j%                  |      r||	j'                  |||||
      d   . }}t         dt        iS # t        j                  $ r t         dt        i icY S w xY w# t        $ r i }Y w xY wc c}w )a  Given a tag regex and single run, return ScalarEvents.

        Args:
          ctx: A tensorboard.context.RequestContext value.
          run: A run string.
          tag_regex_string: A regular expression that captures portions of tags.

        Raises:
          ValueError: if the scalars plugin is not registered.

        Returns:
          A dictionary that is the JSON-able response.
        F)runs)r=   plugin_namerun_tag_filterNzVFailed to respond to request for /scalars. The scalars plugin is oddly not registered.r   T)_REGEX_VALID_PROPERTY_TAG_TO_EVENTS_PROPERTYrecompileerrorr   list_scalarsr   r   r   RunTagFilterKeyErrorr!   r?   r   OutputFormatJSONkeysmatchrI   )r   rB   r0   rM   rC   regexrun_to_datatag_to_datapayloadrJ   formr1   s               r   rI   z CustomScalarsPlugin.scalars_impl   sw      &u' 	JJ/0E ))66$(44#00se<	 7 
 	%c*K &*&>&>&@#* F  "..33D
 '++-	 ;;s#	 ,99c:t G  "4#W
 	
S xx 	%u' 	"  	 G	 s)   C= ,D$ <1D5=!D! D!$D21D2c                     t        j                  |j                        }t        j                  |j                        }| j	                  ||      }t        j                  ||d      S )a@  Fetches the custom layout specified by the config file in the logdir.

        If more than 1 run contains a layout, this method merges the layouts by
        merging charts within individual categories. If 2 categories with the same
        name are found, the charts within are merged. The merging is based on the
        order of the runs to which the layouts are written.

        The response is a JSON object mirroring properties of the Layout proto if a
        layout for any run is found.

        The response is an empty object if no layout could be found.
        rL   )r   r   r:   r=   layout_implr   r@   )r   r6   rB   rC   rE   s        r   r$   z CustomScalarsPlugin.layout_route   sT     !!'//2 ..w?
Z0  $0BCCr   c           
         i }d }| j                   j                  ||t        j                  t	        j
                  t        j                  g      d      }t        |      D ]Q  }||   t        j                     }|d   j                  j                         }t        j                         }	|	j                  t        j                  j                  |             |r|	j                   D ]  }
|
j"                  |v r\||
j"                     j$                  j'                  |
j$                  D cg c]  }|||
j"                     j$                  vr|! c}       m|j                   j)                         j+                  |
       |
||
j"                  <    0|	}|	j                   D ]  }
|
||
j"                  <    T |rt-        j.                  |      S i S c c}w )N)tags   )r=   rP   rQ   
downsampler   )r   read_tensorsr
   r   r   rX   CONFIG_SUMMARY_TAGsortednumpyitemr	   LayoutParseFromStringr   compatas_bytescategorytitlechartextendadd	MergeFromr   proto_to_json)r   rB   rC   title_to_categorymerged_layoutdatar0   pointsr7   layout_protorr   cs               r   rd   zCustomScalarsPlugin.layout_impl  s    ""//$ ,,#00112  0 
 $< 	AC#Yx::;FQioo**,G%,,.L((););G)DE , 5 5 EH~~):: *(..9??FF *2$%#$'8'H'N'N$O !" &..224>>xH<D)(..9E$ !- , 5 5 AH8@%hnn5A7	A< ,,];; I+s   )$GN)__name__
__module____qualname____doc__r
   r   rP   r   r!   r&   r)   r.   r   Requestapplicationr#   r>   r%   rI   r$   rd   r(   r   r   r   r   3   s    /&&KH


 !!; ";&B !! ; " ;DD
L !!D "D$1r   r   )r   rT   werkzeugr   tensorboardr   tensorboard.backendr   tensorboard.compatr   tensorboard.datar   tensorboard.pluginsr   !tensorboard.plugins.custom_scalarr	   r
   tensorboard.plugins.scalarr   r   rR   rS   _CONFIG_FILE_CHECK_THROTTLETBPluginr   r(   r   r   <module>r      sY    
  # ) ! % + 8 6 C 5 &  *  ! N+.. Nr   