
    0h(                        d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlmZ ddlmZ ddlZddlmc 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& 	 d3dZ'd Z)d Z*d Z+d Z,d Z-d4dZ. e$d      	 	 	 	 	 	 	 	 	 	 d5d       Z/d Z0d6dZ1d7dZ2d8dZ3 G d d      Z4d Z5 e$d       G d d             Z6d Z7i a8da9 ejt                         Z;da< e=       Z>da? ej                         ZAd  ZBd! ZCd" ZDd# ZEd$ ZF e$d%       G d& d'             ZG e$d(       G d) d*eG             ZHd3d+ZId, ZJ e$d-       G d. d/eG             ZK e$d0d1      	 	 	 	 	 d9d2       ZLy):z(Utilities for file download and caching.    N)abstractmethod)closing)urlsplit)io_utils)
tf_inspect)Progbar)keras_export)urlopenc                     dd}t        | |      }t        |d      5 } |||      D ]  }|j                  |        	 ddd       y# 1 sw Y   yxY w)a  Replacement for `urlretrieve` for Python 2.

        Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy
        `urllib` module, known to have issues with proxy management.

        Args:
            url: url to retrieve.
            filename: where to store the retrieved data locally.
            reporthook: a hook function that will be called once on
              establishment of the network connection and once after each block
              read thereafter. The hook will be passed three arguments; a count
              of blocks transferred so far, a block size in bytes, and the total
              size of the file.
            data: `data` argument passed to `urlopen`.
        Nc              3      K   | j                         j                  d      }d}|t        |j                               }d}	 | j	                  |      }|dz  }|
 ||||       |r| ny +w)NzContent-Lengthr      )infogetintstripread)response
chunk_size
reporthookcontent_type
total_sizecountchunks          W/var/www/html/engine/venv/lib/python3.12/site-packages/tf_keras/src/utils/data_utils.py
chunk_readzurlretrieve.<locals>.chunk_readE   s|     #==?../?@LJ' !3!3!56
E j1
)uj*=K s   A+A-wb)r   )i    N)r
   openwrite)urlfilenamer   datar   r   fdr   s           r   urlretriever$   4   sW    "	  3%(D! 	 R#HD   	  	  	 s   !AAc                 $   t         t        t        t        t        t
        f}t        | t        j                  t        j                  f|z         ryt        j                  |       xs, t        | t              xs t        | t        j                        S )z*Check if `x` is a TF-Keras generator type.F)strlisttupledictset	frozenset
isinstancetfTensornpndarrayr   isgeneratorSequencetypingIterator)xbuiltin_iteratorss     r   is_generator_or_sequencer7   ^   sj    dE4i@!bii,/@@Aq! 	*a"	*a)    c                 z    t         j                  j                  t         j                  j                  |             S N)ospathrealpathabspath)r<   s    r   _resolve_pathr?   j   s$    77BGGOOD122r8   c                 r    t        t        j                  j                  ||             j	                  |      S r:   )r?   r;   r<   join
startswith)r<   base_dirs     r   _is_path_in_dirrD   n   s'    h56AA(KKr8   c                     t        t        j                  j                  |t        j                  j	                  | j
                                    }t        | j                  |      S )N)rC   )r?   r;   r<   rA   dirnamenamerD   linkname)r   basetips      r   _is_link_in_dirrK   r   s=    
T277??499+EF
GC4==377r8   c              #     K   t        d      }| D ]y  }d}t        |j                  |      rd}| n2|j                         s|j	                         rt        ||      rd}| |rWt        j                  d|j                   d       { y w)N.FTz2Skipping invalid path during archive extraction: 'z'.)r?   rD   rG   issymislnkrK   warningswarn)membersrC   finfo
valid_paths       r   _filter_safe_pathsrU   w   s     S!H 
5::x0JK[[]ekkmuh/!
MMJJ<r#s   A$B'&Bc                 (   |y|dk(  rddg}t        |t              r|g}t        j                  |       } t        j                  |      }|D ]  }|dk(  r t        j
                  }t        j                  }|dk(  r t        j                  }t        j                  } |       sV |       5 }	 t        j                  |       r|j                  |       n|j                  |t        |             ddd        y y# t        j                  t        t        f$ rk t        j                   j#                  |      rJt        j                   j%                  |      rt        j&                  |        t)        j*                  |        w xY w# 1 sw Y    yxY w)a_  Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.

    Args:
        file_path: Path to the archive file.
        path: Where to extract the archive file.
        archive_format: Archive format to try for extracting the file.
            Options are `'auto'`, `'tar'`, `'zip'`, and `None`.
            `'tar'` includes tar, tar.gz, and tar.bz files.
            The default 'auto' is `['tar', 'zip']`.
            `None` or an empty list will return no matches found.

    Returns:
        True if a match was found and an archive extraction was completed,
        False otherwise.
    NFautotarzip)rR   T)r,   r&   r   path_to_stringtarfiler   
