a
    Sic                     @   s<  d Z ddlZddlZddlZddlZddlZddlZddl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  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% dIddZ&dd Z'dJddZ(e#ddKddZ)dd Z*dLddZ+dMddZ,dNd d!Z-G d"d# d#Z.d$d% Z/e#d&G d'd( d(Z0d)d* Z1i a2da3e4 Z5da6e7 Z8da9e: Z;d+d, Z<d-d. Z=d/d0 Z>d1d2 Z?d3d4 Z@e#d5G d6d7 d7ZAe#d8G d9d: d:eAZBdOd;d<ZCd=d> ZDe#d?G d@dA dAeAZEe#dBdCdPdGdHZFdS )Qz(Utilities for file download and caching.    N)abstractmethod)closing)urlsplit)io_utils)
tf_inspect)Progbar)keras_export)urlopenc                 C   s^   ddd}t | |}t|d,}|||dD ]}|| q,W d   n1 sP0    Y  dS )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                 s   sd   |   d}d}|d ur&t| }d}| |}|d7 }|d urP|||| |r`|V  q*q`q*d S )NzContent-Lengthr      )infogetintstripread)response
chunk_size
reporthookcontent_type
total_sizecountchunk r   R/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/utils/data_utils.py
chunk_readD   s    
zurlretrieve.<locals>.chunk_readwb)r   )r
   N)r	   openwrite)urlfilenamer   datar   r   fdr   r   r   r   urlretrieve3   s
    

r#   c                 C   sJ   t tttttf}t| tjt	j
f| r*dS t| pHt| tpHt| tjS )z'Check if `x` is a Keras generator type.F)strlisttupledictset	frozenset
isinstancetfTensornpndarrayr   isgeneratorSequencetypingIterator)xbuiltin_iteratorsr   r   r   is_generator_or_sequence]   s    

r5   .autoc                 C   s  |du rdS |dkrddg}t |tr,|g}t| } t|}|D ]}|dkr\tj}tj}|dkrptj}tj	}|| rD|| j}z|
| W nJ tjttfy   tj|rtj|rt| n
t|  Y n0 W d   n1 s0    Y   dS qDdS )aN  Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.

    Args:
        file_path: path to the archive file
        path: path 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.
    NFr7   tarzipT)r*   r$   r   path_to_stringtarfiler   
is_tarfilezipfileZipFile
is_zipfile
extractallTarErrorRuntimeErrorKeyboardInterruptospathexistsisfileremoveshutilrmtree)	file_pathrE   archive_formatarchive_typeopen_fnis_match_fnarchiver   r   r   _extract_archivei   s6    




&rQ   zkeras.utils.get_fileFdatasetsc
              
   C   s  |du rt d|	du r.tjtjdd}	|durF|du rF|}d}tj|	}
t|
tjsntjdd}
tj|
|}t| t	| } | stj
t|j} | st d| d|r| d	rt| } | d
d
} t| } tj|| }|d	 }ntj|| }d}tj|rZ|dur^t|||ds^td| d| d d}nd}|rtd|  G dd d}d}zzt|||  W n~ tjjy } z"t|||j|jW Y d}~nHd}~0  tjjy } z"t|||j|jW Y d}~n
d}~0 0 W n2 ttfyN   tj|rHt |  Y n0 tj|r|durt|||dst d| d| d|rtj|st!||dd |S |rt!||| |S )aM	  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(
        "flower_photos",
        "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz",
        untar=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 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 the default directory `~/.keras/`.

    Returns:
        Path to the downloaded file
    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                   @   s    e Zd ZdZdd Zdd ZdS )zget_file.<locals>.DLProgbarz1Manage progress bar state for use in urlretrieve.c                 S   s   d | _ d| _d S NF)progbarfinishedselfr   r   r   __init__  s    z$get_file.<locals>.DLProgbar.__init__c                 S   sZ   | j s|dkrd }t|| _ || }||k r:| j | n| jsV| j | j j d| _d S )Nr   T)rX   r   updaterY   target)r[   Z	block_num
block_sizer   currentr   r   r   __call__  s    
z$get_file.<locals>.DLProgbar.__call__N)__name__
__module____qualname____doc__r\   ra   r   r   r   r   	DLProgbar  s   rf   z!URL fetch failure on {}: {} -- {}z+Incomplete or corrupted file detected. The z0 file hash does not match the provided value of r6   r8   )rL   )"
ValueErrorrD   rE   join
expanduseraccessW_OK_makedirs_exist_okr   r:   basenamer   endswithpathlibPathwith_suffixr$   rF   validate_fileZ	print_msgr#   urlliberror	HTTPError	ExceptionformatcodemsgURLErrorerrnoreasonrC   rH   rQ   )fnameoriginuntarmd5_hash	file_hashcache_subdirhash_algorithmextractrL   	cache_dirdatadir_basedatadiruntar_fpathfpathdownloadrf   	error_msger   r   r   get_file   s    >




