
    1Vh]W                     h   d Z ddlZddl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ddddZdZ eej4                  ej4                  g      Z eej4                  g      Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$ G d dejJ                        Z&y)zThe TensorBoard metrics plugin.    N)wrappers)errors)plugin_util)	http_util)provider)base_plugin)metadataz	image/bmpz	image/gifz
image/jpegz	image/pngzimage/svg+xml)bmpgifjpegpngsvgzapplication/octet-streamc                 N   t        j                  t              }t        j                  t              }| j                         D ]]  \  }}|j                         D ]E  \  }}|j                  }t        |      s||   j                  |       ||   j                  |       G _ ||fS )a  Gets maps from tags to descriptions, and descriptions to runs.

    Args:
        mapping: a nested map `d` such that `d[run][tag]` is a time series
          produced by DataProvider's `list_*` methods.

    Returns:
        A tuple containing
            tag_to_descriptions: A map from tag strings to a set of description
                strings.
            description_to_runs: A map from description strings to a set of run
                strings.
    )collectionsdefaultdictsetitemsdescriptionlenadd)mappingtag_to_descriptionsdescription_to_runsruntag_to_contenttag	metadatumr   s           Z/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/plugins/metrics/metrics_plugin.py_get_tag_description_infor   4   s     &11#6%11#6&}} :^,224 	:NC#//K;#C(,,[9#K044S9		::  333    c                     g }| D ]U  }t        ||         }t        |      dkD  rdnd}d|z   dz   dj                  |      z   }|dz   |z   }|j                  |       W d}|dj                  |      z   S )	a  Creates a single description from a set of descriptions.

    Descriptions may be composites when a single tag has different descriptions
    across multiple runs.

    Args:
        descriptions: A list of description strings.
        description_to_runs: A map from description strings to a set of run
            strings.

    Returns:
        The combined description string.
       runsr   z## For z: z, 
z# Multiple descriptions
)sortedr   joinappend)	descriptionsr   prefixed_descriptionsr   r#   run_or_runs
run_headerdescription_htmlheaders	            r   _build_combined_descriptionr.   N   s     # 7)+67 #D	Af5,t3diioE
%,{:$$%567 )FDII3444r    c                     t        |       \  }}i }|D ]H  }t        ||         }t        |      dk(  r|d   }nt        ||      }t	        j
                  |      ||<   J |S )a  Returns a map of tags to descriptions.

    Args:
        mapping: a nested map `d` such that `d[run][tag]` is a time series
          produced by DataProvider's `list_*` methods.

    Returns:
        A map from tag strings to description HTML strings. E.g.
        {
            "loss": "<h1>Multiple descriptions</h1><h2>For runs: test, train
            </h2><p>...</p>",
            "loss2": "<p>The lossy details</p>",
        }
    r"   r   )r   r%   r   r.   r   markdown_to_safe_html)r   r   r   resultr   r(   r   s          r   _get_tag_to_descriptionr2   h   s     0I0,, F" E1#67|!&q/K51K "77DsE Mr    c                 F    | D ci c]  }|t        | |          c}S c c}w )aM  Returns a map of run names to a list of tag names.

    Args:
        mapping: a nested map `d` such that `d[run][tag]` is a time series
          produced by DataProvider's `list_*` methods.

    Returns:
        A map from run strings to a list of tag strings. E.g.
            {"loss001a": ["actor/loss", "critic/loss"], ...}
    )r%   )r   r   s     r   _get_run_tag_infor4      s&     299#C%%999s   c                 0    t        |       t        |       dS )a  Prepares a scalar or histogram mapping for client consumption.

    Args:
        mapping: a nested map `d` such that `d[run][tag]` is a time series
          produced by DataProvider's `list_*` methods.

    Returns:
        A dict with the following fields:
            runTagInfo: the return type of `_get_run_tag_info`
            tagDescriptions: the return type of `_get_tag_to_description`
    )
runTagInfotagDescriptions)r4   r2   r   s    r   _format_basic_mappingr9      s     (027; r    c                     |dz   }g }| D ][  }t        |j                        |k  r|j                  |j                  |j                  |j                  |   j
                  d       ] |S )a  Formats image metadata from a list of BlobSequenceDatum's for clients.

    This expects that frontend clients need to access images based on the
    run+tag+sample.

    Args:
        sorted_datum_list: a list of DataProvider's `BlobSequenceDatum`, sorted by
            step. This can be produced via DataProvider's `read_blob_sequences`.
        sample: zero-indexed integer for the requested sample.

    Returns:
        A list of `ImageStepDatum` (see http_api.md).
       )stepwallTimeimageId)r   valuesr'   r<   	wall_timeblob_key)sorted_datum_listsampleindex	step_datadatums        r   !_format_image_blob_sequence_datumrG      sp      QJEI" 

