o
    i~                     @   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mZm	Z	 ddl
Z
ddlmZ ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- e.e/Z0e
j1Z2z	ddl3Z3e3j4Z2W n	 e5y   Y nw G dd dZ6G dd dZ7G dd dZ8dS )zlProvides an API for writing protocol buffers to event files to be
consumed by TensorBoard for visualization.    N)OptionalUnion   )CometLogger)append_pbtxtmake_matmake_spritemake_tsv)EventFileWriter)load_onnx_graph)load_openvino_graph)	event_pb2summary_pb2)Event
SessionLog)audiocustom_scalars	histogramhistogram_rawhparamsimageimage_boxesmeshpr_curvepr_curve_rawscalartextvideo)figure_to_imagec                   @   sv   e Zd ZdZdd Zdd ZdddZdd	d
ZdddZdddZ	dd Z
dd Zdd ZejdddddZdS )DummyFileWriterz8A fake file writer that writes nothing to the disk.
    c                 C   s
   || _ d S N_logdir)selflogdir r%   G/home/ubuntu/.local/lib/python3.10/site-packages/tensorboardX/writer.py__init__5   s   
zDummyFileWriter.__init__c                 C   s   | j S z7Returns the directory where event file will be written.r!   r#   r%   r%   r&   
get_logdir8   s   zDummyFileWriter.get_logdirNc                 C      d S r    r%   r#   eventstepwalltimer%   r%   r&   	add_event<      zDummyFileWriter.add_eventc                 C   r+   r    r%   )r#   summaryglobal_stepr/   r%   r%   r&   add_summary?   r1   zDummyFileWriter.add_summaryc                 C   r+   r    r%   )r#   graph_profiler/   r%   r%   r&   	add_graphB   r1   zDummyFileWriter.add_graphc                 C   r+   r    r%   )r#   graphr/   r%   r%   r&   add_onnx_graphE   r1   zDummyFileWriter.add_onnx_graphc                 C   r+   r    r%   r)   r%   r%   r&   flushH   r1   zDummyFileWriter.flushc                 C   r+   r    r%   r)   r%   r%   r&   closeK   r1   zDummyFileWriter.closec                 C   r+   r    r%   r)   r%   r%   r&   reopenN   r1   zDummyFileWriter.reopenr3   r/   c                c   s    | V  d S r    r%   r#   r3   r/   r%   r%   r&   use_metadataQ   s   
zDummyFileWriter.use_metadataNNr    )__name__
__module____qualname____doc__r'   r*   r0   r4   r6   r8   r9   r:   r;   
contextlibcontextmanagerr>   r%   r%   r%   r&   r   1   s    



r   c                   @   s   e Zd ZdZdddZdd Zdd
dZdddZdddZdddZ	dddZ
dd Zdd Zdd Zejd	d	dddZd	S ) 
FileWritera  Writes protocol buffers to event files to be consumed by TensorBoard.

    The `FileWriter` class provides a mechanism to create an event file in a
    given directory and add summaries and events to it. The class updates the
    file contents asynchronously. This allows a training program to call methods
    to add data to the file directly from the training loop, without slowing down
    training.
    
   x    c                    s8   t |}t|||| _ fdd}t| i  _dS )ad  Creates a `FileWriter` and an event file.
        On construction the writer creates a new event file in `logdir`.
        The other arguments to the constructor control the asynchronous writes to
        the event file.

        Args:
          logdir: A string. Directory where event file will be written.
          max_queue: Integer. Size of the queue for pending events and
            summaries before one of the 'add' calls forces a flush to disk.
            Default is ten items.
          flush_secs: Number. How often, in seconds, to flush the
            pending events and summaries to disk. Default is every two minutes.
          filename_suffix: A string. Suffix added to all event filenames
            in the logdir directory. More details on filename construction in
            tensorboard.summary.writer.event_file_writer.EventFileWriter.
        c                      s    j   d S r    event_writerr:   r%   r)   r%   r&   cleanupy   s   z$FileWriter.__init__.<locals>.cleanupN)strr
   rK   atexitregister_default_metadata)r#   r$   	max_queue
flush_secsfilename_suffixrL   r%   r)   r&   r'   `   s   

zFileWriter.__init__c                 C   s
   | j  S r(   )rK   r*   r)   r%   r%   r&   r*      s   
zFileWriter.get_logdirNc                 C   sf   |du r| j dt n|}|dur||_|du r | j dn|}|dur+t||_| j| dS )aI  Adds an event to the event file.
        Args:
          event: An `Event` protocol buffer.
          step: Number. Optional global step value for training process
            to record with the event.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time())
        Nr/   r3   )rP   gettime	wall_timeintr.   rK   r0   r,   r%   r%   r&   r0      s   
