
    h~                        S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJrJ	r	  SSK
r
SSKJr  SSKJrJrJrJr  SSKJr  SSKJr  SS	KJr  SS
KJrJr  SSKJrJr  SSKJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+  SSK,J-r-  \R\                  " \/5      r0\
Rb                  r2 SSK3r3\3Rh                  r2 " S S5      r6 " S S5      r7 " S S5      r8g! \5 a     N'f = f)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                       \ rS rSrSrS rS rSS jrSS jrSS jr	SS	 jr
S
 rS rS r\R                  SSS.S j5       rSrg)DummyFileWriter1   z8A fake file writer that writes nothing to the disk.
    c                     Xl         g N_logdir)selflogdirs     M/var/www/fran/franai/venv/lib/python3.13/site-packages/tensorboardX/writer.py__init__DummyFileWriter.__init__5   s        c                     U R                   $ z7Returns the directory where event file will be written.r%   r'   s    r)   
get_logdirDummyFileWriter.get_logdir8   s    ||r,   Nc                     g r$    r'   eventstepwalltimes       r)   	add_eventDummyFileWriter.add_event<       r,   c                     g r$   r3   )r'   summaryglobal_stepr7   s       r)   add_summaryDummyFileWriter.add_summary?   r:   r,   c                     g r$   r3   )r'   graph_profiler7   s      r)   	add_graphDummyFileWriter.add_graphB   r:   r,   c                     g r$   r3   )r'   graphr7   s      r)   add_onnx_graphDummyFileWriter.add_onnx_graphE   r:   r,   c                     g r$   r3   r/   s    r)   flushDummyFileWriter.flushH   r:   r,   c                     g r$   r3   r/   s    r)   closeDummyFileWriter.closeK   r:   r,   c                     g r$   r3   r/   s    r)   reopenDummyFileWriter.reopenN   r:   r,   r=   r7   c             #      #    U v   g 7fr$   r3   r'   r=   r7   s      r)   use_metadataDummyFileWriter.use_metadataQ   s
     
s   r%   NNr$   )__name__
__module____qualname____firstlineno____doc__r*   r0   r8   r>   rB   rF   rI   rL   rO   
contextlibcontextmanagerrT   __static_attributes__r3   r,   r)   r!   r!   1   sS     *.  r,   r!   c                       \ rS rSrSrSS jrS rSS jrSS jrSS jr	SS	 jr
SS
 jrS rS rS r\R                   SSS.S j5       rSrg)
FileWriterV   a  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.
c                    ^  [        U5      n[        XX45      T l        U 4S jn[        R                  " U5        0 T l        g)a  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                  :   > T R                   R                  5         g r$   event_writerrL   r/   s   r)   cleanup$FileWriter.__init__.<locals>.cleanupy   s    ##%r,   N)strr   re   atexitregister_default_metadata)r'   r(   	max_queue
flush_secsfilename_suffixrf   s   `     r)   r*   FileWriter.__init__`   s;    * V+z<	& 	 !#r,   c                 6    U R                   R                  5       $ r.   )re   r0   r/   s    r)   r0   FileWriter.get_logdir   s      ++--r,   Nc                    Uc/  U R                   R                  S[        R                  " 5       5      OUnUb  X1l        Uc  U R                   R                  S5      OUnUb  [	        U5      Ul        U R                  R                  U5        g)a  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())
Nr7   r=   )rk   gettime	wall_timeintr6   re   r8   r4   s       r)   r8   FileWriter.add_event   s      ""&&z499;? 	
 &O<@Lt%%))-8d TEJ##E*r,   c                 P    [         R                  " US9nU R                  XBU5        g)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())
)r<   N)r   r   r8   )r'   r<   r=   r7   r5   s        r)   r>   FileWriter.add_summary   s      0u84r,   c                    US   nUS   n[         R                  " UR                  5       S9nU R                  USU5        [         R                  " SUR                  5       S9n[         R                  " US9nU R                  USU5        g)zAdds 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   SerializeToStringr8   TaggedRunMetadata)r'   rA   r7   rE   	stepstatsr5   trms          r)   rB   FileWriter.add_graph   s|     a !!$	%*A*A*CDudH-)))D)D)FHC8udH-r,   c                 n    [         R                  " UR                  5       S9nU R                  USU5        g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())
r{   Nr   r   r   r8   r'   rE   r7   r5   s       r)   rF   FileWriter.add_onnx_graph   +     %*A*A*CDudH-r,   c                 n    [         R                  " UR                  5       S9nU R                  USU5        gr   r   r   s       r)   add_openvino_graphFileWriter.add_openvino_graph   r   r,   c                 8    U R                   R                  5         g)zqFlushes the event file to disk.
Call this method to make sure that all pending events have been written to
disk.
N)re   rI   r/   s    r)   rI   FileWriter.flush   s    
 	!r,   c                 8    U R                   R                  5         g)zuFlushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