is_tarfilezipfileZipFile
is_zipfile
extractallrU   TarErrorRuntimeErrorKeyboardInterruptr;   r<   existsisfileremoveshutilrmtree)	file_pathr<   archive_formatarchive_typeopen_fnis_match_fnarchives          r   _extract_archivero      si     .#&()''	2I""4(D& 5 llG!,,K5 ooG!,,Ky!# w)))4**40  ** *<W*E + " 56   ((,8IJ ww~~d+77>>$/IIdO  #MM$/" s    *F,AC;;B	FFF	zkeras.utils.get_fileFc
                    |t        d      |	=t        j                  j                  t        j                  j	                  d      d      }	|||}d}t        j                  j	                  |	      }
t        j
                  |
t        j                        s t        j                  j                  dd      }
t        j                  j                  |
|      }t        |       t        j                  |       } | sCt        j                  j                  t        |      j                        } | st        d| d      |rw| j                  d	      r@t        j                  |       } | j                  d
      j                  d
      } t!        |       } t        j                  j                  ||       }|d	z   }n t        j                  j                  ||       }d}t        j                  j#                  |      r/|/t%        |||      s!t        j&                  d| d| d       d}nd}|rzt        j&                  d|         G d d      }d}	 	 t)        || |              	 t        j                  j#                  |      r"| t%        |||      st        d| d| d      |r/t        j                  j#                        stC        ||d       |S |rtC        |||       |S # t*        j,                  j.                  $ r5}t1        |j3                  ||j4                  |j6                              d}~wt*        j,                  j8                  $ r5}t1        |j3                  ||j:                  |j<                              d}~ww xY w# t0        t>        f$ r6 t        j                  j#                  |      rt        j@                  |        w xY w)u
  Downloads a file from a URL if it not already in the cache.

    By default the file at the url `origin` is downloaded to the
    cache_dir `~/.keras`, placed in the cache_subdir `datasets`,
    and given the filename `fname`. The final location of a file
    `example.txt` would therefore be `~/.keras/datasets/example.txt`.

    Files in tar, tar.gz, tar.bz, and zip formats can also be extracted.
    Passing a hash will verify the file after download. The command line
    programs `shasum` and `sha256sum` can compute the hash.

    Example:

    ```python
    path_to_downloaded_file = tf.keras.utils.get_file(
        origin="https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz",
        extract=True,
    )
    ```

    Args:
        fname: Name of the file. If an absolute path `/path/to/file.txt` is
            specified the file will be saved at that location. If `None`, the
            name of the file at `origin` will be used.
        origin: Original URL of the file.
        untar: Deprecated in favor of `extract` argument.
            boolean, whether the file should be decompressed
        md5_hash: Deprecated in favor of `file_hash` argument.
            md5 hash of the file for verification
        file_hash: The expected hash string of the file after download.
            The sha256 and md5 hash algorithms are both supported.
        cache_subdir: Subdirectory under the TF-Keras cache dir where the file
            is saved. If an absolute path `/path/to/folder` is
            specified the file will be saved at that location.
        hash_algorithm: Select the hash algorithm to verify the file.
            options are `'md5'`, `'sha256'`, and `'auto'`.
            The default 'auto' detects the hash algorithm in use.
        extract: True tries extracting the file as an Archive, like tar or zip.
        archive_format: Archive format to try for extracting the file.
            Options are `'auto'`, `'tar'`, `'zip'`, and `None`.
            `'tar'` includes tar, tar.gz, and tar.bz files.
            The default `'auto'` corresponds to `['tar', 'zip']`.
            None or an empty list will return no matches found.
        cache_dir: Location to store cached files, when None it
            defaults to `~/.keras/`.

    Returns:
        Path to the downloaded file.

    ⚠️ **Warning on malicious downloads** ⚠️

    Downloading something from the Internet carries a risk.
    NEVER download a file/archive if you do not trust the source.
    We recommend that you specify the `file_hash` argument
    (if the hash of the source file is known) to make sure that the file you
    are getting is the one you expect.
    NzCPlease specify the "origin" argument (URL of the file to download).~z.kerasmd5z/tmpz5Can't parse the file name from the origin provided: 'z0'.Please specify the `fname` as the input param.z.tar.gz F)	algorithmzNA local file was found, but it seems to be incomplete or outdated because the z0 file hash does not match the original value of z! so we will re-download the data.TzDownloading data from c                       e Zd ZdZd Zd Zy)get_file.<locals>.DLProgbarz1Manage progress bar state for use in urlretrieve.c                      d | _         d| _        y NF)progbarfinishedselfs    r   __init__z$get_file.<locals>.DLProgbar.__init__D  s    # %r8   c                 X   | j                   s|dk(  rd }t        |      | _         ||z  }|| j                   j                  |       y ||k  r| j                   j                  |       y | j                  s7| j                   j                  | j                   j                         d| _        y y )Nr   T)ry   r   updaterz   target)r|   	block_num