zFileWriter.add_eventc                 C   s   t j|d}| ||| dS )a  Adds a `Summary` protocol buffer to the event file.
        This method wraps the provided summary in an `Event` protocol buffer
        and adds it to the event file.

        Args:
          summary: A `Summary` protocol buffer.
          global_step: Number. Optional global step value for training process
            to record with the summary.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time())
        )r2   N)r   r   r0   )r#   r2   r3   r/   r-   r%   r%   r&   r4      s   zFileWriter.add_summaryc                 C   s^   |d }|d }t j| d}| |d| t jd| d}t j|d}| |d| dS )a&  Adds a `Graph` and step stats protocol buffer to the event file.

        Args:
          graph_profile: A `Graph` and step stats protocol buffer.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time()) seconds after epoch
        r   r   	graph_defNprofiler)tagrun_metadata)tagged_run_metadata)r   r   SerializeToStringr0   TaggedRunMetadata)r#   r5   r/   r7   	stepstatsr-   trmr%   r%   r&   r6      s   zFileWriter.add_graphc                 C   "   t j| d}| |d| dS zAdds a `Graph` protocol buffer to the event file.

        Args:
          graph: A `Graph` protocol buffer.
          walltime: float. Optional walltime to override the default (current)
            _get_file_writerfrom time.time())
        rX   Nr   r   r^   r0   r#   r7   r/   r-   r%   r%   r&   r8         zFileWriter.add_onnx_graphc                 C   rb   rc   rd   re   r%   r%   r&   add_openvino_graph   rf   zFileWriter.add_openvino_graphc                 C      | j   dS )zFlushes the event file to disk.
        Call this method to make sure that all pending events have been written to
        disk.
        N)rK   r9   r)   r%   r%   r&   r9      s   zFileWriter.flushc                 C   rh   )zFlushes the event file to disk and close the file.
        Call this method when you do not need the summary writer anymore.
        NrJ   r)   r%   r%   r&   r:      s   zFileWriter.closec                 C   rh   )zReopens the EventFileWriter.
        Can be called after `close()` to add more events in the same directory.
        The events will go into a new events file.
        Does nothing if the EventFileWriter was not closed.
        N)rK   r;   r)   r%   r%   r&   r;      s   zFileWriter.reopenr<   c                c   sD    | j rJ d|dus|dusJ d||d| _ | V  i | _ dS )ah  Context manager to temporarily set default metadata for all enclosed :meth:`add_event`
        calls.

        Args:
            global_step: Global step value to record
            walltime: Walltime to record (defaults to time.time())

        Examples::

            with writer.use_metadata(global_step=10):
                writer.add_event(event)
        z Default metadata is already set.Nz=At least one of `global_step` or `walltime` must be provided.r<   )rP   r=   r%   r%   r&   r>      s   
zFileWriter.use_metadata)rG   rH   rI   r?   r    )r@   rA   rB   rC   r'   r*   r0   r4   r6   r8   rg   r9   r:   r;   rD   rE   r>   r%   r%   r%   r&   rF   V   s    
	




rF   c                   @   s  e Zd ZdZddddddddddif	dee d	ee d
ee dee dee dee dee dee dee fddZ	dd Z
dd Zdd Z		ddeeeeeeef f deeef dee dee fddZ				dded eeef dee d!ee d"ee d#ee fd$d%Z		dd&ed'eeef dee d!ee fd(d)Zd*d+ Z		,		dded-edee d.ee d!ee f
d/d0Z		ddedee d!ee fd1d2Z			3dded4edee d!ee d5ee f
d6d7Z			8dded4edee d!ee d5ee f
d9d:Z			3	dded4ed;edee d!ee d5ee d<eee  fd=d>Z			ddedee d?ee d!ee fd@dAZ		B		CddedDedee dEeeeef  d!ee d5ee fdFdGZ		H	ddedIedee dJee d!ee f
dKdLZ		ddedMedee d!ee fdNdOZdPdQ ZdRdS Z		T	ddUdVZ e!dWdX Z"				Y	ddZed[edee fd\d]Z#		^		dded<ed_edee d`ee d!ee fdadbZ$		^		ddedceddedeedfedgedhedee d`ee d!ee fdidjZ%	Y	kddlee dmednefdodpZ&	Y	kddlee dmednefdqdrZ'dseeeeef f fdtduZ(					ddedvedwedxedee d!ee fdydzZ)d{d| Z*d}d~ Z+dd Z,dd Z-e.j/dddddZ0dS )SummaryWritera  Writes entries directly to event files in the logdir to be
    consumed by TensorBoard.

    The `SummaryWriter` class provides a high-level API to create an event file
    in a given directory and add summaries and events to it. The class updates the
    file contents asynchronously. This allows a training program to call methods
    to add data to the file directly from the training loop, without slowing down
    training.
    NrI   rG   rH   Tdisabledr$   comment
