B
    ӻd                 @   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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d
dG dd de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eZ'G dd deZ(G dd deZ)G dd de*Z+G d d! d!eZ,d_d"d#Z-ed$d`d&d'Z.ed(d)d* Z/ej0d+d, Z1ed-dad.d/Z2G d0d1 d1e3Z4ed2d3d4 Z5dbd5d6Z6dcd8d9Z7ed:ddd;d<Z8d=d> Z9ded?d@Z:dfdAdBZ;edCG dDdE dEeZ<dFdG Z=dgdHdIZ>dJdK Z?dLdM Z@dNdO ZAdPdQ ZBdhdSdTZCdUdV ZDdWdX ZEdYdZ ZFd[d\ ZGG d]d^ d^ejHZIeZJdS )iz#Python utilities required by Keras.    N)tf_contextlib)
tf_inspect)nest)tf_decorator)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 = layer.get_config()  # Config contains a reference to `my_regularizer`
  ...
  # 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   ]/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/utils/generic_utils.py__init__M   s    zCustomObjectScope.__init__c             C   s(   t  | _x| jD ]}t | qW | S )N)_GLOBAL_CUSTOM_OBJECTScopyr	   r   update)r
   objectsr   r   r   	__enter__Q   s    
zCustomObjectScope.__enter__c             O   s   t   t | j d S )N)r   clearr   r	   )r
   r   kwargsr   r   r   __exit__W   s    zCustomObjectScope.__exit__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   2   s   r   zkeras.utils.get_custom_objectsc               C   s   t S )a  Retrieves a live reference to the global dictionary of custom objects.

  Updating and clearing custom objects using `custom_object_scope`
  is preferred, but `get_custom_objects` can
  be used to directly access the current collection of custom objects.

  Example:

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

  Returns:
      Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`).
  )r   r   r   r   r   get_custom_objects\   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 )zBGet 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 )zBGet the current shared object saving scope in a threadsafe manner.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   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 )Nr   )r
   Zunused_object_idr   r   r   get   s    zNoopLoadingScope.getc             C   s   d S )Nr   )r
   	object_idobjr   r   r   set   s    zNoopLoadingScope.setN)r   r   r   r   r*   r-   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 )SharedObjectLoadingScopeaM  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 )N)r    r#   r"   r!   _obj_ids_to_obj)r
   r   r   r   r      s
    z"SharedObjectLoadingScope.__enter__c             C   s   |dkrdS | j |S )zGiven 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)r/   r*   )r
   r+   r   r   r   r*      s    zSharedObjectLoadingScope.getc             C   s   |dkrdS || j |< dS )z<Stores an instantiated object for future lookup and sharing.N)r/   )r
   r+   r,   r   r   r   r-      s    zSharedObjectLoadingScope.setc             O   s   t  t_d S )N)r#   r"   r!   )r
   r   r   r   r   r   r      s    z!SharedObjectLoadingScope.__exit__N)r   r   r   r   r   r*   r-   r   r   r   r   r   r.      s
   	r.   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t| j|f| d S )N   )	ref_countr+   superr0   r   )r
   base_configr+   r   )	__class__r   r   r      s    zSharedObjectConfig.__init__c             C   s&   | j dkr| j| t< |  j d7  _ d S )Nr1   )r2   r+   SHARED_OBJECT_KEY)r
   r   r   r   increment_ref_count   s    

z&SharedObjectConfig.increment_ref_count)r   r   r   r   r   r7   __classcell__r   r   )r5   r   r0      s   r0   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 k	r d| _t S d| _| t_t | _d| _| S )NTFr   )	r    r&   _passthroughr%   r!   weakrefWeakKeyDictionary_shared_objects_config_next_id)r
   r   r   r   r     s    	

z!SharedObjectSavingScope.__enter__c          	   C   s4   y| j | }W n ttfk
r&   dS X |  |S )zGets 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)r=   	TypeErrorKeyErrorr7   )r
   r,   shared_object_configr   r   r   
get_config  s    
z"SharedObjectSavingScope.get_configc             C   sB   t || j}|  jd7  _y|| j|< W n tk
r<   Y nX |S )z3Create a new SharedObjectConfig for a given object.r1   )r0   r>   r=   r?   )r
   r4   r,   rA   r   r   r   create_config-  s    z%SharedObjectSavingScope.create_configc             O   s   t | ddsd t_d S )Nr:   F)r   r%   r!   )r
   r   r   r   r   r   r   :  s    z SharedObjectSavingScope.__exit__N)r   r   r   r   r   rB   rC   r   r   r   r   r   r9      s
   r9   c             C   sV   | |d}|dk	r||t < t dk	rR|dk	rRt |}|dkrNt ||S |S |S )z=Returns the serialization of the class with the given config.)
class_nameconfigN)r6   r&   rB   rC   )cls_name
cls_configr,   r   r4   rA   r   r   r    serialize_keras_class_and_config@  s    
rH   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.

  Args:
    package: The package that this class belongs to.
    name: The name to serialize this class under in this package. If None, the
      class' name will be used.

  Returns:
    A decorator that registers the decorated class with the passed names.
  c                s    dk	r n| j }d | }t| r:t| ds:td|tkrVtd|t| f | tkrrtd| t|  f | t|< |t| < | S )z9Registers a class with the Keras serialization framework.N>rB   zACannot register a class that does not have a get_config() method.z$%s has already been registered to %s)r   r   isclasshasattr
ValueErrorr   _GLOBAL_CUSTOM_NAMES)argrD   Zregistered_name)namepackager   r   	decoratorp  s    z.register_keras_serializable.<locals>.decoratorr   )rQ   rP   rR   r   )rP   rQ   r   register_keras_serializableX  s    rS   zkeras.utils.get_registered_namec             C   s   | t k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)rN   r   )r,   r   r   r   get_registered_name  s    rT   c              c   s   t } zda d V  W d | a X d S )NT)_SKIP_FAILED_SERIALIZATION)prevr   r   r   skip_failed_serialization  s
    
rW   z!keras.utils.get_registered_objectc             C   s<   | t krt |  S |r$| |kr$||  S |r8| |kr8||  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   )rP   r   module_objectsr   r   r   get_registered_object  s    rY   c               @   s   e Zd ZdS )CustomMaskWarningN)r   r   r   r   r   r   r   rZ     s   rZ   z"keras.utils.serialize_keras_objectc       
   
   C   sn  t | \}} | dkrdS t| ddp:t| do:t| j }|rXt| jrXtjdt	d t| drLt
| j}y|  }W n8 tk
r } ztrt|tdiS |W dd}~X Y nX i }x|| D ]p\}}t|tr|||< qy4t|}	t|	trt|tsd|	d	< |	||< W q tk
r0   |||< Y qX qW t
| j}t||| S t| d
r`t
| S t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.)categoryrB   T__passive_serialization__r   zCannot serialize)r   unwrapr   rL   
is_defaultr\   rB   warningswarnrZ   rT   r5   NotImplementedErrorrU   rH   _LAYER_UNDEFINED_CONFIG_KEYitems
isinstancestrserialize_keras_objectdictrM   )
instance_r[   rP   rE   eZserialization_configkeyitemZserialized_itemr   r   r   rh     sH    




rh   c             C   s(   | t krt |  S |r$| |kr$||  S dS )zCReturns the item if it is in either local or global custom objects.N)r   )rn   r   r   r   r   get_custom_objects_by_name  s
    ro   objectc       
      C   s  t | trd| ksd| kr*tdt|  | d }t|||}|dkrVtd||| d }t |trp||fS i }xv| D ]j\}}	|dkr|	||< q~t |	trd|	krt|	||dd	||< q~t |	tr~t	