block_sizer   currents        r   __call__z$get_file.<locals>.DLProgbar.__call__H  s    ||!R'%)
#*:#6DL#j0%LL''0+++G4!]]++DLL,?,?@(, +r8   N)__name__
__module____qualname____doc__r}   r    r8   r   	DLProgbarrv   A  s    C&-r8   r   z!URL fetch failure on {}: {} -- {}z+Incomplete or corrupted file detected. The z0 file hash does not match the provided value of rM   rX   )rj   )"
ValueErrorr;   r<   rA   
expanduseraccessW_OK_makedirs_exist_okr   rZ   basenamer   endswithpathlibPathwith_suffixr&   rd   validate_file	print_msgr$   urlliberror	HTTPError	ExceptionformatcodemsgURLErrorerrnoreasonrc   rf   ro   )fnameoriginuntarmd5_hash	file_hashcache_subdirhash_algorithmextractrj   	cache_dirdatadir_basedatadiruntar_fpathfpathdownloadr   	error_msges                     r   get_filer      sV   L ~
 	

 GGLL!3!3C!8(C		 1	77%%i0L99\277+ww||FH5ggll<6Gw##E*E  &!1!6!678 AA  >>)$LL'E %%b)55b9EJEggll7E2i'We,H	ww~~e  	^L""::H9I JF k "77  3F8<=	- 	-. 8	
	MFE9;7 77>>% Y%: 	^L )* +#A'  ww~~k*UGEB8L; <<)) I	 0 0 GHH<<(( M	 0 0!(( KLLM,- 	ww~~e$		% 	s1   K& &N0L33 N0NNN AOc                 2    t        j                  | d       y )NT)exist_ok)r;   makedirs)r   s    r   r   r   |  s    KK$'r8   c                     | dk(  rt        j                         S | dk(  r$|"t        |      dk(  rt        j                         S t        j                         S )z+Returns hash algorithm as hashlib function.sha256rW   @   )hashlibr   lenrr   )rt   r   s     r   _resolve_hasherr     sJ    H~~Fy4Y29M~~ ;;=r8   c                    t        |t              rt        |      }n|}t        | d      5 t	        fdd      D ]  }|j                  |        	 ddd       |j                         S # 1 sw Y   |j                         S xY w)a  Calculates a file sha256 or md5 hash.

    Example:

    ```python
    _hash_file('/path/to/file.zip')
    'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
    ```

    Args:
        fpath: Path to the file being validated.
        algorithm: Hash algorithm, one of `'auto'`, `'sha256'`, or `'md5'`.
            The default `'auto'` detects the hash algorithm in use.
        chunk_size: Bytes to read at a time, important for large files.

    Returns:
        The file hash.
    rbc                  &    j                         S r:   )r   )r   
fpath_files   r   <lambda>z_hash_file.<locals>.<lambda>  s    *//*"= r8   r8   N)r,   r&   r   r   iterr   	hexdigest)r   rt   r   hasherr   r   s     `  @r   
_hash_filer     s    & )S! +	eT	 !j=sC 	!EMM% 	!! 	! s   'A--Bc                 b    t        ||      }t        t        | ||            t        |      k(  ryy)a  Validates a file against a sha256 or md5 hash.

    Args:
        fpath: path to the file being validated
        file_hash:  The expected hash string of the file.
            The sha256 and md5 hash algorithms are both supported.
        algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
            The default 'auto' detects the hash algorithm in use.
        chunk_size: Bytes to read at a time, important for large files.

    Returns:
        Whether the file is valid
    TF)r   r&   r   )r   r   rt   r   r   s        r   r   r     s0     Y	2F