*0
r   c                 C   s   t j| dd d S )NT)exist_ok)rD   makedirs)r   r   r   r   rl   I  s    rl   c                 C   s<   | dkrt  S | dkr4|dur4t|dkr4t  S t  S )z+Returns hash algorithm as hashlib function.sha256r7   N@   )hashlibr   lenrT   )rV   r   r   r   r   _resolve_hasherM  s
    r   r     c                    sn   t |trt|}n|}t| d4t fdddD ]}|| q8W d   n1 s\0    Y  | S )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                      s
     S N)r   r   r   
fpath_filer   r   <lambda>r      z_hash_file.<locals>.<lambda>r   N)r*   r$   r   r   iterr]   	hexdigest)r   rV   r   hasherr   r   r   r   
_hash_fileY  s    

*r   c                 C   s.   t ||}tt| ||t|kr&dS dS dS )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
    TFN)r   r$   r   )r   r   rV   r   r   r   r   r   rr   x  s    
rr   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )ThreadsafeIterzEWrap an iterator with a lock and propagate exceptions to all threads.c                 C   s   || _ t | _d | _d S r   )it	threadingLocklock
_exception)r[   r   r   r   r   r\     s    

zThreadsafeIter.__init__c                 C   s   | S r   r   rZ   r   r   r   __iter__  s    zThreadsafeIter.__iter__c                 C   s   |   S r   )__next__rZ   r   r   r   next  s    zThreadsafeIter.nextc                 C   s~   | j d | jr| jzt| jW W  d    S  tyZ } z|| _ W Y d }~n
d }~0 0 W d    n1 sp0    Y  d S r   )r   r   r   r   rv   )r[   r   r   r   r   r     s    zThreadsafeIter.__next__N)rb   rc   rd   re   r\   r   r   r   r   r   r   r   r     s
   r   c                    s   t   fdd}|S )Nc                     s   t  | i |S r   )r   )akwfr   r   g  s    zthreadsafe_generator.<locals>.g	functoolswraps)r   r   r   r   r   threadsafe_generator  s    r   zkeras.utils.Sequencec                   @   s8   e Zd ZdZedd Zedd Zdd Zdd	 Zd