t|	|r~t|	|||< q~W x | D ]\}}	|| ||< qW ||fS )
z@Returns the class name and config for a serialized keras object.rD   rE   zImproper config format: NzUnknown {}: {}. 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.rP   r^   Zconfig_item)rX   r   printable_module_name)rf   ri   rM   rg   rY   formatlistre   deserialize_keras_objectr   
isfunction)
rE   rX   r   rq   rD   clsrG   Zdeserialized_objectsrm   rn   r   r   r   ,class_and_config_for_serialized_keras_object  s:    




	rw   z$keras.utils.deserialize_keras_objectc          	   C   s  | dkrdS t | tr| }t||||\}}|t}t |}|dk	rN|S t|drt|j	}	|pji }d|	j
kr|j	|ttt t|  d}
qt| |	|}
W dQ R X n&|pi }t| |f |}
W dQ R X t ||
 |
S t | trp| }|r"||kr"||}n8|tkr6t| }n$||}|dkrZtd||t|rl| S |S t| r| S td|| f dS )av  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   zUnknown {}: {}. 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.z%Could not interpret serialized %s: %s)rf   ri   rw   r*   r6   r$   rL   r   getfullargspecrx   r   rs   r   re   r   r-   rg   rM   rr   rK   ru   )
identifierrX   r   rq   rE   rv   rG   r   Zshared_objectarg_specZdeserialized_objZobject_namer,   r   r   r   rt   ]  sX    0