:eVZ01S^Cr8   c                   (    e Zd ZdZd Zd Zd Zd Zy)ThreadsafeIterzEWrap an iterator with a lock and propagate exceptions to all threads.c                 R    || _         t        j                         | _        d | _        y r:   )it	threadingLocklock
_exception)r|   r   s     r   r}   zThreadsafeIter.__init__  s     NN$	 r8   c                     | S r:   r   r{   s    r   __iter__zThreadsafeIter.__iter__  s    r8   c                 "    | j                         S r:   )__next__r{   s    r   nextzThreadsafeIter.next  s    }}r8   c                     | j                   5  | j                  r| j                  	 t        | j                        cd d d        S # t        $ r}|| _         d }~ww xY w# 1 sw Y   y xY wr:   )r   r   r   r   r   )r|   r   s     r   r   zThreadsafeIter.__next__  s`    YY 	oo%DGG}	 	  "#	 	s(   AA	AAAAA'N)r   r   r   r   r}   r   r   r   r   r8   r   r   r     s    O	r8   r   c                 B     t        j                          fd       }|S )Nc                  &    t         | i |      S r:   )r   )akwfs     r   gzthreadsafe_generator.<locals>.g  s    akbk**r8   	functoolswraps)r   r   s   ` r   threadsafe_generatorr     s%    __Q+ + Hr8   zkeras.utils.Sequencec                   <    e Zd ZdZed        Zed        Zd Zd Zy)r2   a  Base object for fitting to a sequence of data, such as a dataset.

    Every `Sequence` must implement the `__getitem__` and the `__len__` methods.
    If you want to modify your dataset between epochs, you may implement
    `on_epoch_end`. The method `__getitem__` should return a complete batch.

    Notes:

    `Sequence` is a safer way to do multiprocessing. This structure guarantees
    that the network will only train once on each sample per epoch, which is not
    the case with generators.

    Examples:

    ```python
    from skimage.io import imread
    from skimage.transform import resize
    import numpy as np
    import math

    # Here, `x_set` is list of path to the images
    # and `y_set` are the associated classes.

    class CIFAR10Sequence(tf.keras.utils.Sequence):

        def __init__(self, x_set, y_set, batch_size):
            self.x, self.y = x_set, y_set
            self.batch_size = batch_size

        def __len__(self):
            return math.ceil(len(self.x) / self.batch_size)

        def __getitem__(self, idx):
            low = idx * self.batch_size
            # Cap upper bound at array length; the last batch may be smaller
            # if the total number of items is not a multiple of batch size.
            high = min(low + self.batch_size, len(self.x))
            batch_x = self.x[low:high]
            batch_y = self.y[low:high]

            return np.array([
                resize(imread(file_name), (200, 200))
                   for file_name in batch_x]), np.array(batch_y)
    ```
    c                     t         )zGets batch at position `index`.

        Args:
            index: position of the batch in the Sequence.

        Returns:
            A batch
        NotImplementedError)r|   indexs     r   __getitem__zSequence.__getitem__  
     "!r8   c                     t         )znNumber of batch in the Sequence.

        Returns:
            The number of batches in the Sequence.
        r   r{   s    r   __len__zSequence.__len__(  s
     "!r8   c                      y)z(Method called at the end of every epoch.Nr   r{   s    r   on_epoch_endzSequence.on_epoch_end1  s    r8   c              #   Z    K    fdt        t                     D        D ]  }|  yw)z2Create a generator that iterate over the Sequence.c              3   (   K   | ]	  }|     y wr:   r   ).0ir|   s     r   	<genexpr>z$Sequence.__iter__.<locals>.<genexpr>7  s     7T!W7s   N)ranger   )r|   items   ` r   r   zSequence.__iter__5  s)     7eCI&67 	DJ	s   (+N)	r   r   r   r   r   r   r   r   r   r   r8   r   r2   r2     s:    ,\ 	" 	" " "r8   r2   c              #   $   K   	 | D ]  }|  w)zIterates indefinitely over a Sequence.

    Args:
      seq: `Sequence` instance.

    Yields:
      Batches of data from the `Sequence`.
    r   )seqr   s     r   iter_sequence_infiniter   ;  s$       	DJ	 s   c                 B     t        j                          fd       }|S )Nc                  f    t         5  t        dc}a | i |}|a|cd d d        S # 1 sw Y   y xY w)NT)_FORCE_THREADPOOL_LOCK_FORCE_THREADPOOL)argskwargsold_force_threadpooloutr   s       r   wrappedz.dont_use_multiprocessing_pool.<locals>.wrappedZ  sA    # 	6G3 "3T$V$C 4	 	 	s   '0r   )r   r   s   ` r   dont_use_multiprocessing_poolr   Y  s%    __Q  Nr8   c                 f    | rt         rt        j                  j                  S t        j                  S r:   )r   multiprocessingdummyPool)use_multiprocessings    r   get_pool_classr  f  s&    "3$$)))r8   c                  B    t         t        j                         a t         S )z,Lazily create the queue to track worker ids.)_WORKER_ID_QUEUEr   Queuer   r8   r   get_worker_id_queuer  m  s     *002r8   c                     | a y r:   _SHARED_SEQUENCES)seqss    r   	init_poolr
  u  s    r8   c                     t         |    |   S )ac  Get the value from the Sequence `uid` at index `i`.

    To allow multiple Sequences to be used at the same time, we use `uid` to
    get a specific one. A single Sequence would cause the validation to
    overwrite the training Sequence.

    Args:
        uid: int, Sequence identifier
        i: index

    Returns:
        The value at index `i`.
    r  )uidr   s     r   	get_indexr  z  s     S!!$$r8   zkeras.utils.SequenceEnqueuerc                   j    e Zd ZdZddZd ZddZd ZddZd Z	e