u||%

!OO <<.77	
	

 r    c                     t        j                  t              }| j                         D ]4  \  }}|j                         D ]  \  }}d|j                  dz
  i||   |<    6 t        |      S )a
  Returns a map of tag names to run information.

    Args:
        mapping: the result of DataProvider's `list_blob_sequences`.

    Returns:
        A nested map from run strings to tag string to image info, where image
        info is an object of form {"maxSamplesPerStep": num}. For example,
        {
            "reshaped": {
                "test": {"maxSamplesPerStep": 1},
                "train": {"maxSamplesPerStep": 1}
            },
            "convolved": {"test": {"maxSamplesPerStep": 50}},
        }
    maxSamplesPerStepr;   )r   r   dictr   
max_length)r   tag_run_image_infor   r   r   r   s         r   _get_tag_run_image_inforM      s{    " %006&}} ^,224 	NC#Y%9%9A%=,s#C(	
 "##r    c                 0    t        |       t        |       dS )aV  Prepares an image mapping for client consumption.

    Args:
        mapping: the result of DataProvider's `list_blob_sequences`.

    Returns:
        A dict with the following fields:
            tagRunSampledInfo: the return type of `_get_tag_run_image_info`
            tagDescriptions: the return type of `_get_tag_description_info`
    )r7   tagRunSampledInfo)r2   rM   r8   s    r   _format_image_mappingrP      s     37;4W= r    c                   2   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d	Zd
 Zej                  j                  d        Zd Zd Zd Zd Zd Zd Zd Zd Zej                  j                  d        Zd Zy)MetricsPluginzMetrics Plugin for TensorBoard.c                    |j                   | _        |j                  xs i }|j                  t        j
                  d      |j                  t        j
                  d      |j                  t        j
                  d      d| _        t        j                  dd      | _        t        j                  dd      | _        t        j                  d	d      | _        y
)zInstantiates MetricsPlugin.

        Args:
            context: A base_plugin.TBContext instance. MetricsLoader checks that
                it contains a valid `data_provider`.
        i  3   
   )scalars
histogramsimageszscalar time seriesr   )	data_kindlatest_known_versionzhistogram time serieszimage time seriesN)data_provider_data_providersampling_hintsgetscalar_metadataPLUGIN_NAMEhistogram_metadataimage_metadata_plugin_downsamplingr   _MetadataVersionChecker_scalar_version_checker_histogram_version_checker_image_version_checker)selfcontextr]   s      r   __init__zMetricsPlugin.__init__   s     &33
 !//52%))/*E*EtL(,,".. %(()C)CRH%
! (3'J'J*!"(
$ +6*M*M-!"+
' '2&I&I)!"'
#r    c                 0    t        j                  dd      S )NTzTime Series)is_ng_componenttab_name)r   FrontendMetadatarh   s    r   frontend_metadatazMetricsPlugin.frontend_metadata  s    ++ =
 	
r    c                 J    | j                   | j                  | j                  dS )N)z/tagsz/timeSeriesz
/imageData)_serve_tags_serve_time_series_serve_image_dataro   s    r   get_plugin_appszMetricsPlugin.get_plugin_apps  s'    %%2200
 	
r    c                 `    t         j                  t        j                  t        j                  fS N)r_   r`   ra   rb   ro   s    r   data_plugin_nameszMetricsPlugin.data_plugin_names&  s'    ''**&&
 	
r    c                      y)NF ro   s    r   	is_activezMetricsPlugin.is_active-  s    r    c                     t        j                  |j                        }t        j                  |j                        }| j	                  ||      }t        j                  ||d      S )N)
experimentapplication/json)r   ri   environexperiment_id
_tags_implr   Respond)rh   requestctxr}   rD   s        r   rr   zMetricsPlugin._serve_tags0  sR    !!'//2 ..w?

