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m  mZ ddlmZ ddlmZ ddlmZ ddlmZ i Zi ZdadZe Zed	d
G dd dZ eddd Z!dZ"e Z#e a$e a%dd Z&dd Z'dd Z(G dd dZ)G dd dZ*G dd dZ+G dd de,Z-G dd  d Z.d^d!d"Z/ed#d_d%d&Z0ed'd(d) Z1ej2d*d+ Z3ed,d`d-d.Z4G d/d0 d0e5Z6ed1d2d3 Z7dad4d5Z8dbd7d8Z9ed9dcd:d;Z:d<d= Z;ddd>d?Z<ded@dAZ=edBG dCdD dDZ>dEdF Z?dfdGdHZ@dIdJ ZAdKdL ZBdMdN ZCdOdP ZDdgdRdSZEdTdU ZFdVdW ZGdXdY ZHdZd[ ZIG d\d] d]ejJZKe ZLdS )hz#Python utilities required by Keras.    N)io_utils)tf_contextlib)
tf_inspect)keras_exportFzlayer was saved without configzkeras.utils.custom_object_scopezkeras.utils.CustomObjectScopec                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	CustomObjectScopea  Exposes custom classes/functions to Keras deserialization internals.

    Under a scope `with custom_object_scope(objects_dict)`, Keras methods such
    as `tf.keras.models.load_model` or `tf.keras.models.model_from_config`
    will be able to deserialize any custom object referenced by a
    saved config (e.g. a custom layer or metric).

    Example:

    Consider a custom regularizer `my_regularizer`:

    ```python
    layer = Dense(3, kernel_regularizer=my_regularizer)
    # Config contains a reference to `my_regularizer`
    config = layer.get_config()
    ...
    # Later:
    with custom_object_scope({'my_regularizer': my_regularizer}):
      layer = Dense.from_config(config)
    ```

    Args:
        *args: Dictionary or dictionaries of `{name: object}` pairs.
    c                 G   s   || _ d | _d S N)custom_objectsbackup)selfargs r   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/utils/generic_utils.py__init__T   s    zCustomObjectScope.__init__c                 C   s(   t j | _| jD ]}t j| q| S r   )_THREAD_LOCAL_CUSTOM_OBJECTS__dict__copyr	   r   update)r
   objectsr   r   r   	__enter__X   s    
zCustomObjectScope.__enter__c                 O   s   t j  t j| j d S r   )r   r   clearr   r	   r
   r   kwargsr   r   r   __exit__^   s    