d	        Ze
d
        Ze
d        Zy)SequenceEnqueuera  Base class to enqueue inputs.

    The task of an Enqueuer is to use parallelism to speed up preprocessing.
    This is done with processes or threads.

    Example:

    ```python
        enqueuer = SequenceEnqueuer(...)
        enqueuer.start()
        datas = enqueuer.get()
        for data in datas:
            # Use the inputs; training, evaluating, predicting.
            # ... stop sometime.
        enqueuer.stop()
    ```

    The `enqueuer.get()` should be an infinite stream of data.
    c                    || _         || _        t        	 t        j                  dd      at        t        t              rt        | _        t        dz  anKt        j                         5  t        j                  | _        t        xj                  dz  c_
        d d d        d| _        d | _        d | _        d | _        d | _        y # t
        $ r daY w xY w# 1 sw Y   >xY w)Nr   r   r   )sequencer   _SEQUENCE_COUNTERr   ValueOSErrorr,   r   r  get_lockvalueworkersexecutor_fnqueue
run_threadstop_signal)r|   r  r   s      r   r}   zSequenceEnqueuer.__init__  s     #6  $&$3$9$9#q$A! '-(DH" #++- -,22!''1,'- 
'  & %&!	&- -s   C )/CCCCc                 X    | j                   d uxr | j                   j                          S r:   )r  is_setr{   s    r   
is_runningzSequenceEnqueuer.is_running  s*    t+MD4D4D4K4K4M0MMr8   c                 t   | j                   r| j                        | _        n
fd| _        | _        t	        j
                  |      | _        t        j                         | _        t        j                  | j                        | _        d| j                  _        | j                  j                          y)zStarts the handler's workers.

        Args:
            workers: Number of workers.
            max_queue_size: queue size
                (when full, workers could block on `put()`)
        c                 &     t        d            S rx   )r  )_r  s    r   r   z(SequenceEnqueuer.start.<locals>.<lambda>  s    )>)>w)G r8   )r   TN)r   _get_executor_initr  r  r  r  r   Eventr  Thread_runr  daemonstart)r|   r  max_queue_sizes    ` r   r'  zSequenceEnqueuer.start  s     ###66w?D  HD[[0
$??,#**$))<!%r8   c                 >    | j                   t        | j                  <   y)z&Sends current Iterable to all workers.N)r  r  r  r{   s    r   _send_sequencezSequenceEnqueuer._send_sequence  s     '+mm$((#r8   Nc                    | j                   j                          | j                  j                  5  | j                  j                  j	                          d| j                  _        | j                  j                  j                          ddd       | j                  j                  |       dt        | j                  <   y# 1 sw Y   8xY w)zStops running threads and wait for them to exit, if necessary.

        Should be called by the same thread which called `start()`.

        Args:
            timeout: maximum time to wait on `thread.join()`
        r   N)r  r*   r  mutexclearunfinished_tasksnot_fullnotifyr  rA   r  r  )r|   timeouts     r   stopzSequenceEnqueuer.stop  s     	ZZ 	)JJ""$*+DJJ'JJ&&(	) 	W%&*$((#	) 	)s   ACCc                 F    | j                         r| j                          y y r:   )r  r2  r{   s    r   __del__zSequenceEnqueuer.__del__  s    ??IIK r8   c                     t         )?Submits request to the executor and queue the `Future` objects.r   r{   s    r   r%  zSequenceEnqueuer._run  s
     "!r8   c                     t         )Gets the Pool initializer for multiprocessing.

        Args:
            workers: Number of workers.

        Returns:
            Function, a Function to initialize the pool
        r   )r|   r  s     r   r"  z#SequenceEnqueuer._get_executor_init  r   r8   c                     t         )zCreates a generator to extract data from the queue.

        Skip the data if it is `None`.
        # Returns
            Generator yielding tuples `(inputs, targets)`
                or `(inputs, targets, sample_weights)`.
        r   r{   s    r   r   zSequenceEnqueuer.get  s
     "!r8   )F)r   
   r:   )r   r   r   r   r}   r  r'  r*  r2  r4  r   r%  r"  r   r   r8   r   r  r    sb    ( :N (4
+  " " 	" 	" " "r8   r  zkeras.utils.OrderedEnqueuerc                   <     e Zd ZdZd fd	Zd Zd Zd Zd Z xZ	S )OrderedEnqueuera  Builds a Enqueuer from a Sequence.

    Args:
        sequence: A `tf.keras.utils.data_utils.Sequence` object.
        use_multiprocessing: use multiprocessing if True, otherwise threading
        shuffle: whether to shuffle the data at the beginning of each epoch
    c                 4    t         |   ||       || _        y r:   )superr}   shuffle)r|   r  r   r?  	__class__s       r   r}   zOrderedEnqueuer.__init__  s    #67r8   c                     fd}|S )r8  c                 x     t        d      t        | d t               f      }t        j	                  |       |S NT)initializerinitargs)r  init_pool_generatorr  _DATA_POOLSadd)r	  poolr  s     r   pool_fnz3OrderedEnqueuer._get_executor_init.<locals>.pool_fn#  s;    '>$'/&9&;<D
 OOD!Kr8   r   r|   r  rJ  s    ` r   r"  z"OrderedEnqueuer._get_executor_init  s    	 r8   c                     	 t        j                  d       | j                  j                  dk(  s| j                  j                         ryJ)zWait for the queue to be empty.皙?r   N)timesleepr  r.  r  r  r{   s    r   _wait_queuezOrderedEnqueuer._wait_queue.  s;    JJsOzz**a/43C3C3J3J3L r8   c           	         t        t        t        | j                                    }| j	                          	 | j
                  rt        j
                  |       t        | j                  t                    5 }|D ]c  }| j                  j                         r
 ddd       y| j                  j                  |j                  t        | j                   |f      d       e | j#                          | j                  j                         r
	 ddd       y	 ddd       | j                  j%                          | j	                          # 1 sw Y   5xY wr6  TNblock)r'   r   r   r  r*  r?  randomr   r  r  r  r  r  putapply_asyncr  r  rP  r   )r|   r  executorr   s       r   r%  zOrderedEnqueuer._run5  s   c$--012||x())*;<= ! A''..0 
 JJNN ,,Y1F" # 	   "##**,  -$ MM&&(!/  s   8!E