purge_steprQ   rR   rS   write_to_disklog_dircomet_configc
                 K   s  |dur
|du r
|}|s,ddl }ddlm} | d}tjd|d |  | }|| _|| _	|| _
|| _|| _|| _|	| _d| _|
| _d | _| _|   d}g }g }|dk rn|| ||  |d	9 }|dk s[|ddd
 dg | | _i | _i | _dS )a]	  Creates a `SummaryWriter` that will write out events and summaries
        to the event file.

        Args:
            logdir: Save directory location. Default is
              runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.
              Use hierarchical folder structure to compare
              between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
              for each new experiment to compare across them.
            comment: Comment logdir suffix appended to the default
              ``logdir``. If ``logdir`` is assigned, this argument has no effect.
            purge_step:
              When logging crashes at step :math:`T+X` and restarts at step :math:`T`,
              any events whose global_step larger or equal to :math:`T` will be
              purged and hidden from TensorBoard.
              Note that crashed and resumed experiments should have the same ``logdir``.
            max_queue: Size of the queue for pending events and
              summaries before one of the 'add' calls forces a flush to disk.
              Default is ten items.
            flush_secs: How often, in seconds, to flush the
              pending events and summaries to disk. Default is every two minutes.
            filename_suffix: Suffix added to all event filenames in
              the logdir directory. More details on filename construction in
              tensorboard.summary.writer.event_file_writer.EventFileWriter.
            write_to_disk:
              If pass `False`, SummaryWriter will not write to disk.
            comet_config:
              A comet config dictionary. Contains parameters that need to be
              passed to comet like workspace, project_name, api_key, disabled etc

        Examples::

            from tensorboardX import SummaryWriter

            # create a summary writer with automatically generated folder name.
            writer = SummaryWriter()
            # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/

            # create a summary writer using the specified folder name.
            writer = SummaryWriter("my_experiment")
            # folder location: my_experiment

            # create a summary writer with comment appended.
            writer = SummaryWriter(comment="LR_0.1_BATCH_16")
            # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/

        Nr   )datetimez%b%d_%H-%M-%Sruns_g-q=g@xDg?)socketrp   nowstrftimeospathjoingethostnamer$   rl   
_max_queue_flush_secs_filename_suffix_write_to_disk_comet_config_comet_loggerkwargsfile_writerall_writers_get_file_writerappenddefault_binsscalar_dictrP   )r#   r$   rk   rl   rQ   rR   rS   rm   rn   ro   r   rt   rp   current_timevbucketsneg_bucketsr%   r%   r&   r'     s>   ;

zSummaryWriter.__init__c                 C   sF   ddl m} || jvrg | j|< | j| ||t|| g dS )zThis adds an entry to the self.scalar_dict datastructure with format
        {writer_id : [[timestamp, step, value], ...], ...}.
        r   make_npN)x2numr   r   r   floatsqueeze)r#   r[   scalar_valuer3   	timestampr   r%   r%   r&   __append_to_scalar_dictg  s   


z%SummaryWriter.__append_to_scalar_dictc                 C   s   | j st| jd| _| j | ji| _| jS | jdu s | jdu rZtd| j| j| j| j	d| j
| _| jdurQ| jt| jdd | jt| jttjdd | j | ji| _| jS )	z@Returns the default FileWriter instance. Recreates it if closed.r$   N)r$   rQ   rR   rS   zbrain.Event:2)r.   file_version)status)r.   session_logr%   )r~   r   r$   r   r*   r   rF   r{   r|   r}   r   rl   r0   r   r   STARTr)   r%   r%   r&   r   r  s*   
zSummaryWriter._get_file_writerc                 C   s   | j du rt| j| _ | j S )z8Returns a comet logger instance. Recreates it if closed.N)r   r   r   r)   r%   r%   r&   _get_comet_logger  s   
zSummaryWriter._get_comet_loggerhparam_dictmetric_dictnamer3   c                 C   s   t |tust |turtdt||\}}}|s tt }ttj	| j
 |d*}|j
| |j
| |j
| | D ]\}	}
||	|
| qDW d   n1 sZw   Y  |  j||d dS )aM  Add a set of hyperparameters to be compared in tensorboard.

        Args:
            hparam_dict: Each key-value pair in the dictionary is the
              name of the hyper parameter and it's corresponding value.
            metric_dict: Each key-value pair in the dictionary is the
              name of the metric and it's corresponding value.
              Note that the key used here should be unique in the
              tensorboard record. Otherwise the value you added by `add_scalar`
              will be displayed in hparam plugin. In most
              cases, this is unwanted.
            name: Personnalised name of the hparam session
            global_step: Current time step

        Examples::

            from tensorboardX import SummaryWriter
            with SummaryWriter() as w:
                for i in range(5):
                    w.add_hparams({'lr': 0.1*i, 'bsize': i},
                                  {'hparam/accuracy': 10*i, 'hparam/loss': 10*i})

        Expected result:

        .. image:: _static/img/tensorboard/add_hparam.png
           :scale: 50 %
        z1hparam_dict and metric_dict should be dictionary.r   Nr.   )typedict	TypeErrorr   rM   rU   ri   rw   rx   ry   r   r*   r4   items
