
    BVhAM                     8   d 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Z eddg       G d d             Z eddg       ej*                  de      ej,                  j.                  fd              Z eddg       ej*                  de      ddddej,                  j.                  fd              Z ej4                  ej,                  j.                  ej6                  ej8                  ej:                         y)z+Create threads to run multiple enqueue ops.    N)queue_runner_pb2)session)context)errors)ops)
tf_logging)deprecation)	tf_exportz7To construct input pipelines, use the `tf.data` module.ztrain.queue_runner.QueueRunnerztrain.QueueRunner)v1c                       e Zd ZdZ ej
                  de      	 	 	 dd       Z	 	 ddZddZ	e
d        Ze
d        Ze
d        Ze
d	        Ze
d
        Ze
d        Ze
d        ZddZd ZddZddZedd       Zy)QueueRunnera  Holds a list of enqueue operations for a queue, each to be run in a thread.

  Queues are a convenient TensorFlow mechanism to compute tensors
  asynchronously using multiple threads. For example in the canonical 'Input
  Reader' setup one set of threads generates filenames in a queue; a second set
  of threads read records from the files, processes them, and enqueues tensors
  on a second queue; a third set of threads dequeues these input records to
  construct batches and runs them through training operations.

  There are several delicate issues when running multiple threads that way:
  closing the queues in sequence as the input is exhausted, correctly catching
  and reporting exceptions, etc.

  The `QueueRunner`, combined with the `Coordinator`, helps handle these issues.

  @compatibility(TF2)
  QueueRunners are not compatible with eager execution. Instead, please
  use [tf.data](https://www.tensorflow.org/guide/data) to get data into your
  model.
  @end_compatibility
  Nc                 *   t        j                         rt        d      |r#|s|rt        d      | j	                  ||       n| j                  |||||       t        j                         | _        t        j                         | _        g | _        y)a  Create a QueueRunner.

    On construction the `QueueRunner` adds an op to close the queue.  That op
    will be run if the enqueue ops raise exceptions.

    When you later call the `create_threads()` method, the `QueueRunner` will
    create one thread for each op in `enqueue_ops`.  Each thread will run its
    enqueue op in parallel with the other threads.  The enqueue ops do not have
    to all be the same op, but it is expected that they all enqueue tensors in
    `queue`.

    Args:
      queue: A `Queue`.
      enqueue_ops: List of enqueue ops to run in threads later.
      close_op: Op to close the queue. Pending enqueue ops are preserved.
      cancel_op: Op to close the queue and cancel pending enqueue ops.
      queue_closed_exception_types: Optional tuple of Exception types that
        indicate that the queue has been closed when raised during an enqueue
        operation.  Defaults to `(tf.errors.OutOfRangeError,)`.  Another common
        case includes `(tf.errors.OutOfRangeError, tf.errors.CancelledError)`,
        when some of the enqueue ops may dequeue from other Queues.
      queue_runner_def: Optional `QueueRunnerDef` protocol buffer. If specified,
        recreates the QueueRunner from its contents. `queue_runner_def` and the
        other arguments are mutually exclusive.
      import_scope: Optional `string`. Name scope to add. Only used when
        initializing from protocol buffer.

    Raises:
      ValueError: If both `queue_runner_def` and `queue` are both specified.
      ValueError: If `queue` or `enqueue_ops` are not provided when not
        restoring from `queue_runner_def`.
      RuntimeError: If eager execution is enabled.
    zxQueueRunners are not supported when eager execution is enabled. Instead, please use tf.data to get data into your model.z2queue_runner_def and queue are mutually exclusive.)import_scope)queueenqueue_opsclose_op	cancel_opqueue_closed_exception_typesN)r   executing_eagerlyRuntimeError
ValueError_init_from_proto_init_from_args	threadingLock_lockweakrefWeakKeyDictionary_runs_per_session_exceptions_raised)selfr   r   r   r   r   queue_runner_defr   s           \/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/queue_runner_impl.py__init__zQueueRunner.__init__9   s    J   "EF F 	+MNN
,)5  7 ;y'C  E
 !DJ %668D D    c                    |r|st        d      || _        || _        || _        || _        |2t        |t              r|rt        d |D              st        d|z        || _	        | j                  | j                  j                         | _        | j                  !| j                  j                  d      | _        | j                  st        j                  f| _	        yt        | j                        | _	        y)a  Create a QueueRunner from arguments.

    Args:
      queue: A `Queue`.
      enqueue_ops: List of enqueue ops to run in threads later.
      close_op: Op to close the queue. Pending enqueue ops are preserved.
      cancel_op: Op to close the queue and cancel pending enqueue ops.
      queue_closed_exception_types: Tuple of exception types, which indicate
        the queue has been safely closed.

    Raises:
      ValueError: If `queue` or `enqueue_ops` are not provided when not
        restoring from `queue_runner_def`.
      TypeError: If `queue_closed_exception_types` is provided, but is not
        a non-empty tuple of error types (subclasses of `tf.errors.OpError`).
    z#Must provide queue and enqueue_ops.Nc              3   P   K   | ]  }t        |t        j                           y wN)