;  %1CDDr    Nc                 x   | j                   j                  ||t        j                        }| j	                  |t        j
                  | j                        }| j                   j                  ||t        j                        }|i }| j	                  |t        j
                  | j                        }| j                   j                  ||t        j                        }|i }| j	                  |t        j
                  | j                        }i }t        |      |d<   t        |      |d<   t        |      |d<   |S )a  Returns tag metadata for a given experiment's logged metrics.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: optional string ID of the request's experiment.

        Returns:
            A nested dict 'd' with keys in ("scalars", "histograms", "images")
                and values being the return type of _format_*mapping.
        )r   plugin_namerV   rW   rX   )r\   list_scalarsr_   r`   _filter_by_versionparse_plugin_metadatare   list_tensorsra   rf   list_blob_sequencesrb   rg   r9   rP   )rh   r   r}   scalar_mappinghistogram_mappingimage_mappingr1   s          r   r   zMetricsPlugin._tags_impl7  sO    ,,99$'33 : 

 0011((
 !//<<$*66 = 

 $ " 3344++
 ++??$&22 @ 

  M//00''
 1.Ay45FG|0?xr    c                     |D ci c]  }|i  }}|j                         D ]U  \  }}|j                         D ]=  \  }} ||j                        }	|j                  |	j                  ||      s6|||   |<   ? W |S c c}w )z@Filter `DataProvider.list_*` output by summary metadata version.)r   plugin_contentokversion)
rh   r   parse_metadataversion_checkerr   r1   r   r   r   mds
             r   r   z MetricsPlugin._filter_by_versionm  s    %,-c#r'--#*==? 	-C"0"6"6"8 -Y#I$<$<=&))"**c3?#,sC 	-	-  .s   
A;c                    t        j                  |j                        }t        j                  |j                        }|j                  dk(  r|j
                  j                  d      }n|j                  j                  d      }|st        j                  d      	 t        j                  |      }| j                  |||      }t        j                  ||d      S # t        $ r t        j                  d      w xY w)NPOSTrequestszMissing 'requests' fieldz"Unable to parse 'requests' as JSONr~   )r   ri   r   r   methodformr^   argsr   InvalidArgumentErrorjsonloads
ValueError_time_series_implr   r   )rh   r   r   r}   series_requests_stringseries_requestsresponses          r   rs   z MetricsPlugin._serve_time_seriesx  s    !!'//2 ..w?
>>V#%,\\%5%5j%A"%,\\%5%5j%A"%--.HII	"jj)?@O ))#z?K  (4FGG  	--4 	s   C C;c                 P    |D cg c]  }| j                  |||       }}|S c c}w )a~  Constructs a list of responses from a list of series requests.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: string ID of the request's experiment.
            series_requests: a list of `TimeSeriesRequest` dicts (see http_api.md).

        Returns:
            A list of `TimeSeriesResponse` dicts (see http_api.md).
        )_get_time_series)rh   r   r}   r   r   	responsess         r   r   zMetricsPlugin._time_series_impl  s=     +
 !!#z7;
	 
 	
s   #c                     |j                  d      }|j                  d      }|j                  d      }|j                  d      }||d}t        |t              r||d<   t        |t              r||d<   |S )Nr   r   pluginrC   )r   r   )r^   
isinstancestrint)rh   series_requestr   r   r   rC   r   s          r   _create_base_responsez#MetricsPlugin._create_base_response  sx      '  '##H-##H-$S1c3!HUOfc"!'HXr    c                    |j                  d      }|j                  d      }|j                  d      }|j                  d      }t        |t              sy|t        j                  k7  r'|t
        j                  k7  r|t        j                  k7  ry|t        v rt        |t              sy|t        v rt        |t              syy )	Nr   r   r   rC   zMissing tagzInvalid pluginzMissing runzMissing sample)
r^   r   r   r_   r`   ra   rb   _SINGLE_RUN_PLUGINS_SAMPLED_PLUGINSr   )rh   r   r   r   r   rC   s         r   _get_invalid_request_errorz(MetricsPlugin._get_invalid_request_error  s      '##H-  '##H-#s#  o111,888.444#((C1E %%j.E#r    c                    |j                  d      }|j                  d      }|j                  d      }|j                  d      }| j                  |      }| j                  |      }	|	r|	|d<   |S |r|gnd}
d}|t        j                  k(  r| j                  ||||
      }|t        j                  k(  r| j                  ||||
      }|t        j                  k(  r| j                  |||||
      }||d<   |S )aY  Returns time series data for a given tag, plugin.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: string ID of the request's experiment.
            series_request: a `TimeSeriesRequest` (see http_api.md).

        Returns:
            A `TimeSeriesResponse` dict (see http_api.md).
        r   r   r   rC   errorNrunToSeries)
r^   r   r   r_   r`   _get_run_to_scalar_seriesra   _get_run_to_histogram_seriesrb   _get_run_to_image_series)rh   r   r}   r   r   r   r   rC   r   request_errorr#   run_to_seriess               r   r   zMetricsPlugin._get_time_series  s      '  '##H-##H---n=77G -HWOu_000 ::ZdM '333 ==ZdM ^/// 99ZfdM #0r    c           
      b   | j                   j                  ||t        j                  | j                  d   t        j                  ||g            }i }|j                         D ]C  \  }}||vr||   D 	cg c]&  }	|	j                  |	j                  |	j                  d( }
}	|
||<   E |S c c}	w )a  Builds a run-to-scalar-series dict for client consumption.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: a string experiment id.
            tag: string of the requested tag.
            runs: optional list of run names as strings.

        Returns:
            A map from string run names to `ScalarStepDatum` (see http_api.md).
        rV   r#   tagsr   r   
downsamplerun_tag_filter)r=   r<   value)r\   read_scalarsr_   r`   rc   r   RunTagFilterr   r@   r<   r   rh   r   r}   r   r#   r   r   
result_runtag_datarF   r?   s              r   r   z'MetricsPlugin._get_run_to_scalar_series  s     %%22$'3300;#00d#G 3 
 $+MMO 	/ J(" &c] 	 !&!JJ"[[F  )/M*%	/ s   6+B,c                 |    |j                   j                         }|D cg c]  }|d   |d   |d   d }}|S c c}w )zFormats a histogram datum's bins for client consumption.

        Args:
            datum: a DataProvider's TensorDatum.

        Returns:
            A list of `HistogramBin`s (see http_api.md).
        r   r"   r;   )minmaxcount)numpytolist)rh   rF   