add_scalarr   log_parameters)r#   r   r   r   r3   expssiseiw_hpkr   r%   r%   r&   add_hparams  s   !zSummaryWriter.add_hparamsr[   r   r/   display_namesummary_descriptionc                 C   s4   |   t|||||| |  |||| dS )ag  Add scalar data to summary.

        Args:
            tag: Data identifier
            scalar_value: Value to be logged in tensorboard
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event
            display_name: The title of the plot. If empty string is passed,
              `tag` will be used.
            summary_description: The comprehensive text that will showed
              by clicking the information icon on TensorBoard.
        Examples::

            from tensorboardX import SummaryWriter
            writer = SummaryWriter()
            x = range(100)
            for i in x:
                writer.add_scalar('y=2x', i * 2, i)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_scalar.png
           :scale: 50 %

        N)r   r4   r   r   
log_metric)r#   r[   r   r3   r/   r   r   r%   r%   r&   r     s   "zSummaryWriter.add_scalarmain_tagtag_scalar_dictc           
      C   s   |du rt   n|}|   }| D ]5\}}tjt|||}|| jv r-| j| }	n
t	|d}	|	| j|< |	
t|||| | |||| q|  j|||d dS )a:  Adds many scalar data to summary.

        Note that this function also keeps logged scalars in memory. In extreme case it explodes your RAM.

        Args:
            main_tag: The parent name for the tags
            tag_scalar_dict: Key-value pair storing the tag and corresponding values
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event

        Examples::

            from tensorboardX import SummaryWriter
            writer = SummaryWriter()
            r = 5
            for i in range(100):
                writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
                                                'xcosx':i*np.cos(i/r),
                                                'tanx': np.tan(i/r)}, i)
            writer.close()
            # This call adds three values to the same scalar plot with the tag
            # 'run_14h' in TensorBoard's scalar section.

        Expected result:

        .. image:: _static/img/tensorboard/add_scalars.png
           :scale: 50 %

        Nr   r   )rU   r   r*   r   rw   rx   ry   rM   r   rF   r4   r   %_SummaryWriter__append_to_scalar_dictr   log_metrics)
r#   r   r   r3   r/   	fw_logdirr[   r   fw_tagfwr%   r%   r&   add_scalars  s   #


zSummaryWriter.add_scalarsc                 C   sB   t |d}t| j| W d   n1 sw   Y  i | _dS )a  Exports to the given path an ASCII file containing all the scalars written
        so far by this instance, with the following format:
        {writer_id : [[timestamp, step, value], ...], ...}

        The scalars saved by ``add_scalars()`` will be flushed after export.
        wN)openjsondumpr   )r#   rx   fr%   r%   r&   export_scalars_to_json  s   
z$SummaryWriter.export_scalars_to_json
tensorflowvaluesbinsc                 C   sL   t |tr|dkr| j}|  t||||d|| |  ||| dS )a  Add histogram to summary.

        Args:
            tag: Data identifier
            values: Values to build histogram
            global_step: Global step value to record
            bins: One of {'tensorflow','auto', 'fd', ...}. This determines how the
              bins are made. You can find other options in the `numpy reference
              <https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html>`_.
            walltime: Optional override default walltime (time.time()) of event

        Examples::

            from tensorboardX import SummaryWriter
            import numpy as np
            writer = SummaryWriter()
            for i in range(10):
                x = np.random.random(1000)
                writer.add_histogram('distribution centers', x + i, i)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_histogram.png
           :scale: 50 %

        r   )max_binsN)