issubclassr   OpError).0ts     r#   	<genexpr>z.QueueRunner._init_from_args.<locals>.<genexpr>   s#      <  6>>2 <s   $&z[queue_closed_exception_types, when provided, must be a tuple of tf.error types, but saw: %sT)cancel_pending_enqueues)r   _queue_enqueue_ops	_close_op
_cancel_op
isinstancetupleall	TypeError_queue_closed_exception_typescloser   OutOfRangeError)r!   r   r   r   r   r   s         r#   r   zQueueRunner._init_from_argsu   s    $ <==DK#DDNDO#/5u=- <:< <=*+, 	, *FD& ~~{{((*dn ))$)Gdo--,2,B,B+Dd(+0

,
,,.d(r%   c           	         t        |t        j                        sJ t        j                         }|j                  t        j                  |j                  |            | _        |j                  D cg c]'  }|j                  t        j                  ||            ) c}| _
        |j                  t        j                  |j                  |            | _        |j                  t        j                  |j                  |            | _        t        d |j                   D              | _        | j"                  st$        j&                  f| _        yyc c}w )zCreate a QueueRunner from `QueueRunnerDef`.

    Args:
      queue_runner_def: Optional `QueueRunnerDef` protocol buffer.
      import_scope: Optional `string`. Name scope to add.
    c              3   F   K   | ]  }t        j                  |        y wr(   )r   exception_type_from_error_code)r+   codes     r#   r-   z/QueueRunner._init_from_proto.<locals>.<genexpr>   s%      /C 	--d3/Cs   !N)r3   r   QueueRunnerDefr   get_default_graphas_graph_elementprepend_name_scope
queue_namer/   enqueue_op_namer0   close_op_namer1   cancel_op_namer2   r4   r   r7   r   r9   )r!   r"   r   gops        r#   r   zQueueRunner._init_from_proto   s4    &(8(G(GHHHA$$/::LIKDK $4#C#CE ++r<02 ED ''(>(>&&)6 7DN(()?)?''*7 8DO). /C$AA/C *CD&
 --,2,B,B+Dd( .Es   3,Ec                     | j                   S r(   )r/   r!   s    r#   r   zQueueRunner.queue   s    ;;r%   c                     | j                   S r(   )r0   rI   s    r#   r   zQueueRunner.enqueue_ops   s    r%   c                     | j                   S r(   )r1   rI   s    r#   r   zQueueRunner.close_op   s    >>r%   c                     | j                   S r(   )r2   rI   s    r#   r   zQueueRunner.cancel_op   s    ??r%   c                     | j                   S r(   )r7   rI   s    r#   r   z(QueueRunner.queue_closed_exception_types   s    ---r%   c                     | j                   S )a  Exceptions raised but not handled by the `QueueRunner` threads.

    Exceptions raised in queue runner threads are handled in one of two ways
    depending on whether or not a `Coordinator` was passed to
    `create_threads()`:

    * With a `Coordinator`, exceptions are reported to the coordinator and
      forgotten by the `QueueRunner`.
    * Without a `Coordinator`, exceptions are captured by the `QueueRunner` and
      made available in this `exceptions_raised` property.

    Returns:
      A list of Python `Exception` objects.  The list is empty if no exception
      was captured.  (No exceptions are captured when using a Coordinator.)
    )r    rI   s    r#   exceptions_raisedzQueueRunner.exceptions_raised   s    " """r%   c                 .    | j                   j                  S )z(The string name of the underlying Queue.)r/   namerI   s    r#   rQ   zQueueRunner.name   s     ;;r%   c           
      R   d}	 |j                  |      }	 |r|j                         rn		  |        	 |s-| j                  5  | j                  |xx   dz  cc<   ddd       yy# | j                  $ r | j                  5  | j                  |xx   dz  cc<   d}| j                  |   dk(  rS	 |j                  | j                         n6# t        $ r*}t        j                  ddt        |             Y d}~nd}~ww xY w	 ddd       Y |s9| j                  5  | j                  |xx   dz  cc<   ddd       y# 1 sw Y   yxY wy# 1 sw Y   nxY wY !w xY w# t        $ r{}|r|j                  |       n\t        j                  dt        |             | j                  5  | j                  j                  |       ddd        # 1 sw Y    xY wY d}~d}~ww xY w# 1 sw Y   yxY w# |s9| j                  5  | j                  |xx   dz  cc<   ddd       w # 1 sw Y   w xY ww xY w)zExecute the enqueue op in a loop, close the queue in case of error.

    Args:
      sess: A Session.
      enqueue_op: The Operation to run.
      coord: Optional Coordinator object for reporting errors and checking
        for stop conditions.
    FT   r   Ignored exception: %sNzException in QueueRunner: %s)make_callableshould_stopr7   r   r   runr1   	Exceptionloggingvlogstrrequest_stoperrorr    append)r!   sess
