
    BVhJ                        d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dZ G d de      Z edg       G d de             Z y)z6Provides an API for generating Event protocol buffers.    N)	graph_pb2)summary_pb2)meta_graph_pb2)	event_pb2)context)
meta_graph)ops)gfile)
tf_logging)plugin_asset)EventFileWriter)EventFileWriterV2)	tf_exportpluginsc                   T    e Zd ZdZddZddZddZddZddZd Z	dd	Z
dd
Zd Zy)SummaryToEventTransformerzAbstractly implements the SummaryWriter API.

  This API basically implements a number of endpoints (add_summary,
  add_session_log, etc). The endpoints all generate an event protobuf, which is
  passed to the contained event_writer.
  Nc                    || _         i | _        ||j| j                  ||       t        |t        j
                        r|j                  d      n|}| j                  t        j                  |xs |             t               | _        y)al  Creates a `SummaryWriter` and an event file.

    On construction the summary writer creates a new event file in `logdir`.
    This event file will contain `Event` protocol buffers constructed when you
    call one of the following functions: `add_summary()`, `add_session_log()`,
    `add_event()`, or `add_graph()`.

    If you pass a `Graph` to the constructor it is added to
    the event file. (This is equivalent to calling `add_graph()` later).

    TensorBoard will pick the graph from the file and display it graphically so
    you can interactively explore the graph you built. You will usually pass
    the graph from the session in which you launched it:

    ```python
    ...create a graph...
    # Launch the graph in a session.
    sess = tf.compat.v1.Session()
    # Create a summary writer, add the 'graph' to the event file.
    writer = tf.compat.v1.summary.FileWriter(<some-directory>, sess.graph)
    ```


    Args:
      event_writer: An EventWriter. Implements add_event and get_logdir.
      graph: A `Graph` object, such as `sess.graph`.
      graph_def: DEPRECATED: Use the `graph` argument instead.
    N)graph	graph_defT
add_shapesr   )event_writer_session_run_tags	add_graph
isinstancer	   Graphas_graph_defadd_meta_graphr   create_meta_graph_defset_seen_summary_tags)selfr   r   r   maybe_graph_as_defs        W/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/summary/writer/writer.py__init__z"SummaryToEventTransformer.__init__.   s    : %DDI1
nn5In6  *%; "..$.?AF 