"A*E

Ec              #   v  K   | j                         rn	 | j                  j                  dd      j                         }| j                         r| j                  j                          || | j                         rmyy# t        j                  $ r Y (t
        $ r}| j                          |d}~ww xY ww)  Creates a generator to extract data from the queue.

        Skip the data if it is `None`.

        Yields:
            The next element in the queue, i.e. a tuple
            `(inputs, targets)` or
            `(inputs, targets, sample_weights)`.
        T   rT  r1  N)r  r  r   	task_doneEmptyr   r2  )r|   inputsr   s      r   r   zOrderedEnqueuer.getR  s      oo
dA>BBD??$JJ((*% L oo ;;  		s;   B9AB /B9 B9B6B9B6B11B66B9)FF)
r   r   r   r   r}   r"  rP  r%  r   __classcell__r@  s   @r   r<  r<    s!    *":r8   r<  c                     | a t        j                         }d|j                   |_        |,t        j
                  j                  ||j                  z          ||j                  |j                  dd       yy)a  Initializer function for pool workers.

    Args:
      gens: State which should be made available to worker processes.
      random_seed: An optional value with which to seed child processes.
      id_queue: A multiprocessing Queue of worker ids. This is used to indicate
        that a worker process was created by TF-Keras and can be terminated
        using the cleanup_all_keras_forkpools utility.
    Keras_worker_NTrM  r\  )	r  r   current_processrG   r/   rU  seedidentrV  )gensrandom_seedid_queueworker_procs       r   rF  rF  j  st     !113K '{'7'7&89K
		{[%6%667[&&dC@ r8   c                 &    t        t        |          S )a[  Gets the next value from the generator `uid`.

    To allow multiple generators to be used at the same time, we use `uid` to
    get a specific one. A single generator would cause the validation to
    overwrite the training generator.

    Args:
        uid: int, generator identifier

    Returns:
        The next value of generator `uid`.
    )r   r  )r  s    r   next_samplerl    s     !#&''r8   zkeras.utils.GeneratorEnqueuerc                   6     e Zd ZdZd fd	Zd Zd Zd Z xZS )GeneratorEnqueuera  Builds a queue out of a data generator.

    The provided generator can be finite in which case the class will throw
    a `StopIteration` exception.

    Args:
        generator: a generator function which yields data
        use_multiprocessing: use multiprocessing if True, otherwise threading
        random_seed: Initial seed for workers,
            will be incremented by one for each worker.
    c                 4    t         |   ||       || _        y r:   )r>  r}   rh  )r|   	generatorr   rh  r@  s       r   r}   zGeneratorEnqueuer.__init__  s    $78&r8   c                       fd}|S )zGets the Pool initializer for multiprocessing.

        Args:
          workers: Number of works.

        Returns:
            A Function to initialize the pool
        c                      t        d      t        | j                  t               f      }t        j                  |       |S rC  )r  rF  rh  r  rG  rH  )r	  rI  r|   r  s     r   rJ  z5GeneratorEnqueuer._get_executor_init.<locals>.pool_fn  sA    '>$'/ 0 02E2GHD
 OOD!Kr8   r   rK  s   `` r   r"  z$GeneratorEnqueuer._get_executor_init  s    	 r8   c                 <   | j                          t        | j                  t                    5 }	 | j                  j                         r
	 ddd       y| j                  j                  |j                  t        | j                  f      d       a# 1 sw Y   yxY wrR  )r*  r   r  r  r  r  r  rV  rW  rl  r  )r|   rX  s     r   r%  zGeneratorEnqueuer._run  s    T%%&789 	X##**,	 	
 