enqueue_opcoorddecrementedenqueue_callablees          r#   _runzQueueRunner._run   s    K", ++J7U&&(
	

	 
4 ZZ 	,

 
 
&!
+
&	, 	, / 11 	zz 	""4(A-(K%%d+q0A( AQ 7Q@@A 	 	* ZZ 	,

 
 
&!
+
&	, 	, 	, +	 	 		  	14c!f=ZZ 	,

!
!
(
(
+	,	, 		, 	, ZZ 	,

 
 
&!
+
&	, 	, 	, s   %E A# E G) G#E>,E+CE	C: C50E5C::E>EE D66D?E	EE EE 	G?GG:	GG	GG) GG) G&)H&8H	H&H"H&c                     |j                          	 |j                  |       y# t        $ r*}t        j                  ddt        |             Y d}~yd}~ww xY w)zClose the queue when the Coordinator requests stop.

    Args:
      sess: A Session.
      cancel_op: The Operation to run.
      coord: Coordinator.
    rS   rT   N)wait_for_stoprW   rX   rY   rZ   r[   )r!   r_   r   ra   rd   s        r#   _close_on_stopzQueueRunner._close_on_stop  sI     
7
hhy 7ll1-s1v667s   $ 	A AAc           	         | j                   5  	 | j                  |   dkD  rg cddd       S 	 t        | j                        | j                  |<   g | _        ddd       g }| j                  D ]\  }dj                  | j                  |j                        }|j                  t        j                  | j                  |||f|             ^ |rYdj                  | j                        }|j                  t        j                  | j                  || j                  |f|             |D ]1  }|r|j                  |       |rd|_        |s"|j!                          3 |S # t        $ r Y =w xY w# 1 sw Y   xY w)a  Create threads to run the enqueue ops for the given session.

    This method requires a session in which the graph was launched.  It creates
    a list of threads, optionally starting them.  There is one thread for each
    op passed in `enqueue_ops`.

    The `coord` argument is an optional coordinator that the threads will use
    to terminate together and report exceptions.  If a coordinator is given,
    this method starts an additional thread to close the queue when the
    coordinator requests a stop.

    If previously created threads for the given session are still running, no
    new threads will be created.

    Args:
      sess: A `Session`.
      coord: Optional `Coordinator` object for reporting errors and checking
        stop conditions.
      daemon: Boolean.  If `True` make the threads daemon threads.
      start: Boolean.  If `True` starts the threads.  If `False` the
        caller must call the `start()` method of the returned threads.

    Returns:
      A list of threads.
    r   NzQueueRunnerThread-{}-{})targetargsrQ   z"QueueRunnerThread-{}-close_on_stopT)r   r   KeyErrorlenr0   r    formatrQ   r^   r   Threadre   rh   r2   register_threaddaemonstart)	r!   r_   ra   rq   rr   ret_threadsrG   rQ   r,   s	            r#   create_threadszQueueRunner.create_threads*  sr   4 
 	#!!$'!+		# 	#+ &)):):%;dT" "d	# K 6&--diiAd))04b%/@/35 66
 188Cd))1D1D04doou/M/35 6  	a 				 1  	# 	#s-   E.E*E.	E+'E.*E++E..E8c                    |&| j                   j                  j                  |      r3t        j                         }t        j                  | j                   j                  |      |_        | j                  D ];  }|j                  j                  t        j                  |j                  |             = t        j                  | j                  j                  |      |_        t        j                  | j                  j                  |      |_        |j                  j!                  | j"                  D cg c]  }t%        j&                  |       c}       |S yc c}w )a  Converts this `QueueRunner` to a `QueueRunnerDef` protocol buffer.

    Args:
      export_scope: Optional `string`. Name scope to remove.

    Returns:
      A `QueueRunnerDef` protocol buffer, or `None` if the `Variable` is not in
      the specified name scope.
    N)r   rQ   
startswithr   r>   r   strip_name_scoperB   r   rC   r^   r   rD   r   rE   r   extendr7   r   error_code_from_exception_type)r!   export_scoper"   r`   clss        r#   to_protozQueueRunner.to_protoc  s#    	

""<0)88:$'$8$8
**//<%)!(( A*((//  ,?	AA (+';';
--