S )r0   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` are 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):
            batch_x = self.x[idx * self.batch_size:(idx + 1) *
            self.batch_size]
            batch_y = self.y[idx * self.batch_size:(idx + 1) *
            self.batch_size]

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

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

        Returns:
            A batch
        NNotImplementedError)r[   indexr   r   r   __getitem__  s    
zSequence.__getitem__c                 C   s   t dS )znNumber of batch in the Sequence.

        Returns:
            The number of batches in the Sequence.
        Nr   rZ   r   r   r   __len__  s    zSequence.__len__c                 C   s   dS )z(Method called at the end of every epoch.Nr   rZ   r   r   r   on_epoch_end  s    zSequence.on_epoch_endc                 #   s*    fddt t D D ]
}|V  qdS )z2Create a generator that iterate over the Sequence.c                 3   s   | ]} | V  qd S r   r   ).0irZ   r   r   	<genexpr>  r   z$Sequence.__iter__.<locals>.<genexpr>N)ranger   )r[   itemr   rZ   r   r     s    zSequence.__iter__N)	rb   rc   rd   re   r   r   r   r   r   r   r   r   r   r0     s   -

r0   c                 c   s   | D ]
}|V  qq dS )zIterates indefinitely over a Sequence.

    Args:
      seq: `Sequence` instance.

    Yields:
      Batches of data from the `Sequence`.
    Nr   )seqr   r   r   r   iter_sequence_infinite  s    
r   c                    s   t   fdd}|S )Nc                     sH   t 0 td }a | i |}|a|W  d    S 1 s:0    Y  d S )NT)_FORCE_THREADPOOL_LOCK_FORCE_THREADPOOL)argskwargsold_force_threadpooloutr   r   r   wrapped&  s
    
z.dont_use_multiprocessing_pool.<locals>.wrappedr   )r   r   r   r   r   dont_use_multiprocessing_pool%  s    r   c                 C   s   | rt rtjjS tjS r   )r   multiprocessingdummyPool)use_multiprocessingr   r   r   get_pool_class2  s    r   c                   C   s   t du rt a t S )z,Lazily create the queue to track worker ids.N)_WORKER_ID_QUEUEr   Queuer   r   r   r   get_worker_id_queue9  s    r   c                 C   s   | a d S r   _SHARED_SEQUENCES)seqsr   r   r   	init_poolA  s    r   c                 C   s   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   r   r   r   	get_indexF  s    r   zkeras.utils.SequenceEnqueuerc                   @   sj   e Zd ZdZdddZdd Zdd	d
Zdd ZdddZdd Z	e
dd Ze
dd Ze
dd ZdS )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.
    Fc                 C   s   || _ || _td u r<ztddaW n ty:   daY n0 tttrVt| _td7 an>t	 & tj
| _t j
d7  _
W d    n1 s0    Y  d| _d | _d | _d | _d | _d S )Nr   r   r   )sequencer   _SEQUENCE_COUNTERr   ValueOSErrorr*   r   r   get_lockvalueworkersexecutor_fnqueue
run_threadstop_signal)r[   r   r   r   r   r   r\   m  s$    



,zSequenceEnqueuer.__init__c                 C   s   | j d uo| j   S r   )r   is_setrZ   r   r   r   
is_running  s    zSequenceEnqueuer.is_runningr   
   c                    sd   | j r|  | _n fdd| _ | _t|| _t | _tj	| j
d| _d| j_| j  dS )zStarts the handler's workers.

        Args:
            workers: Number of workers.
            max_queue_size: queue size
                (when full, workers could block on `put()`)
        c                    s   t d S rW   )r   )_r   r   r   r     r   z(SequenceEnqueuer.start.<locals>.<lambda>)r^   TN)r   _get_executor_initr   r   r   r   r   Eventr   Thread_runr   daemonstart)r[   r   max_queue_sizer   r   r   r     s    
zSequenceEnqueuer.startc                 C   s   | j t| j< dS )z&Sends current Iterable to all workers.N)r   r   r   rZ   r   r   r   _send_sequence  s    zSequenceEnqueuer._send_sequenceNc                 C   sl   | j   | jj0 | jj  d| j_| jj  W d   n1 sH0    Y  | j	| dt
| j< dS )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   rh   r   r   )r[   timeoutr   r   r   stop  s    

*zSequenceEnqueuer.stopc                 C   s   |   r|   d S r   )r   r   rZ   r   r   r   __del__  s    zSequenceEnqueuer.__del__c                 C   s   t dS )?Submits request to the executor and queue the `Future` objects.Nr   rZ   r   r   r   r     s    zSequenceEnqueuer._runc                 C   s   t dS )Gets the Pool initializer for multiprocessing.

        Args:
            workers: Number of workers.

        Returns:
            Function, a Function to initialize the pool
        Nr   r[   r   r   r   r   r     s    
z#SequenceEnqueuer._get_executor_initc                 C   s   t dS )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)`.
        Nr   rZ   r   r   r   r     s    	zSequenceEnqueuer.get)F)r   r   )N)rb   rc   rd   re   r\   r   r   r   r   r   r   r   r   r   r   r   r   r   r   W  s   




r   zkeras.utils.OrderedEnqueuerc                       sB   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zdd Z  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
    Fc                    s   t  || || _d S r   )superr\   shuffle)r[   r   r   r   	__class__r   r   r\     s    zOrderedEnqueuer.__init__c                    s    fdd}|S )r   c                    s(   t d t| d t fd}t| |S NT)initializerinitargs)r   init_pool_generatorr   _DATA_POOLSaddr   poolr   r   r   pool_fn  s    

z3OrderedEnqueuer._get_executor_init.<locals>.pool_fnr   r[   r   r  r   r   r   r     s    
	z"OrderedEnqueuer._get_executor_initc                 C   s*   t d | jjdks | j r dS q dS )zWait for the queue to be empty.皙?r   N)timesleepr   r   r   r   rZ   r   r   r   _wait_queue  s    
zOrderedEnqueuer._wait_queuec                 C   s   t tt| j}|   | jr*t| t| t	v}|D ]>}| j
 r^ W d   dS | jj|t| j|fdd q>|   | j
 rW d   dS W d   n1 s0    Y  | j  |   qdS r   NTblock)r%   r   r   r   r   r   randomr   r   r   r   r   r   putapply_asyncr   r   r  r   )r[   r   executorr   r   r   r   r     s"    


.
zOrderedEnqueuer._runc              
   c   s   |   rz8| jjddd }|   r0| j  |dur>|V  W q  tjyT   Y q  ty } z|   |W Y d}~q d}~0 0 q dS )  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   r  r   N)r   r   r   	task_doneEmptyrv   r   )r[   inputsr   r   r   r   r     s    


zOrderedEnqueuer.get)FF)
rb   rc   rd   re   r\   r   r  r   r   __classcell__r   r   r   r   r     s   r   c                 C   sR   | a t }d|j|_|dur4tj||j  |durN|j	|jddd dS )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 Keras and can be terminated using
        the cleanup_all_keras_forkpools utility.
    zKeras_worker_{}NTr  r  )