isinstancerM   r   r   r4   r   r   log_histogram)r#   r[   r   r3   r   r/   r   r%   r%   r&   add_histogram   s   #zSummaryWriter.add_histogramc              	   C   sX   t |t |krtdt||||||||}|  ||	|
 |  j|||	d dS )ao  Adds histogram with raw data.

        Args:
            tag: Data identifier
            min (float or int): Min value
            max (float or int): Max value
            num (int): Number of values
            sum (float or int): Sum of all values
            sum_squares (float or int): Sum of squares for all values
            bucket_limits (torch.Tensor, numpy.array): Upper value per
              bucket, note that the bucket_limits returned from `np.histogram`
              has one more element. See the comment in the following example.
            bucket_counts (torch.Tensor, numpy.array): Number of values per bucket
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event

        Examples::

            import numpy as np
            dummy_data = []
            for idx, value in enumerate(range(30)):
                dummy_data += [idx + 0.001] * value
            values = np.array(dummy_data).astype(float).reshape(-1)
            counts, limits = np.histogram(values)
            sum_sq = values.dot(values)
            with SummaryWriter() as summary_writer:
                summary_writer.add_histogram_raw(
                        tag='hist_dummy_data',
                        min=values.min(),
                        max=values.max(),
                        num=len(values),
                        sum=values.sum(),
                        sum_squares=sum_sq,
                        bucket_limits=limits[1:].tolist(),  # <- note here.
                        bucket_counts=counts.tolist(),
                        global_step=0)

        z;len(bucket_limits) != len(bucket_counts), see the document.r   N)len
ValueErrorr   r   r4   r   log_histogram_raw)r#   r[   minmaxnumsumsum_squaresbucket_limitsbucket_countsr3   r/   r2   r%   r%   r&   add_histogram_rawI  s"   2zSummaryWriter.add_histogram_rawCHW
img_tensordataformatsc                 C   sF   t |||d}|jd j j}|  ||| |  j|||d dS )a  Add image data to summary.

        Note that this requires the ``pillow`` package.

        Args:
            tag: Data identifier
            img_tensor: An `uint8` or `float` Tensor of shape `
                [channel, height, width]` where `channel` is 1, 3, or 4.
                The elements in img_tensor can either have values
                in [0, 1] (float32) or [0, 255] (uint8).
                Users are responsible to scale the data in the correct range/type.
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event.
            dataformats: This parameter specifies the meaning of each dimension of the input tensor.
        Shape:
            img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
            convert a batch of tensor into 3xHxW format or use ``add_images()`` and let us do the job.
            Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitible as long as
            corresponding ``dataformats`` argument is passed. e.g. CHW, HWC, HW.

        Examples::

            from tensorboardX import SummaryWriter
            import numpy as np
            img = np.zeros((3, 100, 100))
            img[0] = np.arange(0, 10000).reshape(100, 100) / 10000
            img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000

            img_HWC = np.zeros((100, 100, 3))
            img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000
            img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000

            writer = SummaryWriter()
            writer.add_image('my_image', img, 0)

            # If you have non-default dimension setting, set the dataformats argument.
            writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_image.png
           :scale: 50 %

        r   r   r   N)r   valueencoded_image_stringr   r4   r   log_image_encoded)r#   r[   r   r3   r/   r   r2   r   r%   r%   r&   	add_image  s   4zSummaryWriter.add_imageNCHWc           
      C   s   t |tr?| dkr| dkrtd td dS ddl}z||d}W n ty:   ddl}||d}Y nw d| }t|||d}|j	d jj
}	|  ||| |  j|	||d	 dS )
a  Add batched (4D) image data to summary.
        Besides passing 4D (NCHW) tensor, you can also pass a list of tensors of the same size.
        In this case, the ``dataformats`` should be `CHW` or `HWC`.
        Note that this requires the ``pillow`` package.

        Args:
            tag: Data identifier
            img_tensor: Image data
                The elements in img_tensor can either have values in [0, 1] (float32) or [0, 255] (uint8).
                Users are responsible to scale the data in the correct range/type.
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event
        Shape:
            img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be
            accepted. e.g. NCHW or NHWC.

        Examples::

            from tensorboardX import SummaryWriter
            import numpy as np

            img_batch = np.zeros((16, 3, 100, 100))
            for i in range(16):
                img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
                img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i

            writer = SummaryWriter()
            writer.add_images('my_image_batch', img_batch, 0)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_images.png
           :scale: 30 %

        r   HWCzEA list of image is passed, but the dataformat is neither CHW nor HWC.zNothing is written.Nr   Nr   r   )r   listupperprinttorchstackr   numpyr   r   r   r   r4   r   r   )
r#   r[   r   r3   r/   r   r   npr2   r   r%   r%   r&   
add_images  s&   
+zSummaryWriter.add_images
box_tensorlabelsc                 K   s   |durt |tr|g}t||jd krtd d}t|||f||d|}	|	jd jj	}
| 
 |	|| |  j|
||d dS )a  Add image and draw bounding boxes on the image.

        Args:
            tag: Data identifier
            img_tensor: Image data
            box_tensor: Box data (for detected objects)
              box should be represented as [x1, y1, x2, y2].
            global_step: Global step value to record
            walltime: override default walltime (time.time()) of event
            labels: The strings to be show on each bounding box.
        Shape:
            img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument.
            e.g. CHW or HWC

            box_tensor: (torch.Tensor, numpy.array, or string/blobname): NX4,  where N is the number of
            boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax).
        Nr   z@Number of labels do not equal to number of box, skip the labels.)r   r   r   )r   rM   r   shapeloggerwarningr   r   r   r   r   r4   r   r   )r#   r[   r   r   r3   r/   r   r   r   r2   r   r%   r%   r&   add_image_with_boxes  s$   