l(,$(+(<(<
..

|)-%33::77<9 
/
/
4<9 : <9s   7Ec                     t        | |      S )z?Returns a `QueueRunner` object created from `queue_runner_def`.r"   r   )r   r~   s     r#   
from_protozQueueRunner.from_proto  s     (8$02 2r%   )NNNNNNN)NNNNNr(   )NFF)__name__
__module____qualname____doc__r	   
deprecated_DEPRECATION_INSTRUCTIONr$   r   r   propertyr   r   r   r   r   rO   rQ   re   rh   rt   r|   staticmethodr    r%   r#   r   r   !   s   , ;$ 89<@<@379! :9!v DHCG..`E4         . . # #$  
,,\7 7r: 2 2r%   r   z#train.queue_runner.add_queue_runnerztrain.add_queue_runnerc                 0    t        j                  ||        y)a  Adds a `QueueRunner` to a collection in the graph.

  When building a complex model that uses many queues it is often difficult to
  gather all the queue runners that need to be run.  This convenience function
  allows you to add a queue runner to a well known collection in the graph.

  The companion method `start_queue_runners()` can be used to start threads for
  all the collected queue runners.

  @compatibility(TF2)
  QueueRunners are not compatible with eager execution. Instead, please
  use [tf.data](https://www.tensorflow.org/guide/data) to get data into your
  model.
  @end_compatibility

  Args:
    qr: A `QueueRunner`.
    collection: A `GraphKey` specifying the graph collection to add
      the queue runner to.  Defaults to `GraphKeys.QUEUE_RUNNERS`.
  N)r   add_to_collection)qr
collections     r#   add_queue_runnerr     s    . 
B'r%   z&train.queue_runner.start_queue_runnersztrain.start_queue_runnersTc           
      t   t        j                         rt        d      | !t        j                         } | st        d      t        | t        j                        s>| j                  j                  dv rg S t        dj                  | j                              t        j                  |      }|st        j                  d       | j                   j#                         5  g }t        j                  |      D ]&  }|j%                  |j'                  | |||             ( 	 ddd       |S # 1 sw Y   S xY w)a  Starts all queue runners collected in the graph.

  This is a companion method to `add_queue_runner()`.  It just starts
  threads for all queue runners collected in the graph.  It returns
  the list of all threads.

  @compatibility(TF2)
  QueueRunners are not compatible with eager execution. Instead, please
  use [tf.data](https://www.tensorflow.org/guide/data) to get data into your
  model.
  @end_compatibility

  Args:
    sess: `Session` used to run the queue ops.  Defaults to the
      default session.
    coord: Optional `Coordinator` for coordinating the started threads.
    daemon: Whether the threads should be marked as `daemons`, meaning
      they don't block program exit.
    start: Set to `False` to only create the threads, not start them.
    collection: A `GraphKey` specifying the graph collection to
      get the queue runners from.  Defaults to `GraphKeys.QUEUE_RUNNERS`.

  Raises:
    ValueError: if `sess` is None and there isn't any default session.
    TypeError: if `sess` is not a `tf.compat.v1.Session` object.

  Returns:
    A list of threads.

  Raises:
    RuntimeError: If called with eager execution enabled.
    ValueError: If called without a default `tf.compat.v1.Session` registered.
  z/Queues are not compatible with eager execution.NzCannot start queue runners: No default session is registered. Use `with sess.as_default()` or pass an explicit session to tf.start_queue_runners(sess=sess))MonitoredSessionSingularMonitoredSessionz3sess must be a `tf.Session` object. Given class: {}z`tf.train.start_queue_runners()` was called when no queue runners were defined. You can safely remove the call to this deprecated function.)ra   rq   rr   )r   r   r   r   get_default_sessionr   r3   r   SessionInterface	__class__r   r6   rn   get_collectionrY   warninggraph
as_defaultrx   rt   )r_   ra   rq   rr   r   queue_runnersthreadsr   s           r#   start_queue_runnersr     s2   L  
H
II	\""$D O P P 
D'22	3~~ #8 8i
 &&,fT^^&<> > $$Z0-	OO	
 zz 5G  , 5nnR&&t5-2 ' 4 555
 
.5
 
.s   !AD--D7)
proto_typer|   r   )r   r   r   tensorflow.core.protobufr   tensorflow.python.clientr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.platformr   rY   tensorflow.python.utilr	    tensorflow.python.util.tf_exportr
   r   r   r   	GraphKeysQUEUE_RUNNERSr   r   register_proto_functionr>   r|   r   r   r%   r#   <module>r      s0    2   5 , + . + < . 6 >  /1DEFb2 b2 Gb2J 46NOP67$'MM$?$? ( 8 Q(0 7*, -67!d$#&==#>#>@ 8-@F   CMM77'7'F'F%0%9%9'2'='=?r%   