Nrd   r/   s    r)   rL   FileWriter.close   s     	!r,   c                 8    U R                   R                  5         g)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)re   rO   r/   s    r)   rO   FileWriter.reopen   s     	  "r,   rQ   c             #   ~   #    U R                   (       a   S5       eUc
  Uc   S5       eXS.U l         U v   0 U l         g7f)a(  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.rQ   )rk   rS   s      r)   rT   FileWriter.use_metadata   sQ      ))M+MM)#x';	KJ	K;1<!S
!#s   ;=)rk   re   )
   x    rV   r$   )rW   rX   rY   rZ   r[   r*   r0   r8   r>   rB   rF   r   rI   rL   rO   r\   r]   rT   r^   r3   r,   r)   r`   r`   V   sX    $>.+.5.$	.	.""# *. $ $r,   r`   c                   p   \ rS rSrSrSSSSSSSSSS04	S	\\   S
\\   S\\   S\\   S\\   S\\   S\\   S\\   S\\	   4S jjr
S rS rS r  S]S\	\\\\\\4   4   S\	\\4   S\\   S\\   4S jjr    S^S\S\\\4   S\\   S\\   S\\   S\\   4S  jjr  S]S!\S"\	\\4   S\\   S\\   4S# jjrS$ r    S_S\S%\S\\   S&\\   S\\   4
S' jjr  S]S\S\\   S\\   4S( jjr   S`S\S)\S\\   S\\   S*\\   4
S+ jjr   SaS\S)\S\\   S\\   S*\\   4
S, jjr    SbS\S)\S-\S\\   S\\   S*\\   S.\\\      4S/ jjr   ScS\S\\   S0\\   S\\   4S1 jjr    SdS\S2\S\\   S3\\\\4      S\\   S*\\   4S4 jjr   SeS\S5\S\\   S6\\   S\\   4
S7 jjr  S]S\S8\S\\   S\\   4S9 jjrS: rS; r    SfS< jr!\"S= 5       r#     SgS>\S?\S\\   4S@ jjr$    ShS\S.\SA\S\\   SB\\   S\\   4SC jjr%    ShS\SD\SE\SF\SG\SH\SI\S\\   SB\\   S\\   4SJ jjr&  SiSK\\   SL\SM\4SN jjr'  SiSK\\   SL\SM\4SO jjr(SP\	\\	\\4   4   4SQ jr)     SjS\SR\SS\ST\S\\   S\\   4SU jjr*SV r+SW r,SX r-SY r.\/R`                  SSSZ.S[ j5       r1S\r2g)kSummaryWriter   a  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.
Nr   r   r   Tdisabledr(   comment
purge_steprl   rm   rn   write_to_disklog_dircomet_configc
                 H   Ub  Uc  UnU(       d`  SSK nSSKJn  UR                  5       R                  S5      n[        R
                  R                  SUS-   UR                  5       -   U-   5      nXl        X0l	        X@l
        XPl        X`l        Xpl        Xl        SU l        Xl        S=U l        U l        U R'                  5         Sn/ n/ nUS:  a0  UR)                  U5        UR)                  U* 5        US	-  nUS:  a  M0  USSS
2   S/-   U-   U l        0 U l        0 U l        g)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?)socketr   nowstrftimeospathjoingethostnamer(   r   
_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_dictrk   )r'   r(   r   r   rl   rm   rn   r   r   r   r   r   r   current_timevbucketsneg_bucketss                    r)   r*   SummaryWriter.__init__  s*   v 6>F)#<<>22?CLWW\\s*V-?-?-AAGKMF$#% /+)! /324+ $hNN1r"HA $h ("-3g=!#r,   c           	          SSK Jn  XR                  ;  a  / U R                  U'   U R                  U   R                  XC[	        U" U5      R                  5       5      /5        g)zyThis 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_valuer=   	timestampr   s         r)   __append_to_scalar_dict%SummaryWriter.__append_to_scalar_dictg  sX    
 	#&&&$&DS!$$U7<+@+H+H+J%KL	Nr,   c           	         U R                   (       dO  [        U R                  S9U l        U R                  R	                  5       U R                  0U l        U R                  $ U R
                  b  U R                  c  [        SU R                  U R                  U R                  U R                  S.U R                  D6U l        U R                  bo  U R                  R                  [        U R                  SS95        U R                  R                  [        U R                  [        [        R                  S9S95        U R                  R	                  5       U R                  0U l        U R                  $ )z@Returns the default FileWriter instance. Recreates it if closed.r(   )r(   rl   rm   rn   zbrain.Event:2)r6   file_version)status)r6   session_logr3   )r   r!   r(   r   r0   r   r`   r   r   r   r   r   r8   r   r   STARTr/   s    r)   r   SummaryWriter._get_file_writerr  s+   "".dkkBD $ 0 0 ; ; =t?O?OPD####t'7'7'?)  948OO595E5E:>:O:O 9 -1KK	 9D
 *  **t_MO  **tJjN^N^<_`b $ 0 0 ; ; =t?O?OPDr,   c                 h    U R                   c  [        U R                  5      U l         U R                   $ )z8Returns a comet logger instance. Recreates it if closed.)r   r   r   r/   s    r)   _get_comet_loggerSummaryWriter._get_comet_logger  s-    %!,T-?-?!@D!!!r,   hparam_dictmetric_dictnamer=   c                    [        U5      [        Ld  [        U5      [        La  [        S5      e[        X5      u  pVnU(       d  [	        [
        R
                  " 5       5      n[        [        R                  R                  U R                  R                  5       U5      S9 nUR                  R                  U5        UR                  R                  U5        UR                  R                  U5        UR                  5        H  u  pUR                  XU5        M     SSS5        U R                  5       R!                  XS9  g! , (       d  f       N,= f)a  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r6   )typedict	TypeErrorr   rh   rt   r   r   r   r   r   r0   r>   items
add_scalarr   log_parameters)r'   r   r   r   r=   expssiseiw_hpkr   s              r)   add_hparamsSummaryWriter.add_hparams  s    B D(D,=T,IOPP9#tyy{#D"'',,t/?/?/J/J/Ld"STX\((-((-((-#))+k2 ,	 U 	 ///N UTs   "A=E
Er~   r   r7   display_namesummary_descriptionc                     U R                  5       R                  [        XXV5      X45        U R                  5       R	                  XX#5        g)a  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   r>   r   r   
log_metric)r'   r~   r   r=   r7   r   r   s          r)   r   SummaryWriter.add_scalar  sB    D 	++3lH+	a ++C|Yr,   main_tagtag_scalar_dictc                    Uc  [         R                   " 5       OUnU R                  5       R                  5       nUR                  5        H  u  pg[        R
                  R                  [        U5      X5      nXR                  ;   a  U R                  U   n	O[        US9n	XR                  U'   U	R                  [        X5      X45        U R                  XX45        M     U R                  5       R                  X!US9  g)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   )rt   r   r0   r   r   r   r   rh   r   r`   r>   r   %_SummaryWriter__append_to_scalar_dictr   log_metrics)
r'   r   r   r=   r7   	fw_logdirr~   r   fw_tagfws
             r)   add_scalarsSummaryWriter.add_scalars  s    F #+"2499;))+668	!0!6!6!8CWW\\#i.(@F)))%%f-v.+-  (NN6(9&2((k= "9 	 ,,_[,Yr,   c                     [        US5       n[        R                  " U R                  U5        SSS5        0 U l        g! , (       d  f       N= f)zExports 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'   r   fs      r)   export_scalars_to_json$SummaryWriter.export_scalars_to_json  s8     $_IId&&*  _s	   "?
Avaluesbinsc           	          [        U[        5      (       a  US:X  a  U R                  nU R                  5       R	                  [        XXFS9X55        U R                  5       R                  X!U5        g)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 %


tensorflow)max_binsN)
isinstancerh   r   r   r>   r   r   log_histogram)r'   r~   r   r=   r   r7   r  s          r)   add_histogramSummaryWriter.add_histogram   sa    F dC  T\%9$$D++c4;[	T ..vKHr,   c           
          [        U5      [        U5      :w  a  [        S5      e[        UUUUUUUU5      nU R                  5       R	                  UU	U
5        U R                  5       R                  XU	S9  g)ag  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   r>   r   log_histogram_raw)r'   r~   minmaxnumsumsum_squaresbucket_limitsbucket_countsr=   r7   r<   s               r)   add_histogram_rawSummaryWriter.add_histogram_rawI  s    d }]!33Z[[ # # # # + - -/ 	++	 	 223k2Rr,   
img_tensordataformatsc                     [        XUS9nUR                  S   R                   R                  nU R                  5       R	                  XcU5        U R                  5       R                  XqUS9  g)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   r>   r   log_image_encoded)r'   r~   r  r=   r7   r  r<   r  s           r)   	add_imageSummaryWriter.add_image  sf    h [A&}}Q/55JJ++(	, 223GS^2_r,   c                    [        U[        5      (       a\  UR                  5       S:w  a+  UR                  5       S:w  a  [        S5        [        S5        gSSKn UR
                  " US5      nSU-   n[        XUS9nUR                  S   R                  R                  n	U R                  5       R                  XU5        U R                  5       R                  XUS	9  g! [         a    SSKnUR                  US5      n Nf = f)
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 %

CHW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   r>   r   r  )
r'   r~   r  r=   r7   r  r$  npr<   r  s
             r)   
add_imagesSummaryWriter.add_images  s    V j$''  "e+0A0A0Cu0L]^+,5"[[Q7

 +K[A&}}Q/55JJ++(	, 223GS^2_  5"XXj!4
5s   C  D D
box_tensorlabelsc                    UbK  [        U[        5      (       a  U/n[        U5      UR                  S   :w  a  [        R                  S5        Sn[        XU4XgS.UD6n	U	R                  S   R                  R                  n
U R                  5       R                  XU5        U R                  5       R                  XUS9  g)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  rh   r  shapeloggerwarningr   r  r   r  r   r>   r   r  )r'   r~   r  r*  r=   r7   r  r+  r   r<   r  s              r)   add_image_with_boxes"SummaryWriter.add_image_with_boxes  s    6 &#&& 6{j..q11abZ[5@[SY[&}}Q/55JJ++(	, 223GS^2_r,   rL   c                     [        U[        5      (       a  U R                  U[        X$5      X5SS9  gU R                  U[        X$5      X5SS9  g)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
NCHWr  r  N)r  r!  r  r   )r'   r~   figurer=   rL   r7   s         r)   
add_figureSummaryWriter.add_figure,  sE    $ fd##NN3 >ciNjNN3 >chNir,   
vid_tensorfpsc                     [        XXFS9nUR                  S   R                  R                  nU R	                  5       R                  XsU5        U R                  5       R                  XUS9  g)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   r>   r   r  )	r'   r~   r7  r=   r8  r7   r  r<   r  s	            r)   	add_videoSummaryWriter.add_videoC  se    . F&}}Q/55JJ++(	, 223GS^2_r,   
snd_tensorsample_ratec                     U R                  5       R                  [        XUS9X55        U R                  5       R	                  X$XS9  g)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   r>   r   r   	log_audio)r'   r~   r<  r=   r=  r7   s         r)   	add_audioSummaryWriter.add_audio`  sD    ( 	++#{;[	T **:C*Zr,   text_stringc                     U R                  5       R                  [        X5      X45        U R                  5       R	                  X#5        g)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   r>   r   r   log_text)r'   r~   rB  r=   r7   s        r)   add_textSummaryWriter.add_textx  s<    $ 	++"K	; ))+Cr,   c                     U R                  5       R                  [        U5      5        U R                  5       R	                  U5        g)z`Add onnx graph to TensorBoard.

Args:
    onnx_model_file (string): The path to the onnx model.
N)r   rF   r   r   	log_asset)r'   onnx_model_files     r)   rF   SummaryWriter.add_onnx_graph  s7     	../OP **?;r,   c                     U R                  5       R                  [        U5      5        U R                  5       R	                  U5        g)zoAdd openvino graph to TensorBoard.

Args:
    xmlname (string): The path to the openvino model. (the xml file)
N)r   r   r   r   rH  )r'   xmlnames     r)   r    SummaryWriter.add_openvino_graph  s8     	223Fw3OP **73r,   c           	      X    SSK Jn  U R                  5       R                  U" XX4S95        g)a  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   )rE   )use_strict_traceN)&torch.utils.tensorboard._pytorch_graphrE   r   rB   )r'   modelinput_to_modelverboserO  rE   s         r)   rB   SummaryWriter.add_graph  s&    " 	A))%w*rsr,   c                    U nUR                  SSR                  [        S5      5      5      nUR                  SSR                  [        S5      5      5      nUR                  SSR                  [        S5      5      5      nU$ )N%z%{:02x}/\)replaceformatord)rawstrretvals     r)   _encodeSummaryWriter._encode  sk     Y%5%5c#h%?@Y%5%5c#h%?@i&6&6s4y&ABr,   mat	label_imgc                 d   SSK Jn  U" U5      nUc  Sn[        U5      R                  S5       SU R	                  U5       3n[
        R                  R                  U R                  5       R                  5       U5      n	 [
        R                  " U	5        Ub-  UR                  S   [        U5      :X  d   S5       e[        X)US	9  UbY  UR                  S   UR                  S   :X  d   S
5       eUR                  S   UR                  S   :X  d   S5       e[!        X95        UR"                  S:X  d   S5       e[%        X5        ['        X#U R                  5       R                  5       XU5        Ub  U S3OSn
U R)                  5       R+                  XX:S9  g! [         a    [        S5         GNf = f)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      rW  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   rh   zfillr^  r   r   r   r   r0   makedirsOSErrorr#  r-  r  r
   r	   ndimr   r   r   log_embedding)r'   r`  metadatara  r=   r~   rd  r   subdir	save_pathrg  s              r)   add_embeddingSummaryWriter.add_embedding  s   h 	#clK $**1-.aS0A/BCGGLL!6!6!8!C!C!EvN		_KK	" 99Q<3$  DCD X/J 99Q<9??1#55_7__5??1%);;u=uu;	-xx1}```} X**,7796PS	U-0_se5M$ ..si.m%  	_]_	_s   ?F F/.F/predictionsnum_thresholdsc                     SSK Jn  U" U5      U" U5      p2[        XX5U5      n	U R                  5       R	                  U	XG5        U R                  5       R                  XXTS9  g)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   r>   r   log_pr_data)
r'   r~   r+  rr  r=   rs  weightsr7   r   r<   s
             r)   add_pr_curveSummaryWriter.add_pr_curve  sa    J 	#%fow{/C3WM++	# 	 ,,S>,\r,   true_positive_countsfalse_positive_countstrue_negative_countsfalse_negative_counts	precisionrecallc                     U R                  5       R                  [        UUUUUUUU	U
5	      UU5        U R                  5       R	                  XUUUUUUU	U
S9
  g)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>`_
)	r6   ry  rz  r{  r|  r}  r~  rs  rv  N)r   r>   r   r   log_pr_raw_data)r'   r~   ry  rz  r{  r|  r}  r~  r=   rs  rv  r7   s               r)   add_pr_curve_rawSummaryWriter.add_pr_curve_rawC  s~    . 	++-.-."' " 	 	 00FZG\FZG\;D8>@N9@ 	1 	Br,   tagscategorytitlec                 b    X#SU/00nU R                  5       R                  [        U5      5        g)a  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   r>   r   r'   r  r  r  layouts        r)   !add_custom_scalars_multilinechart/SummaryWriter.add_custom_scalars_multilinechartp  s2     [$$789++N6,BCr,   c                     [        U5      S:X  d   eX#SU/00nU R                  5       R                  [        U5      5        g)a@  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'])
rf  MarginN)r  r   r>   r   r  s        r)   add_custom_scalars_marginchart,SummaryWriter.add_custom_scalars_marginchart  sB     4yA~~Xt$456++N6,BCr,   r  c                 T    U R                  5       R                  [        U5      5        g)a  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  s     r)   add_custom_scalars SummaryWriter.add_custom_scalars  s     * 	++N6,BCr,   verticescolorsfacesc           	          U R                  5       R                  [        XX4U5      Xg5        U R                  5       R	                  XX4XVU5        g)a  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   r>   r   r   log_mesh)r'   r~   r  r  r  config_dictr=   r7   s           r)   add_meshSummaryWriter.add_mesh  sI    N 	++D{,[]hs ))#*5H	Nr,   c                    U R                   c  gU R                   R                  5        H#  nUR                  5         UR                  5         M%     S=U l        U l         U R                  5       R                  5         SU l        g)zClose the current SummaryWriter. This call flushes the unfinished write operation.
Use context manager (with statement) whenever it's possible.
N)r   r   rI   rL   r   r   endr   r'   writers     r)   rL   SummaryWriter.close  sm     #&&--/FLLNLLN 0 /324+ $$&!r,   c                     U R                   c  gU R                   R                  5        H  nUR                  5         M     g)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   rI   r  s     r)   rI   SummaryWriter.flush  s5     #&&--/FLLN 0r,   c                     U $ r$   r3   r/   s    r)   	__enter__SummaryWriter.__enter__  s    r,   c                 $    U R                  5         g r$   )rL   )r'   exc_typeexc_valexc_tbs       r)   __exit__SummaryWriter.__exit__  s    

r,   rQ   c             #      #    U R                  5       R                  XS9   U v   SSS5        g! , (       d  f       g= f7f)a+  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)
rQ   N)r   rT   rS   s      r)   rT   SummaryWriter.use_metadata  s2      ""$11k1]J ^]]s   ?.	?
<?)r   r   rk   r   r   r   r   r   r   r   r   r(   r   r   rV   )NNr   r   )Nr  NN)NNr  )NNr3  )NNr  N)NTN)N   NNTCHW)NiD  N)NFT)NNNdefaultN)N   NN)r  untitled)NNNNN)3rW   rX   rY   rZ   r[   r   rh   rv   boolr   r*   r   r   r   r   r   r   numpy_compatibler   r   r   r  r  r  r(  r!  r0  r5  r:  r@  rE  rF   r   rB   staticmethodr^  rp  rw  r  r  r  r  r  rL   rI   r  r  r\   r]   rT   r^   r3   r,   r)   r   r      sK    %)%'(,')(+-/,0%),6+=]$SM]$ c]]$ !	]$
  }]$ !]$ &c]]$ $D>]$ c]]$ #4.]$~	N *" #')-.Oc5sE3)>#??@.O c5j).O 3-	.O
 "#.Oh *.(,*,13$Z$Z  '7 78$Z "#	$Z
 uo$Z #3-$Z "*#$ZT *.(,0Z0Z "#u*-0Z "#	0Z
 uo0Zd	 *.".(,'I'I %'I "#	'I
 3-'I uo'If *.(,@S@S "#@S uo@SL *.(,).8`8` )8` "#	8`
 uo8` "#8`| *.(,)/=`=` )=` "#	=`
 uo=` "#=`H *.(,).*.&`&` )&` )	&`
 "#&` uo&` "#&` T#Y'&`X *.$((,jj "#	j
 D>j uoj6 *./0(,)0`` )` "#	`
 %U
+,` uo` "#`B *.).(,[[ )[ "#	[
 "#[ uo[8 *.(,DD D "#	D
 uoD,	<	4  !t(   *.)- Qn!Qn (	Qn
 "#Qnp *.,/(,-]-] %-] *	-]
 "#-] %SM-] uo-]p *.,/(,+B+B #3+B $4	+B
 #3+B $4+B (+B %+B "#+B %SM+B uo+B` &#	Ds)D D 	D* &#	Ds)D D 	D&Dd39o-.D6 (,&*)-(,)N)N ')N %	)N
 $)N "#)N uo)NV" *.  r,   r   )9r[   ri   r\   r   loggingr   rt   typingr   r   r&  comet_utilsr   	embeddingr   r   r	   r
   event_file_writerr   
onnx_graphr   openvino_graphr   protor   r   proto.event_pb2r   r   r<   r   r   r   r   r   r   r   r   r   r   r   r   r   utilsr   	getLoggerrW   r.  ndarrayr  r$  TensorImportErrorr!   r`   r   r3   r,   r)   <module>r     s   .     	  "  $ D D . ' / ) .    #			8	$== 	||
" "Jd$ d$ND Da  		s   C CC