rt   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 )N)cell_contents).0cr   r   r   	<genexpr>  s    zfunc_dump.<locals>.<genexpr>N)osrP   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k	rPt fdd|D }yt| dd}W n$ ttjfk
r   | d}Y nX t	
|} |dkrt }tj| || j||d	S )
zDeserializes 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 )Nr   r   )valuer   r   dummy_fn  s    z9func_load.<locals>.ensure_value_to_cell.<locals>.dummy_fnr   )r   rf   type)r   r   Z
cell_valuer   )r   r   ensure_value_to_cell  s
    

z'func_load.<locals>.ensure_value_to_cellNc             3   s   | ]} |V  qd S )Nr   )r   rk   )r   r   r   r     s    zfunc_load.<locals>.<genexpr>r   r   Zraw_unicode_escape)rP   Zargdefsr   )rf   r   rs   r   r   r   UnicodeEncodeErrorbinasciiErrorr   loadsglobalspython_typesFunctionTypeco_name)r   r   r   Zglobsr   r   )r   r   	func_load  s     


r   c             C   s0   t | }|r|jdk	rdS ||jkp.||jkS )at  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   ry   varkwr   
kwonlyargs)fnrP   Z
accept_allr{   r   r   r   has_arg  s    
r   zkeras.utils.Progbarc               @   s>   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S )ProgbaraG  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").
     r1   皙?Nstepc             C   s   || _ || _|| _|| _|| _|r.t|| _nt | _ttj	drLtj	
 phdtjkphdtjkphdtjk| _d| _d| _i | _g | _t | _d| _d | _d S )NisattyZ	ipykernelposixZPYCHARM_HOSTEDr   )targetwidthverboseinterval	unit_namer-   stateful_metricsrL   sysstdoutr   modulesr   environ_dynamic_display_total_width_seen_so_far_values_values_ordertime_start_last_update_time_after_first_step)r
   r   r   r   r   r   r   r   r   r   r   =  s(    



zProgbar.__init__c             C   s  |dkr"| j dkrd}n
|| j k}|p(g }x|D ]\}}|| jkrN| j| || jkrt|| j d}|| jkr|| |g| j|< q| j| d  || 7  < | j| d  |7  < q0|dg| j|< q0W || _t }d|| j  }| j	dkr|| j
 | jk r|sdS | j}	| jr:tjd|	  tjd ntjd | j dk	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|| _tj| | ||}| j dks,|r|dks@|dkrT|d|| jf 7 }n8|dkrv|d|d | jf 7 }n|d|d | jf 7 }nh|| j |  }|dkrd|d |d d |d f }n(|dkrd|d |d f }nd| }d| }x| jD ]}|d| 7 }t| j| trrt| j| d td| j| d  }t|dkrd|d| 7 }n|d| 7 }n|d| j|  7 }qW |  jt|7  _|	| jkr|d |	| j  7 }|r|d7 }tj| tj  n| j	d!kr|rtt| j d }