*
*Y 6>+=?@ "eD    c                    t        |t              r't        j                         }|j	                  |       |}|j
                  D ]^  }|j                  s|j                  | j                  v r|j                  d       :| j                  j                  |j                         ` t        j                  |      }| j                  ||       y)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.

    You can pass the result of evaluating any summary op, using
    `tf.Session.run` or
    `tf.Tensor.eval`, to this
    function. Alternatively, you can pass a `tf.compat.v1.Summary` protocol
    buffer that you populate with your own data. The latter is
    commonly done to report evaluation results in event files.

    Args:
      summary: A `Summary` protocol buffer, optionally serialized as a string.
      global_step: Number. Optional global step value to record with the
        summary.
    metadata)summaryN)r   bytesr   SummaryParseFromStringvaluer)   tagr"   
ClearFieldaddr   Event
_add_event)r#   r*   global_stepsummr.   events         r%   add_summaryz%SummaryToEventTransformer.add_summarya   s    $ '5!  "d
7#g
  -^^	d--	-$
 !!%)),- OOG,EOOE;'r'   c                 T    t        j                  |      }| j                  ||       y)a@  Adds a `SessionLog` protocol buffer to the event file.

    This method wraps the provided session in an `Event` protocol buffer
    and adds it to the event file.

    Args:
      session_log: A `SessionLog` protocol buffer.
      global_step: Number. Optional global step value to record with the
        summary.
    )session_logN)r   r2   r3   )r#   r9   r4   r6   s       r%   add_session_logz)SummaryToEventTransformer.add_session_log   s      OO4EOOE;'r'   c                 t    |j                         }t        j                  |      }| j                  ||       y )Nr   )SerializeToStringr   r2   r3   )r#   r   r4   graph_bytesr6   s        r%   _add_graph_defz(SummaryToEventTransformer._add_graph_def   s,    --/KOOk2EOOE;'r'   c                 @   ||t        d      t        |t        j                        st        |t        j                        rUt        |t        j                        st	        j
                  d       |}|j                  d      }| j                  |       ntt        |t        j                        st        |t        j                        r5t	        j
                  d       t        |t        j                        r|}n|}nt        d      | j                  ||       y)a  Adds a `Graph` to the event file.

    The graph described by the protocol buffer will be displayed by
    TensorBoard. Most users pass a graph in the constructor instead.

    Args:
      graph: A `Graph` object, such as `sess.graph`.
      global_step: Number. Optional global step counter to record with the
        graph.
      graph_def: DEPRECATED. Use the `graph` parameter instead.

    Raises:
      ValueError: If both graph and graph_def are passed to the method.
    Nz@Please pass only graph, or graph_def (deprecated), but not both.z\When passing a `Graph` object, please use the `graph` named argument instead of `graph_def`.Tr   zmPassing a `GraphDef` to the SummaryWriter is deprecated. Pass a `Graph` object instead, such as `sess.graph`.zLThe passed graph must be an instance of `Graph` or the deprecated `GraphDef`)
ValueErrorr   r	   r   loggingwarningr   _write_plugin_assetsr   GraphDef	TypeErrorr>   )r#   r   r4   r   true_graph_defs        r%   r   z#SummaryToEventTransformer.add_graph   s      Y2 ' ( ( %#z)SYY'G
 syy) B 	C ))T):n
&
UI..
/
Y	 2 2
3oo N O
 
E9--	."  5 6 6 	4r'   c                    t        j                  |      }| j                  j                         }|D ]  }|j                  }t
        j                  j                  |t        |      }t        j                  |       |j                         }|j                         D ]U  \  }}	t
        j                  j                  ||      }
t        j                  |
d      5 }|j                  |	       d d d        W  y # 1 sw Y   dxY w)Nw)r   get_all_plugin_assetsr   
get_logdirplugin_nameospathjoin_PLUGINS_DIRr
   MakeDirsassetsitemsOpenwrite)r#   r   plugin_assetslogdirasset_containerrK   
plugin_dirrQ   
asset_namecontent
asset_pathfs               r%   rC   z.SummaryToEventTransformer._write_plugin_assets   s     66u=M))+F( #//k77<<kBjnnZ %%'f#)<<> 
:wWW\\*j9
ZZ
C( 	A
'''
	 		 	s   C66C?c                     t        |t        j                        st        dt	        |      z        |j                         }t        j                  |      }| j                  ||       y)a  Adds a `MetaGraphDef` to the event file.

    The `MetaGraphDef` allows running the given graph via
    `saver.import_meta_graph()`.

    Args:
      meta_graph_def: A `MetaGraphDef` object, often as returned by
        `saver.export_meta_graph()`.
      global_step: Number. Optional global step counter to record with the
        graph.

    Raises:
      TypeError: If both `meta_graph_def` is not an instance of `MetaGraphDef`.
    z6meta_graph_def must be type MetaGraphDef, saw type: %s)meta_graph_defN)	r   r   MetaGraphDefrE   typer<   r   r2   r3   )r#   r^   r4   meta_graph_bytesr6   s        r%   r   z(SummaryToEventTransformer.add_meta_graph   s]     nn&A&ABN>*+ , ,%779OO+;<EOOE;'r'   c                    || j                   v rt        d      d| j                   |<   t        j                         }||_        |j                         |_        t        j                  |      }| j                  ||       y)af  Adds a metadata information for a single session.run() call.

    Args:
      run_metadata: A `RunMetadata` protobuf object.
      tag: The tag name for this metadata.
      global_step: Number. Optional global step counter to record with the
        StepStats.

    Raises:
      ValueError: If the provided tag was already used for this type of event.
    z5The provided tag was already used for this event typeT)tagged_run_metadataN)	r   r@   r   TaggedRunMetadatar/   r<   run_metadatar2   r3   )r#   re   r/   r4   tagged_metadatar6   s         r%   add_run_metadataz*SummaryToEventTransformer.add_run_metadata   ss     d$$$NOO"&D3113OO $0#A#A#CO OO@EOOE;'r'   c                     t        j                          |_        |t        |      |_        | j                  j                  |       y N)time	wall_timeintstepr   	add_event)r#   r6   rm   s      r%   r3   z$SummaryToEventTransformer._add_event  s4    iikEOt9ej&r'   )NNri   )__name__
__module____qualname____doc__r&   r7   r:   r>   r   rC   r   rg   r3    r'   r%   r   r   &   s7    1$f)(V((
35j(,(0'r'   r   zsummary.FileWriter)v1c                   j     e Zd ZdZ	 	 	 	 	 	 d fd	Zd Zd Zd Zd Z fdZ	d Z
d	 Zd
 Zd Z xZS )
FileWritera  Writes `Summary` protocol buffers to event files.

  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.

  When constructed with a `tf.compat.v1.Session` parameter, a `FileWriter`
  instead forms a compatibility layer over new graph-based summaries
  to facilitate the use of new summary writing with
  pre-existing code that expects a `FileWriter` instance.

  This class is not thread-safe.

  @compatibility(TF2)
  This API is not compatible with eager execution or `tf.function`. To migrate
  to TF2, please use `tf.summary.create_file_writer` instead for summary
  management. To specify the summary step, you can manage the context with
  `tf.summary.SummaryWriter`, which is returned by
  `tf.summary.create_file_writer()`. Or, you can also use the `step` argument
  of summary functions such as `tf.summary.histogram`.
  See the usage example shown below.

  For a comprehensive `tf.summary` migration guide, please follow
  [Migrating tf.summary usage to
  TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x).

  #### How to Map Arguments

  | TF1 Arg Name        | TF2 Arg Name    | Note                              |
  | :---------------- | :---------------- | :-------------------------------- |
  | `logdir`          | `logdir`          | -                                 |
  | `graph`           | Not supported     | -                                 |
  | `max_queue`       | `max_queue`       | -                                 |
  | `flush_secs`      | `flush_millis`    | The unit of time is changed       |
  :                     :                 : from seconds to milliseconds.     :
  | `graph_def`       | Not supported     | -                                 |
  | `filename_suffix` | `filename_suffix` | -                                 |
  | `name`            | `name`            | -                                 |

  #### TF1 & TF2 Usage Example

  TF1:

  ```python
  dist = tf.compat.v1.placeholder(tf.float32, [100])
  tf.compat.v1.summary.histogram(name="distribution", values=dist)
  writer = tf.compat.v1.summary.FileWriter("/tmp/tf1_summary_example")
  summaries = tf.compat.v1.summary.merge_all()

  sess = tf.compat.v1.Session()
  for step in range(100):
    mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100])
    summ = sess.run(summaries, feed_dict={dist: mean_moving_normal})
    writer.add_summary(summ, global_step=step)
  ```

  TF2:

  ```python
  writer = tf.summary.create_file_writer("/tmp/tf2_summary_example")
  for step in range(100):
    mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100])
    with writer.as_default(step=step):
      tf.summary.histogram(name='distribution', data=mean_moving_normal)
  ```

  @end_compatibility
  c                     t        j                         rt        d      |t        |||||      }nt	        ||||      }d| _        t        t        | #  |||       y)a  Creates a `FileWriter`, optionally shared within the given session.

    Typically, constructing a file writer creates a new event file in `logdir`.
    This event file will contain `Event` protocol buffers constructed when you
    call one of the following functions: `add_summary()`, `add_session_log()`,
    `add_event()`, or `add_graph()`.

    If you pass a `Graph` to the constructor it is added to
    the event file. (This is equivalent to calling `add_graph()` later).

    TensorBoard will pick the graph from the file and display it graphically so
    you can interactively explore the graph you built. You will usually pass
    the graph from the session in which you launched it:

    ```python
    ...create a graph...
    # Launch the graph in a session.
    sess = tf.compat.v1.Session()
    # Create a summary writer, add the 'graph' to the event file.
    writer = tf.compat.v1.summary.FileWriter(<some-directory>, sess.graph)
    ```

    The `session` argument to the constructor makes the returned `FileWriter` a
    compatibility layer over new graph-based summaries (`tf.summary`).
    Crucially, this means the underlying writer resource and events file will
    be shared with any other `FileWriter` using the same `session` and `logdir`.
    In either case, ops will be added to `session.graph` to control the
    underlying file writer resource.

    Args:
      logdir: A string. Directory where event file will be written.
      graph: A `Graph` object, such as `sess.graph`.
      max_queue: Integer. Size of the queue for pending events and summaries.
      flush_secs: Number. How often, in seconds, to flush the
        pending events and summaries to disk.
      graph_def: DEPRECATED: Use the `graph` argument instead.
      filename_suffix: A string. Every event file's name is suffixed with
        `suffix`.
      session: A `tf.compat.v1.Session` object. See details above.

    Raises:
      RuntimeError: If called with eager execution enabled.

    @compatibility(eager)
      `v1.summary.FileWriter` is not compatible with eager execution.
      To write TensorBoard summaries under eager execution,
      use `tf.summary.create_file_writer` or
      a `with v1.Graph().as_default():` context.
    @end_compatibility
    zv1.summary.FileWriter is not compatible with eager execution. Use `tf.summary.create_file_writer`,or a `with v1.Graph().as_default():` contextNF)	r   executing_eagerlyRuntimeErrorr   r   _closedsuperrv   r&   )
r#   rV   r   	max_queue
flush_secsr   filename_suffixsessionr   	__class__s
            r%   r&   zFileWriter.__init___  ss    t   "9: : &
69j/Cl %VY
%46l DL	*d$\5)Dr'   c                     | S )"Make usable with "with" statement.rs   r#   s    r%   	__enter__zFileWriter.__enter__  s    Kr'   c                 $    | j                          y)r   N)close)r#   unused_typeunused_valueunused_tracebacks       r%   __exit__zFileWriter.__exit__  s    JJLr'   c                 6    | j                   j                         S )z7Returns the directory where event file will be written.)r   rJ   r   s    r%   rJ   zFileWriter.get_logdir  s    ''))r'   c                 H    | j                   rt        j                  d       y y )NzqAttempting to use a closed FileWriter. The operation will be a noop unless the FileWriter is explicitly reopened.)rz   warningswarnr   s    r%   _warn_if_event_writer_is_closedz*FileWriter._warn_if_event_writer_is_closed  s    ||mm . / r'   c                 N    | j                          t        t        |   ||       y ri   )r   r{   rv   r3   )r#   r6   rm   r   s      r%   r3   zFileWriter._add_event  s     ((*	*d&ud3r'   c                 Z    | j                          | j                  j                  |       y)zYAdds an event to the event file.

    Args:
      event: An `Event` protocol buffer.
    N)r   r   rn   )r#   r6   s     r%   rn   zFileWriter.add_event  s$     	((*&r'   c                 X    | j                          | j                  j                          y)z~Flushes the event file to disk.

    Call this method to make sure that all pending events have been written to
    disk.
    N)r   r   flushr   s    r%   r   zFileWriter.flush  s"     	((*r'   c                 F    | j                   j                          d| _        y)z~Flushes the event file to disk and close the file.

    Call this method when you do not need the summary writer anymore.
    TN)r   r   rz   r   s    r%   r   zFileWriter.close  s    
 	DLr'   c                 F    | j                   j                          d| _        y)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.
    FN)r   reopenrz   r   s    r%   r   zFileWriter.reopen  s     	DLr'   )N
   x   NNN)ro   rp   rq   rr   r&   r   r   rJ   r   r3   rn   r   r   r   __classcell__)r   s   @r%   rv   rv     sS    ER #GER*/4'		r'   rv   )!rr   os.pathrL   rj   r   tensorflow.core.frameworkr   r   tensorflow.core.protobufr   tensorflow.core.utilr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r	   tensorflow.python.platformr
   r   rA   tensorflow.python.summaryr   2tensorflow.python.summary.writer.event_file_writerr   5tensorflow.python.summary.writer.event_file_writer_v2r    tensorflow.python.util.tf_exportr   rO   objectr   rv   rs   r'   r%   <module>r      sv    =    / 1 3 * + 2 + , < 2 N S 6m' m'` #$%L* L &Lr'   