z"SummaryWriter.add_image_with_boxesr:   c                 C   sF   t |tr| j|t||||dd dS | j|t||||dd dS )a  Render matplotlib figure into an image and add it to summary.

        Note that this requires the ``matplotlib`` package.

        Args:
            tag: Data identifier
            figure (matplotlib.pyplot.figure) or list of figures: Figure or a list of figures
            global_step: Global step value to record
            close: Flag to automatically close the figure
            walltime: Override default walltime (time.time()) of event
        r   r   r   N)r   r   r   r   )r#   r[   figurer3   r:   r/   r%   r%   r&   
add_figure,  s   
zSummaryWriter.add_figure   NTCHW
vid_tensorfpsc           	      C   sH   t ||||d}|jd jj}|  ||| |  j|||d dS )a>  Add video data to summary.

        Note that this requires the ``moviepy`` package.

        Args:
            tag: Data identifier
            vid_tensor: Video data
            global_step: Global step value to record
            fps: Frames per second
            walltime: Optional override default walltime (time.time()) of event
            dataformats: Specify different permutation of the video tensor
        Shape:
            vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255]
            for type `uint8` or [0, 1] for type `float`.
        r   r   r   N)r   r   r   r   r   r4   r   r   )	r#   r[   r   r3   r   r/   r   r2   r   r%   r%   r&   	add_videoC  s   zSummaryWriter.add_videoD  
snd_tensorsample_ratec                 C   s6   |   t|||d|| |  j||||d dS )a   Add audio data to summary.

        Args:
            tag: Data identifier
            snd_tensor: Sound data
            global_step: Global step value to record
            sample_rate: sample rate in Hz
            walltime: Optional override default walltime (time.time()) of event
        Shape:
            snd_tensor: :math:`(L, C)`. The values should lie between [-1, 1].
            Where `L` is the number of audio frames and `C` is the channel. Set
            channel equals to 2 for stereo.
        )r   r   N)r   r4   r   r   	log_audio)r#   r[   r   r3   r   r/   r%   r%   r&   	add_audio`  s   zSummaryWriter.add_audiotext_stringc                 C   s,   |   t|||| |  || dS )a  Add text data to summary.

        Args:
            tag: Data identifier
            text_string: String to save
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time()) of event
        Examples::

            writer.add_text('lstm', 'This is an lstm', 0)
            writer.add_text('rnn', 'This is an rnn', 10)
        N)r   r4   r   r   log_text)r#   r[   r   r3   r/   r%   r%   r&   add_textx  s   zSummaryWriter.add_textc                 C   $   |   t| |  | dS )zxAdd onnx graph to TensorBoard.

        Args:
            onnx_model_file (string): The path to the onnx model.
        N)r   r8   r   r   	log_asset)r#   onnx_model_filer%   r%   r&   r8        zSummaryWriter.add_onnx_graphc                 C   r   )zAdd openvino graph to TensorBoard.

        Args:
            xmlname (string): The path to the openvino model. (the xml file)
        N)r   rg   r   r   r   )r#   xmlnamer%   r%   r&   rg     r   z SummaryWriter.add_openvino_graphFc                 C   s*   ddl m} |  |||||d dS )aV  Add graph data to summary. The graph is actually processed by `torch.utils.tensorboard.add_graph()`

        Args:
            model (torch.nn.Module): Model to draw.
            input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of
                variables to be fed.
            verbose (bool): Whether to print graph structure in console.
            use_strict_trace (bool): Whether to pass keyword argument `strict` to
                `torch.jit.trace`. Pass False when you want the tracer to
                record your mutable container types (list, dict)
        r   )r7   )use_strict_traceN)&torch.utils.tensorboard._pytorch_graphr7   r   r6   )r#   modelinput_to_modelverboser   r7   r%   r%   r&   r6     s   zSummaryWriter.add_graphc                 C   sJ   | }| ddtd}| ddtd}| ddtd}|S )N%z%{:02x}/\)replaceformatord)rawstrretvalr%   r%   r&   _encode  s
   zSummaryWriter._encodedefaultmat	label_imgc                 C   s^  ddl m} ||}|du rd}t|d d| | }tj|  	 |}	zt