numpy_listxbinss        r   _format_histogram_datum_binsz*MetricsPlugin._format_histogram_datum_bins  sG     [['')
CMNa!QqTAaD9NN Os   9c           
      l   | j                   j                  ||t        j                  | j                  d   t        j                  ||g            }i }|j                         D ]H  \  }}||vr||   D 	cg c]+  }	|	j                  |	j                  | j                  |	      d- }
}	|
||<   J |S c c}	w )a  Builds a run-to-histogram-series dict for client consumption.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: a string experiment id.
            tag: string of the requested tag.
            runs: optional list of run names as strings.

        Returns:
            A map from string run names to `HistogramStepDatum` (see http_api.md).
        rW   r   r   )r=   r<   r   )r\   read_tensorsra   r`   rc   r   r   r   r@   r<   r   r   s              r   r   z*MetricsPlugin._get_run_to_histogram_series  s     %%22$*6600>#00d#G 3 
 $+MMO 	/ J(" &c] 	 !&!JJ ==eDF  )/M*%	/ s   60B1c           
         | j                   j                  ||t        j                  | j                  d   t        j                  ||g            }i }|j                         D ]#  \  }}	||	vr|	|   }
t        |
|      }|s|||<   % |S )a  Builds a run-to-image-series dict for client consumption.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            experiment: a string experiment id.
            tag: string of the requested tag.
            sample: zero-indexed integer for the requested sample.
            runs: optional list of run names as strings.

        Returns:
            A `RunToSeries` dict (see http_api.md).
        rX   )r   r   )	r\   read_blob_sequencesrb   r`   rc   r   r   r   rG   )rh   r   r}   r   rC   r#   r   r   r   r   blob_sequence_datum_listseriess               r   r   z&MetricsPlugin._get_run_to_image_series@  s     %%99$&2200:#00SEB : 
 $+MMO 	3 J("'/}$6(&F ,2j)	3 r    c                     t        j                  |j                        }|j                  d   }|st	        j
                  d      | j                  ||      \  }}t        j                  |||      S )zServes an individual image.r>   zMissing 'imageId' field)	r   ri   r   r   r   r   _image_data_implr   r   )rh   r   r   rA   datacontent_types         r   rt   zMetricsPlugin._serve_image_datab  sg     !!'//2<<	*--.GHH#44S(C|  $==r    c                     | j                   j                  ||      }t        j                  d|      }t        j                  |t              }||fS )ao  Gets the image data for a blob key.

        Args:
            ctx: A `tensorboard.context.RequestContext` value.
            blob_key: a string identifier for a DataProvider blob.

        Returns:
            A tuple containing:
              data: a raw bytestring of the requested image's contents.
              content_type: a string HTTP content type.
        )rA   N)r\   	read_blobimghdrwhat_IMGHDR_TO_MIMETYPEr^   _DEFAULT_IMAGE_MIMETYPE)rh   r   rA   r   
image_typer   s         r   r   zMetricsPlugin._image_data_implm  sR     "",,S8,D[[t,
*../
 l##r    rw   )__name__
__module____qualname____doc__r	   r`   r   rj   rp   ru   rx   r{   r   Requestapplicationrr   r   r   rs   r   r   r   r   r   r   r   r   rt   r   rz   r    r   rR   rR      s    )&&K
B



 !!E "E4l	 !!H "H&"0'R"H"H D !!> ">$r    rR   )'r   r   r   r   werkzeugr   tensorboardr   r   tensorboard.backendr   tensorboard.datar   tensorboard.pluginsr   tensorboard.plugins.histogramr	   ra   tensorboard.plugins.imagerb   tensorboard.plugins.metricstensorboard.plugins.scalarr_   r   r   	frozensetr`   r   r   r   r.   r2   r4   r9   rG   rM   rP   TBPluginrR   rz   r    r   <module>r      s    &      # ) % + H @ 0 B   5 ##^%?%?@  n889: 4454B:$@$4"J$K(( J$r    