((txxkB$  	 	 	s   B=BBc              #     K   	 | j                         r\| j                  j                  d      j                         }| j                  j                          || | j                         r[yy# t        $ r g }| j                  j                         dkD  rI|j                  | j                  j                  d             | j                  j                         dkD  rI|D ]  }|j                           |D cg c]#  }|j                         s|j                         % nc c}w }}|D ]	  }||  Y yt        $ r/}| j                          dt        |      v rt        d      |d}~ww xY ww)rZ  TrS  Nr   zgenerator already executingzyYour generator is NOT thread-safe. Keras requires a thread-safe generator when `use_multiprocessing=False, workers > 1`. )r  r  r   r]  StopIterationqsizeappendwait
successfulr   r2  r&   rb   )r|   r_  	last_onesr   futurer   s         r   r   zGeneratorEnqueuer.get  sY    	//#d3779

$$&% L	 //#
  	!I**""$q(  d!;< **""$q(   ,5!'8I8I8K

 I  $ !% L!  	IIK,A6"A 
 G	sT   E7A*A1 /E71A0E4"E4=D&D&%E45E4;E7=E4*E//E44E7)FN)	r   r   r   r   r}   r"  r%  r   r`  ra  s   @r   rn  rn    s    
'*
'r8   rn  zkeras.utils.pad_sequencesz*keras.preprocessing.sequence.pad_sequencesc           	      R   t        | d      st        d      t        |       }g }d}d}	| D ]N  }
	 |j                  t        |
             |	r/t        |
      r$t	        j
                  |
      j                  dd }d}	P |t	        j                  |      }t	        j                  |t        j                        xs$ t	        j                  |t        j                        }t        |t              r&|t        k7  r|st        d	| d
t        |       d      t	        j                  ||f|z   ||      }
t!        |       D ]  \  }}t        |      s|dk(  r|| d }n|dk(  r|d| }nt        d| d      t	        j
                  ||      }|j                  dd |k7  r!t        d|j                  dd  d| d|       |dk(  r||
|dt        |      f<   |dk(  r||
|t        |       df<   t        d| d       |
S # t        $ r}t        dt        |
             |d}~ww xY w)a	  Pads sequences to the same length.

    This function transforms a list (of length `num_samples`)
    of sequences (lists of integers)
    into a 2D Numpy array of shape `(num_samples, num_timesteps)`.
    `num_timesteps` is either the `maxlen` argument if provided,
    or the length of the longest sequence in the list.

    Sequences that are shorter than `num_timesteps`
    are padded with `value` until they are `num_timesteps` long.

    Sequences longer than `num_timesteps` are truncated
    so that they fit the desired length.

    The position where padding or truncation happens is determined by
    the arguments `padding` and `truncating`, respectively.
    Pre-padding or removing values from the beginning of the sequence is the
    default.

    >>> sequence = [[1], [2, 3], [4, 5, 6]]
    >>> tf.keras.utils.pad_sequences(sequence)
    array([[0, 0, 1],
           [0, 2, 3],
           [4, 5, 6]], dtype=int32)

    >>> tf.keras.utils.pad_sequences(sequence, value=-1)
    array([[-1, -1,  1],
           [-1,  2,  3],
           [ 4,  5,  6]], dtype=int32)

    >>> tf.keras.utils.pad_sequences(sequence, padding='post')
    array([[1, 0, 0],
           [2, 3, 0],
           [4, 5, 6]], dtype=int32)

    >>> tf.keras.utils.pad_sequences(sequence, maxlen=2)
    array([[0, 1],
           [2, 3],
           [5, 6]], dtype=int32)

    Args:
        sequences: List of sequences (each sequence is a list of integers).
        maxlen: Optional Int, maximum length of all sequences. If not provided,
            sequences will be padded to the length of the longest individual
            sequence.
        dtype: (Optional). Type of the output sequences.
            To pad sequences with variable length strings, you can use `object`.
            Defaults to `"int32"`.
        padding: String, "pre" or "post" (optional):
            pad either before or after each sequence. Defaults to `"pre"`.
        truncating: String, "pre" or "post" (optional):
            remove values from sequences larger than
            `maxlen`, either at the beginning or at the end of the sequences.
            Defaults to `"pre"`.
        value: Float or String, padding value. (Optional). Defaults to `0.`.

    Returns:
        Numpy array with shape `(len(sequences), maxlen)`

    Raises:
        ValueError: In case of invalid values for `truncating` or `padding`,
            or in case of invalid shape for a `sequences` entry.
    r   z`sequences` must be iterable.r   Tr   NFz=`sequences` must be a list of iterables. Found non-iterable: z`dtype` z( is not compatible with `value`'s type: z;
You should set `dtype=object` for variable length strings.)dtypeprepostzTruncating type "z" not understoodzShape of sample z of sequence at position z" is different from expected shape zPadding type ")hasattrr   r   rw  r/   asarrayshape	TypeErrorr&   max
issubdtypestr_r,   objecttypefull	enumerate)	sequencesmaxlenr}  padding
truncatingr  num_sampleslengthssample_shapeflagr5   r   is_dtype_stridxstruncs                   r   pad_sequencesr    so   T 9i(899i.KGLD
  
		NN3q6"A!zz!}22126
 ~==0 BMMrww5L %%6/,ugEE{m 
 	
 	f%4e5IAI& IQ1vvghKE6!gvJE0<LMNN 

5.;;qr?l*"5;;qr?"3 45 B."  f#(Ac<SZ< $)AcCJ;= !~gY6FGHH1I2 H[  	''*1vh0 	s   AH  	H&	H!!H&)NN)rM   rW   )
NNFNNdatasetsrW   FrW   Nr:   )r     )rW   r  )Nint32r~  r~  g        )Mr   r   r   multiprocessing.dummyr   r;   r   r  rU  rg   r[   r   rN  r3   r   rP   weakrefr]   abcr   
contextlibr   numpyr/   tensorflow.compat.v2compatv2r-   six.moves.urllib.parser   tf_keras.src.utilsr   r    tf_keras.src.utils.generic_utilsr    tensorflow.python.util.tf_exportr	   six.moves.urllib.requestr
   r$   urllib.requestr7   r?   rD   rK   rU   ro   r   r   r   r   r   r   r   r2   r   r  r  WeakSetrG  r  r*   _WORKER_IDSr   RLockr   r   r  r  r
  r  r  r<  rF  rl  rn  r  r   r8   r   <module>r     s    /    	                ! ! + ' ) 4 : , $ T	3L8
$5p $%

w &wt(	>,   F $%K K &K\    goo e (* 
 
%" ,-|" |" .|"~ +,[& [ -[|A6(  -.Y( Y /Yx !M
 

EEr8   