|	 W n ty>   td Y nw |durW|jd t|ksPJ dt||	|d	 |dur||jd |jd ksiJ d
|jd |jd kswJ dt||	 |jdksJ dt||	 t|||  	 ||| |dur| dnd}
|  j||||
d dS )a  Add embedding projector data to summary.

        Args:
            mat: A matrix which each row is the feature vector of the data point
            metadata (list): A list of labels, each element will be converted to
                string.
            label_img: Images correspond to each
                data point. Each image should be square sized. The amount and
                the size of the images are limited by the Tensorboard frontend,
                see limits below.
            global_step: Global step value to record
            tag: Name for the embedding
        Shape:
            mat: :math:`(N, D)`, where N is number of data and D is feature dimension

            label_img: :math:`(N, C, H, W)`, where `Height` should be equal to `Width`.
            Also, :math:`\sqrt{N}*W` must be less than or equal to 8192, so that the generated sprite
            image can be loaded by the Tensorboard frontend
            (see `tensorboardX#516 <https://github.com/lanpa/tensorboardX/issues/516>`_ for more).

        Examples::

            import keyword
            import torch
            meta = []
            while len(meta)<100:
                meta = meta+keyword.kwlist # get some strings
            meta = meta[:100]

            for i, v in enumerate(meta):
                meta[i] = v+str(i)

            label_img = torch.rand(100, 3, 32, 32)
            for i in range(100):
                label_img[i]*=i/100.0

            writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img)
            writer.add_embedding(torch.randn(100, 5), label_img=label_img)
            writer.add_embedding(torch.randn(100, 5), metadata=meta)
        r   r   Nr      r   zKwarning: Embedding dir exists, did you set global_step for add_embedding()?z&#labels should equal with #data points)metadata_headerz&#images should equal with #data points      z6Image should be square, see tensorflow/tensorboard#670z@mat should be 2D, where mat.size(0) is the number of data pointsz.json)template_filename)r   r   rM   zfillr  rw   rx   ry   r   r*   makedirsOSErrorr   r   r   r	   r   ndimr   r   r   log_embedding)r#   r	  metadatar
  r3   r[   r  r   subdir	save_pathr  r%   r%   r&   add_embedding  s>   4


zSummaryWriter.add_embedding   predictionsnum_thresholdsc           
      C   sZ   ddl m} ||||}}t|||||}	|  |	|| |  j||	||d dS )a  Adds precision recall curve.
        Plotting a precision-recall curve lets you understand your model's
        performance under different threshold settings. With this function,
        you provide the ground truth labeling (T/F) and prediction confidence
        (usually the output of your model) for each target. The TensorBoard UI
        will let you choose the threshold interactively.

        Args:
            tag: Data identifier
            labels: Ground truth data. Binary label for each element.
            predictions:
              The probability that an element be classified as true.
              Value should in [0, 1]
            global_step: Global step value to record
            num_thresholds: Number of thresholds used to draw the curve.
            walltime: Override default walltime (time.time()) of event

        Examples::

            from tensorboardX import SummaryWriter
            import numpy as np
            labels = np.random.randint(2, size=100)  # binary label
            predictions = np.random.rand(100)
            writer = SummaryWriter()
            writer.add_pr_curve('pr_curve', labels, predictions, 0)
            writer.close()

        r   r   r   N)r   r   r   r   r4   r   log_pr_data)
r#   r[   r   r  r3   r  weightsr/   r   r2   r%   r%   r&   add_pr_curve  s   %zSummaryWriter.add_pr_curvetrue_positive_countsfalse_positive_countstrue_negative_countsfalse_negative_counts	precisionrecallc                 C   sL   |   t||||||||	|
	|| |  j|||||||||	|
d
 dS )a  Adds precision recall curve with raw data.

        Args:
            tag: Data identifier
            global_step: Global step value to record
            num_thresholds (int): Number of thresholds used to draw the curve.
            walltime: Optional override default walltime (time.time()) of event
              see: `Tensorboard refenence
              <https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md>`_
        )	r.   r  r   r!  r"  r#  r$  r  r  N)r   r4   r   r   log_pr_raw_data)r#   r[   r  r   r!  r"  r#  r$  r3   r  r  r/   r%   r%   r&   add_pr_curve_rawC  s0   	