zCustomObjectScope.__exit__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   6   s   r   zkeras.utils.get_custom_objectsc                   C   s   t S )a  Retrieves a live reference to the global dictionary of custom objects.

    Custom objects set using using `custom_object_scope` are not added to the
    global dictionary of custom objects, and will not appear in the returned
    dictionary.

    Example:

    ```python
    get_custom_objects().clear()
    get_custom_objects()['MyObject'] = MyObject
    ```

    Returns:
        Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`).
    )_GLOBAL_CUSTOM_OBJECTSr   r   r   r   get_custom_objectsc   s    r   shared_object_idc                   C   s   t tddS )zFGet whether shared object handling is disabled in a threadsafe manner.disabledF)getattrSHARED_OBJECT_DISABLEDr   r   r   r   _shared_object_disabled   s    r#   c                   C   s   t tdt S )BGet the current shared object saving scope in a threadsafe manner.scope)r!   SHARED_OBJECT_LOADINGNoopLoadingScoper   r   r   r   _shared_object_loading_scope   s    r(   c                   C   s   t tddS )r$   r%   N)r!   SHARED_OBJECT_SAVINGr   r   r   r   _shared_object_saving_scope   s    r*   c                   @   s    e Zd ZdZdd Zdd ZdS )DisableSharedObjectScopezA context manager for disabling handling of shared objects.

    Disables shared object handling for both saving and loading.

    Created primarily for use with `clone_model`, which does extra surgery that
    is incompatible with shared objects.
    c                 C   s   dt _t | _t | _d S NT)r"   r    r(   _orig_loading_scoper*   _orig_saving_scoper
   r   r   r   r      s    z"DisableSharedObjectScope.__enter__c                 O   s   dt _| jt_| jt_d S )NF)r"   r    r-   r&   r%   r.   r)   r   r   r   r   r      s    z!DisableSharedObjectScope.__exit__N)r   r   r   r   r   r   r   r   r   r   r+      s   r+   c                   @   s    e Zd ZdZdd Zdd ZdS )r'   zThe default shared object loading scope. It does nothing.

    Created to simplify serialization code that doesn't care about shared
    objects (e.g. when serializing a single object).
    c                 C   s   d S r   r   )r
   unused_object_idr   r   r   get   s    zNoopLoadingScope.getc                 C   s   d S r   r   r
   	object_idobjr   r   r   set   s    zNoopLoadingScope.setN)r   r   r   r   r1   r5   r   r   r   r   r'      s   r'   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )SharedObjectLoadingScopeaW  A context manager for keeping track of loaded objects.

    During the deserialization process, we may come across objects that are
    shared across multiple layers. In order to accurately restore the network
    structure to its original state, `SharedObjectLoadingScope` allows us to
    re-use shared objects rather than cloning them.
    c                 C   s   t  rt S | t_i | _| S r   )r#   r'   r&   r%   _obj_ids_to_objr/   r   r   r   r      s
    z"SharedObjectLoadingScope.__enter__c                 C   s   |du rdS | j |S )a  Given a shared object ID, returns a previously instantiated object.

        Args:
          object_id: shared object ID to use when attempting to find
            already-loaded object.

        Returns:
          The object, if we've seen this ID before. Else, `None`.
        N)r7   r1   )r
   r3   r   r   r   r1      s    zSharedObjectLoadingScope.getc                 C   s   |du rdS || j |< dS )z<Stores an instantiated object for future lookup and sharing.N)r7   r2   r   r   r   r5      s    zSharedObjectLoadingScope.setc                 O   s   t  t_d S r   )r'   r&   r%   r   r   r   r   r      s    z!SharedObjectLoadingScope.__exit__N)r   r   r   r   r   r1   r5   r   r   r   r   r   r6      s
   	r6   c                       s(   e Zd ZdZ fddZdd Z  ZS )SharedObjectConfiga  A configuration container that keeps track of references.

    `SharedObjectConfig` will automatically attach a shared object ID to any
    configs which are referenced more than once, allowing for proper shared
    object reconstruction at load time.

    In most cases, it would be more proper to subclass something like
    `collections.UserDict` or `collections.Mapping` rather than `dict` directly.
    Unfortunately, python's json encoder does not support `Mapping`s. This is
    important functionality to retain, since we are dealing with serialization.

    We should be safe to subclass `dict` here, since we aren't actually
    overriding any core methods, only augmenting with a new one for reference
    counting.
    c                    s$   d| _ || _t j|fi | d S N   )	ref_countr3   superr   )r
   base_configr3   r   	__class__r   r   r      s    zSharedObjectConfig.__init__c                 C   s&   | j dkr| j| t< |  j d7  _ d S r9   )r;   r3   SHARED_OBJECT_KEYr/   r   r   r   increment_ref_count   s    

z&SharedObjectConfig.increment_ref_count)r   r   r   r   r   rA   __classcell__r   r   r>   r   r8      s   r8   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )SharedObjectSavingScopez6Keeps track of shared object configs when serializing.c                 C   s@   t  r
d S t d ur d| _t S d| _| t_t | _d| _| S )NTFr   )	r#   r*   _passthroughr)   r%   weakrefWeakKeyDictionary_shared_objects_config_next_idr/   r   r   r   r   
  s    	

z!SharedObjectSavingScope.__enter__c              	   C   s4   z| j | }W n ttfy&   Y dS 0 |  |S )a  Gets a `SharedObjectConfig` if one has already been seen for `obj`.

        Args:
          obj: The object for which to retrieve the `SharedObjectConfig`.

        Returns:
          The SharedObjectConfig for a given object, if already seen. Else,
            `None`.
        N)rG   	TypeErrorKeyErrorrA   )r
   r4   shared_object_configr   r   r   
get_config   s    
z"SharedObjectSavingScope.get_configc                 C   s@   t || j}|  jd7  _z|| j|< W n ty:   Y n0 |S )z3Create a new SharedObjectConfig for a given object.r:   )r8   rH   rG   rI   )r
   r=   r4   rK   r   r   r   create_config5  s    z%SharedObjectSavingScope.create_configc                 O   s   t | ddsd t_d S )NrD   F)r!   r)   r%   r   r   r   r   r   C  s    z SharedObjectSavingScope.__exit__N)r   r   r   r   r   rL   rM   r   r   r   r   r   rC     s
   rC   c                 C   sV   | |d}|dur||t < t durR|durRt |}|du rNt ||S |S |S )z=Returns the serialization of the class with the given config.)
class_nameconfigN)r@   r*   rL   rM   )cls_name
cls_configr4   r   r=   rK   r   r   r    serialize_keras_class_and_configI  s    
rR   z'keras.utils.register_keras_serializableCustomc                    s    fdd}|S )a  Registers an object with the Keras serialization framework.

    This decorator injects the decorated class or function into the Keras custom
    object dictionary, so that it can be serialized and deserialized without
    needing an entry in the user-provided custom object dict. It also injects a
    function that Keras will call to get the object's serializable string key.

    Note that to be serialized and deserialized, classes must implement the
    `get_config()` method. Functions do not have this requirement.

    The object will be registered under the key 'package>name' where `name`,
    defaults to the object name if not passed.

    Example:

    ```python
    # Note that `'my_package'` is used as the `package` argument here, and since
    # the `name` argument is not provided, `'MyDense'` is used as the `name`.
    @keras.utils.register_keras_serializable('my_package')
    class MyDense(keras.layers.Dense):
      pass

    assert keras.utils.get_registered_object('my_package>MyDense') == MyDense
    assert keras.utils.get_registered_name(MyDense) == 'my_package>MyDense'
    ```

    Args:
      package: The package that this class belongs to. This is used for the
        `key` (which is 'package>name') to idenfify the class. Note that this is
        the first argument passed into the decorator.
      name: The name to serialize this class under in this package. If not
        provided or `None`, the class' name will be used (note that this is the
        case when the decorator is used with only one argument, which becomes
        the `package`).

    Returns:
      A decorator that registers the decorated class with the passed names.
    c                    s    dur n| j }d | }t| r:t| ds:td|tv rXt| dt|  | tv rvt|  dt|   | t|< |t| < | S )z9Registers a class with the Keras serialization framework.N>rL   zACannot register a class that does not have a get_config() method.z  has already been registered to )r   r   isclasshasattr
ValueErrorr   _GLOBAL_CUSTOM_NAMES)argrN   registered_namenamepackager   r   	decorator  s*    z.register_keras_serializable.<locals>.decoratorr   )r]   r\   r^   r   r[   r   register_keras_serializableb  s    )r_   zkeras.utils.get_registered_namec                 C   s   | t v rt |  S | jS dS )a  Returns the name registered to an object within the Keras framework.

    This function is part of the Keras serialization and deserialization
    framework. It maps objects to the string names associated with those objects
    for serialization/deserialization.

    Args:
      obj: The object to look up.

    Returns:
      The name associated with the object, or the default Python name if the
        object is not registered.
    N)rX   r   )r4   r   r   r   get_registered_name  s    r`   c                  c   s"   t } zda d V  W | a n| a 0 d S r,   )_SKIP_FAILED_SERIALIZATION)prevr   r   r   skip_failed_serialization  s
    rc   z!keras.utils.get_registered_objectc                 C   sP   | t jv rt j|  S | tv r$t|  S |r8| |v r8||  S |rL| |v rL||  S dS )a  Returns the class associated with `name` if it is registered with Keras.

    This function is part of the Keras serialization and deserialization
    framework. It maps strings to the objects associated with them for
    serialization/deserialization.

    Example:
    ```
    def from_config(cls, config, custom_objects=None):
      if 'my_custom_object_name' in config:
        config['hidden_cls'] = tf.keras.utils.get_registered_object(
            config['my_custom_object_name'], custom_objects=custom_objects)
    ```

    Args:
      name: The name to look up.
      custom_objects: A dictionary of custom objects to look the name up in.
        Generally, custom_objects is provided by the user.
      module_objects: A dictionary of custom objects to look the name up in.
        Generally, module_objects is provided by midlevel library implementers.

    Returns:
      An instantiable class associated with 'name', or None if no such class
        exists.
    Nr   r   r   )r\   r   module_objectsr   r   r   get_registered_object  s    