r   r   current_processrw   namer-   r  seedidentr  )gensrandom_seedid_queueworker_procr   r   r   r  6  s    r  c                 C   s   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   r   r   r   next_sampleQ  s    r"  zkeras.utils.GeneratorEnqueuerc                       s:   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Z  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.
    FNc                    s   t  || || _d S r   )r   r\   r  )r[   	generatorr   r  r   r   r   r\   o  s    zGeneratorEnqueuer.__init__c                    s    fdd}|S )zGets the Pool initializer for multiprocessing.

        Args:
          workers: Number of works.

        Returns:
            A Function to initialize the pool
        c                    s*   t dt|  jt fd}t| |S r   )r   r  r  r   r  r  r  r   r   r   r  }  s    
z5GeneratorEnqueuer._get_executor_init.<locals>.pool_fnr   r  r   r   r   r   s  s    
	z$GeneratorEnqueuer._get_executor_initc                 C   sr   |    t| tH}| j r2W d   dS | jj|t	| j
fdd qW d   n1 sd0    Y  dS r  )r   r   r   r   r   r   r   r  r  r"  r   )r[   r  r   r   r   r     s    
zGeneratorEnqueuer._runc              
   c   s   z8|   r6| jjdd }| j  |dur|V  qW n ty   g }| j dkrn|| jjdd qJ|D ]}|  qrdd |D }|D ]}|dur|V  qY nD ty } z,| 	  dt
|v rtd|W Y d}~n
d}~0 0 dS )	r  Tr  Nr   c                 S   s   g | ]}|  r| qS r   )
successfulr   )r   futurer   r   r   
<listcomp>  s   z)GeneratorEnqueuer.get.<locals>.<listcomp>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waitrv   r   r$   rB   )r[   r  	last_onesr   r   r   r   r   r     s2    


zGeneratorEnqueuer.get)FN)	rb   rc   rd   re   r\   r   r   r   r  r   r   r   r   r#  a  s
   r#  zkeras.utils.pad_sequencesz*keras.preprocessing.sequence.pad_sequencesint32pre        c                 C   s  t | dstdt| }g }d}d}	| D ]t}
z6|t|
 |	rbt|
rbt|
jdd }d}	W q* ty } z tdt|
 |W Y d}~q*d}~0 0 q*|du rt	|}t
|tjpt
|tj}t|tr|tkr|std	| d
t| dtj||f| ||d}
t| D ]\}}t|s4q|dkrN|| d }n(|dkrf|d| }ntd| dtj||d}|jdd |krtd|jdd  d| d| |dkr||
|dt|f< n2|dkr||
|t| df< ntd| dq|
S )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.preprocessing.sequence.pad_sequences(sequence)
    array([[0, 0, 1],
           [0, 2, 3],
           [4, 5, 6]], dtype=int32)

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

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

    >>> tf.keras.preprocessing.sequence.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, defaults to `"int32"`). Type of the output sequences.
            To pad sequences with variable length strings, you can use `object`.
        padding: String, "pre" or "post" (optional, defaults to `"pre"`):
            pad either before or after each sequence.
        truncating: String, "pre" or "post" (optional, defaults to `"pre"`):
            remove values from sequences larger than
            `maxlen`, either at the beginning or at the end of the sequences.
        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.)dtyper.  postzTruncating type "z" not understoodzShape of sample z of sequence at position z" is different from expected shape zPadding type ")hasattrrg   r   r*  r-   asarrayshape	TypeErrorr$   max
issubdtypestr_unicode_r*   objecttypefull	enumerate)	sequencesmaxlenr0  paddingZ
truncatingr   num_sampleslengthssample_shapeflagr3   r   Zis_dtype_stridxstruncr   r   r   pad_sequences  sn    H






rH  )NN)r6   r7   )
NNFNNrR   r7   Fr7   N)N)r   r   )r7   r   )NN)Nr-  r.  r.  r/  )Gre   r   r   multiprocessing.dummyr   rD   ro   r   r  rI   r;   r   r	  r1   rs   weakrefr=   abcr   
contextlibr   numpyr-   tensorflow.compat.v2compatv2r+   Zsix.moves.urllib.parser   keras.utilsr   r   keras.utils.generic_utilsr    tensorflow.python.util.tf_exportr   six.moves.urllib.requestr	   r#   r5   rQ   r   rl   r   r   rr   r   r   r0   r   r   r   WeakSetr  r   r(   _WORKER_IDSr   RLockr   r   r   r   r   r   r   r   r  r"  r#  rH  r   r   r   r   <module>   s   
*
1           /


#M^
\     