zSummaryWriter.add_pr_curve_rawuntitledtagscategorytitlec                 C   s&   ||d|gii}|   t| dS )aC  Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument
        is *tags*.

        Args:
            tags: list of tags that have been used in ``add_scalar()``

        Examples::

            writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330'])
        	MultilineNr   r4   r   r#   r(  r)  r*  layoutr%   r%   r&   !add_custom_scalars_multilinechartp  s   z/SummaryWriter.add_custom_scalars_multilinechartc                 C   s6   t |dksJ ||d|gii}|  t| dS )ap  Shorthand for creating marginchart. Similar to ``add_custom_scalars()``, but the only necessary argument
        is *tags*, which should have exactly 3 elements.

        Args:
            tags: list of tags that have been used in ``add_scalar()``

        Examples::

            writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006'])
        r  MarginN)r   r   r4   r   r-  r%   r%   r&   add_custom_scalars_marginchart  s   z,SummaryWriter.add_custom_scalars_marginchartr.  c                 C   s   |   t| dS )a3  Create special chart by collecting charts tags in 'scalars'. Note that this function can only be called once
        for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called
        before or after the training loop. See ``examples/demo_custom_scalars.py`` for more.

        Args:
            layout: {categoryName: *charts*}, where *charts* is also a dictionary
              {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type
              (one of **Multiline** or **Margin**) and the second element should be a list containing the tags
              you have used in add_scalar function, which will be collected into the new chart.

        Examples::

            layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]},
                         'USA':{ 'dow':['Margin',   ['dow/aaa', 'dow/bbb', 'dow/ccc']],
                              'nasdaq':['Margin',   ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}}

            writer.add_custom_scalars(layout)
        Nr,  )r#   r.  r%   r%   r&   add_custom_scalars  s   z SummaryWriter.add_custom_scalarsverticescolorsfacesc              	   C   s<   |   t||||||| |  ||||||| dS )ax  Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js,
        so it allows users to interact with the rendered object. Besides the basic definitions
        such as vertices, faces, users can further provide camera parameter, lighting condition, etc.
        Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for
        advanced usage.

        Args:
            tag: Data identifier
            vertices: List of the 3D coordinates of vertices.
            colors: Colors for each vertex
            faces: Indices of vertices within each triangle. (Optional)
            config_dict: Dictionary with ThreeJS classes names and configuration.
            global_step: Global step value to record
            walltime: Optional override default walltime (time.time())
              seconds after epoch of event

        Shape:
            vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels). If
              Nothing show on tensorboard, try normalizing the values to [-1, 1].

            colors: :math:`(B, N, 3)`. The values should lie in [0, 255].

            faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`.

        Expected result after running ``examples/demo_mesh.py``:

        .. image:: _static/img/tensorboard/add_mesh.png
           :scale: 30 %

        N)r   r4   r   r   log_mesh)r#   r[   r3  r4  r5  config_dictr3   r/   r%   r%   r&   add_mesh  s   'zSummaryWriter.add_meshc                 C   sP   | j du rdS | j  D ]
}|  |  qd | _| _ |    d| _dS )zClose the current SummaryWriter. This call flushes the unfinished write operation.
        Use context manager (with statement) whenever it's possible.
        N)r   r   r9   r:   r   r   endr   r#   writerr%   r%   r&   r:     s   


zSummaryWriter.closec                 C   s*   | j du rdS | j  D ]}|  qdS )zForce the data in memory to be flushed to disk. Use this call if tensorboard does not update reqularly.
        Another way is to set the `flush_secs` when creating the SummaryWriter.
        N)r   r   r9   r:  r%   r%   r&   r9     s
   

zSummaryWriter.flushc                 C   s   | S r    r%   r)   r%   r%   r&   	__enter__  r1   zSummaryWriter.__enter__c                 C   s   |    d S r    )r:   )r#   exc_typeexc_valexc_tbr%   r%   r&   __exit__  s   zSummaryWriter.__exit__r<   c                c   s@    |   j||d | V  W d   dS 1 sw   Y  dS )ac  Context manager to temporarily set default metadata for all enclosed :meth:`add_*` calls.

        Args:
            global_step: Global step value to record
            walltime: Walltime to record (defaults to time.time())

        Examples::

            with writer.use_metadata(global_step=10):
                writer.add_scalar("loss", 3.0)
        r<   N)r   r>   r=   r%   r%   r&   r>     s   "zSummaryWriter.use_metadatar?   )NNrI   rI   )Nr   NN)NNr   )NNr   )NNr   N)NTN)Nr   Nr   )Nr   N)NFT)NNNr  N)Nr  NN)r  r'  )NNNNN)1r@   rA   rB   rC   r   rM   rW   boolr   r'   r   r   r   r   r   r   numpy_compatibler   r   r   r   r   r   r   r   r   r   r   r   r   r8   rg   r6   staticmethodr  r  r  r&  r/  r1  r2  r8  r:   r9   r<  r@  rD   rE   r>   r%   r%   r%   r&   ri      sb   	

_


4

*

2
3

F
>
D

,

!




X
8	

0



+	ri   )9rC   rN   rD   r   loggingrw   rU   typingr   r   r   comet_utilsr   	embeddingr   r   r   r	   event_file_writerr
   
onnx_graphr   openvino_graphr   protor   r   proto.event_pb2r   r   r2   r   r   r   r   r   r   r   r   r   r   r   r   r   utilsr   	getLoggerr@   r   ndarrayrB  r   TensorImportErrorr   rF   ri   r%   r%   r%   r&   <module>   s<    <

% (