rf   c                   @   s   e Zd ZdS )CustomMaskWarningN)r   r   r   r   r   r   r   rg     s   rg   z"keras.utils.serialize_keras_objectc           
   
   C   s  t jj| \}} | du rdS t| ddp>t| do>t| j }|r^t| jr^t	j
dtdd t| drZt| j}z|  }W nF ty } z.trt|td	iW  Y d}~S |W Y d}~n
d}~0 0 i }| D ]n\}}t|tr|||< qz4t|}	t|	trt|tsd	|	d
< |	||< W q ty@   |||< Y q0 qt| j}t||| S t| drnt| S td|  ddS )a  Serialize a Keras object into a JSON-compatible representation.

    Calls to `serialize_keras_object` while underneath the
    `SharedObjectSavingScope` context manager will cause any objects re-used
    across multiple layers to be saved with a special shared object ID. This
    allows the network to be re-created properly during deserialization.

    Args:
      instance: The object to serialize.

    Returns:
      A dict-like, JSON-compatible representation of the object's config.
    Nsupports_maskingFcompute_maskzCustom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument.   )category
stacklevelrL   T__passive_serialization__r   zCannot serialize zK since it doesn't implement `get_config()`, and also doesn	 have `__name__`)tf__internal__r^   unwrapr!   rV   
is_defaultri   rL   warningswarnrg   r`   r?   NotImplementedErrorra   rR   _LAYER_UNDEFINED_CONFIG_KEYitems
isinstancestrserialize_keras_objectdictrW   )
instance_rh   r\   rO   eserialization_configkeyitemserialized_itemr   r   r   ry     s\    





ry   c                 C   s<   | t jv rt j|  S | tv r$t|  S |r8| |v r8||  S dS )zCReturns the item if it is in either local or global custom objects.Nrd   )r   r   r   r   r   get_custom_objects_by_name>  s    

r   objectc           
      C   s  t | trd| vsd| vr*td|  d| d }t|||}|du r\td| d| d| d }t |trv||fS i }| D ]j\}}	|d	kr|	||< qt |	trd
|	v rt|	||dd||< qt |	trt	t|	|rt|	|||< q| D ]\}}	|| ||< q||fS )z@Returns the class name and config for a serialized keras object.rN   rO   zImproper config format for zB. Expecting python dict contains `class_name` and `config` as keysNUnknown : . Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.r\   rm   config_item)re   r   printable_module_name)
rw   rz   rW   rf   listrv   deserialize_keras_objectrx   r   
isfunction)
rO   re   r   r   rN   clsrQ   deserialized_objectsr   r   r   r   r   ,class_and_config_for_serialized_keras_objectI  sL    



r   z$keras.utils.deserialize_keras_objectc                 C   s  | du rdS t | tr4| }t||||\}}|t}t |}|durP|S t|drt|j	}	|pli }d|	j
v r|j	|ttt ttj  t|  d}
n2t| |	|}
W d   n1 s0    Y  n@|pi }t| |f i |}
W d   n1 s0    Y  t ||
 |
S t | tr| }|r`||v r`||}nV|tjv rxtj| }n>|tv rt| }n*||}|du rtd| d| dt|r| S |S t| r| S td| d|  dS )	a  Turns the serialized form of a Keras object back into an actual object.

    This function is for mid-level library implementers rather than end users.

    Importantly, this utility requires you to provide the dict of
    `module_objects` to use for looking up the object config; this is not
    populated by default. If you need a deserialization utility that has
    preexisting knowledge of built-in Keras objects, use e.g.
    `keras.layers.deserialize(config)`, `keras.metrics.deserialize(config)`,
    etc.

    Calling `deserialize_keras_object` while underneath the
    `SharedObjectLoadingScope` context manager will cause any already-seen
    shared objects to be returned as-is rather than creating a new object.

    Args:
      identifier: the serialized form of the object.
      module_objects: A dictionary of built-in objects to look the name up in.
        Generally, `module_objects` is provided by midlevel library
        implementers.
      custom_objects: A dictionary of custom objects to look the name up in.
        Generally, `custom_objects` is provided by the end user.
      printable_module_name: A human-readable string representing the type of
        the object. Printed in case of exception.

    Returns:
      The deserialized object.

    Example:

    A mid-level library implementer might want to implement a utility for
    retrieving an object from its config, as such:

    ```python
    def deserialize(config, custom_objects=None):
       return deserialize_keras_object(
         identifier,
         module_objects=globals(),
         custom_objects=custom_objects,
         name="MyObjectType",
       )
    ```

    This is how e.g. `keras.layers.deserialize()` is implemented.
    Nfrom_configr   )r   r   r   r   zCould not interpret serialized )rw   rz   r   r1   r@   r(   rV   r   getfullargspecr   r   r   r   rv   r   r   r   r5   rx   rW   rU   r   )
identifierre   r   r   rO   r   rQ   r   shared_objectarg_specdeserialized_objobject_namer4   r   r   r   r     sr    4




	
*
.




r   c                 C   s   t jdkr2t| jdd}t|dd}nt| j}t|dd}| j	}| j
rrtdd | j
D }nd}|||fS )	zSerializes a user defined function.

    Args:
        func: the function to serialize.

    Returns:
        A tuple `(code, defaults, closure)`.
    nt   \   /base64asciic                 s   s   | ]}|j V  qd S r   )cell_contents).0cr   r   r   	<genexpr>)      zfunc_dump.<locals>.<genexpr>N)osr\   marshaldumps__code__replacecodecsencodedecode__defaults____closure__tuple)funcraw_codecodedefaultsclosurer   r   r   	func_dump  s    	
r   c              	      s   t | ttfr*| \} }}t |tr*t|}dd  |durPt fdd|D }zt| dd}W n" ttjfy   | d}Y n0 t	
|} |du rt }tj| || j||d	S )
a	  Deserializes a user defined function.

    Args:
        code: bytecode of the function.
        defaults: defaults of the function.
        closure: closure of the function.
        globs: dictionary of global objects.

    Returns:
        A function object.
    c                    s,    fdd}|j d }t t|s(|S  S )zEnsures that a value is converted to a python cell object.

        Args:
            value: Any value that needs to be casted to the cell type

        Returns:
            A value wrapped as a cell object (see function "func_load")
        c                      s     d S r   r   r   valuer   r   dummy_fnJ  s    z9func_load.<locals>.ensure_value_to_cell.<locals>.dummy_fnr   )r   rw   type)r   r   
cell_valuer   r   r   ensure_value_to_cell@  s
    

z'func_load.<locals>.ensure_value_to_cellNc                 3   s   | ]} |V  qd S r   r   )r   r|   r   r   r   r   T  r   zfunc_load.<locals>.<genexpr>r   r   raw_unicode_escape)r\   argdefsr   )rw   r   r   r   r   r   UnicodeEncodeErrorbinasciiErrorr   loadsglobalspython_typesFunctionTypeco_name)r   r   r   globsr   r   r   r   	func_load/  s"    


r   c                 C   s0   t | }|r|jdurdS ||jv p.||jv S )a  Checks if a callable accepts a given keyword argument.

    Args:
        fn: Callable to inspect.
        name: Check if `fn` can be called with `name` as a keyword argument.
        accept_all: What to return if there is no parameter called `name` but
          the function accepts a `**kwargs` argument.

    Returns:
        bool, whether `fn` accepts a `name` keyword argument.
    NT)r   r   varkwr   
kwonlyargs)fnr\   
accept_allr   r   r   r   has_arga  s    
r   zkeras.utils.Progbarc                   @   sF   e Zd ZdZdddZdd	d
ZdddZdd Zdd Zdd Z	dS )Progbara[  Displays a progress bar.

    Args:
        target: Total number of steps expected, None if unknown.
        width: Progress bar width on screen.
        verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)
        stateful_metrics: Iterable of string names of metrics that should *not*
          be averaged over time. Metrics in this list will be displayed as-is.
          All others will be averaged by the progbar before display.
        interval: Minimum visual progress update interval (in seconds).
        unit_name: Display name for step counts (usually "step" or "sample").
       r:   皙?Nstepc                 C   s   || _ || _|| _|| _|| _|r.t|| _nt | _ttj	drLtj	
 phdtjv phdtjv phdtjv | _d| _d| _i | _g | _t | _d| _| j| _d | _d | _d S )Nisatty	ipykernelposixPYCHARM_HOSTEDr   )targetwidthverboseinterval	unit_namer5   stateful_metricsrV   sysstdoutr   modulesr   environ_dynamic_display_total_width_seen_so_far_values_values_ordertime_start_last_update_time_at_epoch_start_time_at_epoch_end_time_after_first_step)r
   r   r   r   r   r   r   r   r   r   r     s0    	
zProgbar.__init__c                 C   s  |du r"| j du rd}n
|| j k}|p(g }|D ]\}}|| jvrL| j| || jvrt|| j d}|| jvr|| |g| j|< q| j| d  || 7  < | j| d  |7  < q.|dg| j|< q.|| _d}t }d|| j  }	|| j kr|| _	| j
dkr|| j | jk r|sdS | j}
| jrB|d|
 7 }|d7 }n|d	7 }| j durtt| j d }d
t| d || j f }t|| j  }t| j| }|dkr|d|d  7 }|| j k r|d7 }n|d7 }|d| j|  7 }|d7 }nd| }t|| _||7 }| ||}| j du s,|r@|	| || j7 }	nh|| j |  }|dkrxd|d |d d |d f }n(|dkrd|d |d f }nd| }d| }	| jD ]}|	d| 7 }	t| j| tr"t| j| d td| j| d  }t|dkr|	d| 7 }	n|	d| 7 }	n|	d| j|  7 }	q|  jt|	7  _|
| jkrh|	d|
| j  7 }	|rv|	d	7 }	||	7 }tj|dd d}n$| j
dkr|rtt| j d }d
t| d || j f }||	 }	| jD ]^}|	d| 7 }	t| j| d td| j| d  }|dkr2|	d| 7 }	n|	d| 7 }	q| j	r| j	| j }|| j  }|| _d| _	|	d | |d! 7 }	|	d | || j 7 }	|	d	7 }	||	7 }tj|dd d}|| _dS )"a  Updates the progress bar.

        Args:
            current: Index of current step.
            values: List of tuples: `(name, value_for_last_step)`. If `name` is
              in `stateful_metrics`, `value_for_last_step` will be displayed
              as-is. Else, an average of the metric over time will be
              displayed.
            finalize: Whether this is the last update for the progress bar. If
              `None`, defaults to `current >= self.target`.
        NFr:   r    z - %.0fs
%zd/%d [=rT   .]z%7d/Unknowni  z%d:%02d:%02d<   z%d:%02dz%dsz
 - ETA: %sz - %s:MbP?z %.4fz %.4ez %s )
line_breakrj   zd/%dz -epoch) r   r   appendr   maxr   r   r   r   r   r   r   r   r   r   intnplog10rx   floatr   len_estimate_step_duration_format_timer   rw   r   meanabsr   	print_msgr   )r
   currentvaluesfinalizekv
value_basemessagenowinfoprev_total_width	numdigitsbarprog
prog_widthtime_per_uniteta
eta_formatavgcountZtime_per_epochZavg_time_per_stepr   r   r   r     s    














 
 


zProgbar.updatec                 C   s   |  | j| | d S r   )r   r   )r
   nr   r   r   r   add>  s    zProgbar.addc                 C   s\   d}|dks|dkr&|d||f 7 }n2|dkrD|d|d |f 7 }n|d|d	 |f 7 }|S )
a  format a given duration to display to the user.

        Given the duration, this function formats it in either milliseconds
        or seconds and displays the unit (i.e. ms/step or s/epoch)
        Args:
          time_per_unit: the duration to display
          unit_name: the name of the unit to display
        Returns:
          a string with the correctly formatted duration and units
        r   r:   r   z	 %.0fs/%sr   z
 %.0fms/%sg     @@z
 %.0fus/%sg    .Ar   )r
   r  r   	formattedr   r   r   r   A  s    zProgbar._format_timec                 C   sR   |rJ| j dur*|dkr*|| j  |d  }n|| j | }|dkrF|| _ |S dS dS )a  Estimate the duration of a single step.

        Given the step number `current` and the corresponding time `now` this
        function returns an estimate for how long a single step takes. If this
        is called before one step has been completed (i.e. `current == 0`) then
        zero is given as an estimate. The duration estimate ignores the duration
        of the (assumed to be non-representative) first step for estimates when
        more steps are available (i.e. `current>1`).

        Args:
          current: Index of current step.
          now: The current time.

        Returns: Estimate of the duration of a single step.
        Nr:   r   )r   r   )r
   r   r  r  r   r   r   r   U  s    zProgbar._estimate_step_durationc                 C   s   | j || _ d S r   )r   union)r
   r   r   r   r   _update_stateful_metricsy  s    z Progbar._update_stateful_metrics)r   r:   r   Nr   )NN)N)
r   r   r   r   r   r   r  r   r   r  r   r   r   r   r   s  s        
%
 
$r   c                    s0   t tt  } fddtd|D S )zReturns a list of batch indices (tuples of indices).

    Args:
        size: Integer, total size of the data to slice into batches.
        batch_size: Integer, batch size.

    Returns:
        A list of tuples of array indices.
    c                    s&   g | ]}|  t |d    fqS )r:   )min)r   i
batch_sizesizer   r   
<listcomp>  s   z make_batches.<locals>.<listcomp>r   )r   r   ceilr   range)r  r  num_batchesr   r  r   make_batches}  s    
r   c                    s   | du rdgS t  tr6dur6td  d nt | trt drnt dr\    fdd| D S  fdd| D S t drt dr   |   S t d	r|   S dgS dS )
a  Slice an array or list of arrays.

    This takes an array-like, or a list of
    array-likes, and outputs:
        - arrays[start:stop] if `arrays` is an array-like
        - [x[start:stop] for x in arrays] if `arrays` is a list

    Can also work on list/array of indices: `slice_arrays(x, indices)`

    Args:
        arrays: Single array or list of arrays.
        start: can be an integer index (start index) or a list/array of indices
        stop: integer (stop index); should be None if `start` was a list.

    Returns:
        A slice of the array(s).

    Raises:
        ValueError: If the value of start is a list and stop is not None.
    NzQThe stop argument has to be None if the value of start is a list. Received start=z, stop=__len__shapec                    s    g | ]}|d u rd n|  qS r   r   r   x)startr   r   r    r   z slice_arrays.<locals>.<listcomp>c                    s2   g | ]*}|d u rd nt |ds"d n
|  qS )N__getitem__)rV   r#  r%  stopr   r   r    s   r&  )rw   r   rW   rV   tolist)arraysr%  r(  r   r'  r   slice_arrays  s2    


	


r+  c                 C   s   t | tr| S | gS )zNormalizes a list/tensor into a list.

    If a tensor is passed, we return
    a list of size 1 containing the tensor.

    Args:
        x: target object to be normalized.

    Returns:
        A list.
    )rw   r   )r$  r   r   r   to_list  s    
r,  c                 C   s8   t dd| }t dd| }|d dkr0|S d| S )Nz(.)([A-Z][a-z]+)z\1_\2z([a-z])([A-Z])r   r|   private)resublower)r\   intermediateinsecurer   r   r   to_snake_case  s
    r3  c                 C   s(   t j| }|D ]}|d ur dS qdS )NFT)rn   nestflatten)	structureiterableelementr   r   r   is_all_none  s
    r9  c                 C   s8   t | |}|r4td|  dt| d| d S )NzUnknown entries in z dictionary: z . Only expected following keys: )r5   keys
differencerW   r   )r\   
input_dictexpected_valuesunknownr   r   r   check_for_unexpected_keys  s    r?   Keyword argument not understood:c                 C   s    | D ]}||vrt ||qdS )zAChecks that all keyword arguments are in the set of allowed keys.N)rI   )r   allowed_kwargserror_messagekwargr   r   r   validate_kwargs  s    rD  c                 C   s   t | tot| vS )z=Determines whether config appears to be a valid layer config.)rw   rz   ru   )rO   r   r   r   validate_config  s    rE  c                 C   s
   d| _ | S )z5Decorates a method to detect overrides in subclasses.T)_is_defaultmethodr   r   r   default  s    rI  c                 C   s   t | ddS )z:Check if a method is decorated with the `default` wrapper.rF  F)r!   rG  r   r   r   rq     s    rq   c                 C   s6   |D ],}t |D ]}t||}||r|| |< qqd S r   )dirr!   )target_dictr   
obj_filtermoduler\   r4   r   r   r   !populate_dict_with_module_objects
  s
    
rN  c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )
LazyLoaderzFLazily import a module, mainly to avoid pulling in large dependencies.c                    s   || _ || _t | d S r   )_local_name_parent_module_globalsr<   r   )r
   
local_nameparent_module_globalsr\   r>   r   r   r     s    zLazyLoader.__init__c                 C   s*   t | j}|| j| j< | j|j |S )z8Load the module and insert it into the parent's globals.)	importlibimport_moduler   rQ  rP  r   r   )r
   rM  r   r   r   _load  s    zLazyLoader._loadc                 C   s   |   }t||S r   )rV  r!   )r
   r   rM  r   r   r   __getattr__%  s    zLazyLoader.__getattr__)r   r   r   r   r   rV  rW  rB   r   r   r>   r   rO    s   rO  )NN)rS   N)NN)N)NNr   )NNr   )NNN)F)NN)r@  )Mr   r   r   rT  r   r   r.  r   	threadingr   typesr   rr   rE   numpyr   tensorflow.compat.v2compatv2rn   keras.utilsr   r   r    tensorflow.python.util.tf_exportr   r   rX   ra   ru   localr   r   r   r@   r"   r&   r)   r#   r(   r*   r+   r'   r6   rz   r8   rC   rR   r_   r`   contextmanagerrc   rf   Warningrg   ry   r   r   r   r   r   r   r   r   r+  r,  r3  r9  r?  rD  rE  rI  rq   rN  
ModuleTyperO  custom_object_scoper   r   r   r   <module>   s   )
- C 
F


%
J
   
K    
2
  
4
	
 
	