d	t|
 d" || j f }|| }xh| jD ]^}|d| 7 }t| j| d td| j| d  }|dkr|d| 7 }n|d| 7 }q0W |d7 }tj| tj  || _
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`.
    NFr1   r   z - %.0fs
%zd/%d [=rJ   .]z%7d/Unknownz	 %.0fs/%sgMbP?z
 %.0fms/%sg     @@z
 %.0fus/%sg    .Ai  z%d:%02d:%02d<   z%d:%02dz%dsz
 - ETA: %sz - %s:z %.4fz %.4ez %s    zd/%d)r   r   appendr   maxr   r   r   r   r   r   r   r   r   r   r   writeintnplog10rg   floatr   len_estimate_step_durationr   rf   rs   Zmeanabsflush)r
   currentvaluesfinalizekvZ
value_basenowinfoZprev_total_widthZ	numdigitsbarprogZ
prog_widthtime_per_unitetaZ
eta_formatavgcountr   r   r   r   ^  s    











((

zProgbar.updatec             C   s   |  | j| | d S )N)r   r   )r
   nr   r   r   r   add  s    zProgbar.addc             C   sR   |rJ| j dk	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.
    Nr1   r   )r   r   )r
   r   r   r   r   r   r   r     s    zProgbar._estimate_step_durationc             C   s   | j || _ d S )N)r   union)r
   r   r   r   r   _update_stateful_metrics  s    z Progbar._update_stateful_metrics)r   r1   r   Nr   )NN)N)	r   r   r   r   r   r   r   r   r   r   r   r   r   r   .  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 )r1   )min)r   i)
batch_sizesizer   r   
<listcomp>  s   z make_batches.<locals>.<listcomp>r   )r   r   ceilr   range)r   r   Znum_batchesr   )r   r   r   make_batches  s    
r   c                s   | dkrdgS t  tr*dk	r*tdnt | trvt drbt drP    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 )	aq  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.
  NzAThe stop argument has to be None if the value of start is a list.__len__shapec                s    g | ]}|d krd n|  qS )Nr   )r   x)startr   r   r   6  s    z slice_arrays.<locals>.<listcomp>c                s2   g | ]*}|d krd nt |ds"d n
|  qS )N__getitem__)rL   )r   r   )r   stopr   r   r   8  s   r   )rf   rs   rM   rL   tolist)Zarraysr   r   r   )r   r   r   slice_arrays  s$    






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.
  )rf   rs   )r   r   r   r   to_listE  s    
r   c             C   s8   t dd| }t dd| }|d dkr0|S d| S )Nz(.)([A-Z][a-z0-9]+)z\1_\2z([a-z])([A-Z])r   rk   private)resublower)rP   ZintermediateZinsecurer   r   r   to_snake_caseV  s
    r   c             C   s(   t | }x|D ]}|d k	rdS qW dS )NFT)r   flatten)Z	structureiterableelementr   r   r   is_all_none`  s
    

r   c             C   s0   t | |}|r,td| t||d S )NzFUnknown entries in {} dictionary: {}. Only expected following keys: {})r-   keys
differencerM   rr   rs   )rP   Z
input_dictZexpected_valuesunknownr   r   r   check_for_unexpected_keysi  s
    r   Keyword argument not understood:c             C   s$   x| D ]}||krt ||qW dS )zAChecks that all keyword arguments are in the set of allowed keys.N)r?   )r   Zallowed_kwargserror_messagekwargr   r   r   validate_kwargsq  s    
r  c             C   s   t | tot| kS )z=Determines whether config appears to be a valid layer config.)rf   ri   rd   )rE   r   r   r   validate_configz  s    r  c             C   s
   d| _ | S )z5Decorates a method to detect overrides in subclasses.T)_is_default)methodr   r   r   default  s    r  c             C   s   t | ddS )z:Check if a method is decorated with the `default` wrapper.r	  F)r   )r
  r   r   r   r`     s    r`   c             C   s>   x8|D ]0}x*t |D ]}t||}||r|| |< qW qW d S )N)dirr   )target_dictr   Z
obj_filtermodulerP   r,   r   r   r   !populate_dict_with_module_objects  s
    

r  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t| | d S )N)_local_name_parent_module_globalsr3   r  r   )r
   Z
local_nameZparent_module_globalsrP   )r5   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   r  r  __dict__r   )r
   r  r   r   r   _load  s    zLazyLoader._loadc             C   s   |   }t||S )N)r  r   )r
   rn   r  r   r   r   __getattr__  s    zLazyLoader.__getattr__)r   r   r   r   r   r  r  r8   r   r   )r5   r   r    s   r  )NN)rI   N)NN)N)NNrp   )NNrp   )NNN)F)NN)r  )Kr   r   r   r  r   r   r   r   	threadingr   typesr   ra   r;   numpyr   Ztensorflow.python.keras.utilsr   r   Ztensorflow.python.utilr   r   Z tensorflow.python.util.tf_exportr   r   rN   rU   rd   rp   r   r   r6   localr   r"   r%   r    r$   r&   r'   r#   r.   ri   r0   r9   rH   rS   rT   contextmanagerrW   rY   WarningrZ   rh   ro   rw   rt   r   r   r   r   r   r   r   r   r   r  r  r  r  r`   r  
ModuleTyper  Zcustom_object_scoper   r   r   r   <module>   s   (- A
0$B
  
;  s
1
 Z
.
	

