B
    dN                 @   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m  m	Z
 ddlmZ ddlmZ ddlmZ edd#ddZd$d
dZdd Zd%ddZd&ddZd'ddZdd Zdd Zdd ZG dd dZedd(dd Zd!d" ZdS ))z/Utilities related to layer/model functionality.    N)initializers)io_utils)keras_exportzkeras.utils.get_source_inputsc                s   t | ds| S |dks|r&| j\}}}|js2| gS |j| }|jrPtj|jS g }xR| D ]F\}}}} t	| ||}x,|D ]$ t
 fdd|D r||  q|W q^W |S dS )a  Returns the list of input tensors necessary to compute `tensor`.

    Output will always be a list of tensors
    (potentially with 1 element).

    Args:
        tensor: The tensor to start from.
        layer: Origin layer of the tensor. Will be
            determined via tensor._keras_history if not provided.
        node_index: Origin node index of the tensor.

    Returns:
        List of input tensors.
    _keras_historyNc             3   s   | ]} |k	V  qd S )N ).0t)xr   I/var/www/html/venv/lib/python3.7/site-packages/keras/utils/layer_utils.py	<genexpr>C   s    z$get_source_inputs.<locals>.<genexpr>)hasattrr   _inbound_nodesZis_inputtfnestflattenZinput_tensorsiterate_inboundget_source_inputsallappend)Ztensorlayer
node_index_nodeZsource_tensorsZprevious_sourcesr   )r	   r
   r   !   s     


r   Fc             C   s   |r| dkrdS |r t | r dS t| tr6| |kr6dS |r>dnd}||rLdnd7 }|d| 7 }|rrd| d}nd}td| d	| d
| d| d|  
dS )z0Validates the correctness of a string-based arg.Nz`None`,  za `Callable`, z or one of the following values: zIf restoring a model and `z` is a custom callable, please ensure the callable is registered as a custom object. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. zUnkown value for `z` argument of layer z. zAllowed values are: z. Received: )callable
isinstancestr
ValueError)Z
input_dataZallowable_stringsZ
layer_namearg_name
allow_noneZallow_callablesZallowed_argsZcallable_noter   r   r
   validate_string_argH   s    	r    c             C   sR   dd | D   }dd |D }dd |D }dd |D }ttdd |D S )	zCount the total number of scalars composing the weights.

    Args:
        weights: An iterable containing the weights on which to compute params

    Returns:
        The total number of scalars composing the weights
    c             S   s   i | ]}|t |qS r   )id)r   wr   r   r
   
<dictcomp>t   s    z count_params.<locals>.<dictcomp>c             S   s   g | ]}t |d r|qS )shape)r   )r   r"   r   r   r
   
<listcomp>v   s    z count_params.<locals>.<listcomp>c             S   s   g | ]}|j  qS r   )r$   as_list)r   r"   r   r   r
   r%   w   s    c             S   s   g | ]}d d |D qS )c             S   s   g | ]}|d krdn|qS )Nr   r   )r   Zw_ir   r   r
   r%   y   s    z+count_params.<locals>.<listcomp>.<listcomp>r   )r   r"   r   r   r
   r%   y   s    c             s   s   | ]}t |V  qd S )N)npprod)r   pr   r   r
   r   {   s    zcount_params.<locals>.<genexpr>)valuesintsum)weightsZunique_weightsZweight_shapesZstandardized_weight_shapesr   r   r
   count_paramsk   s
    	r.   c                s    dk	rXt  dkr,td  dt   t d trHt d tsftd  ndt | jgS  fdd	t| jD } fd
d	t| jD }|r|std  t|t|krt|t|d gS t|t|d gS )a3  Get the layer indexes from the model based on layer names.

    The layer indexes can be used to slice the model into sub models for
    display.

    Args:
        model: `tf.keras.Model` instance.
        layer_names: a list or tuple of 2 strings, the starting layer name and
            ending layer name (both inclusive) for the result. All layers will
            be included when `None` is provided.

    Returns:
        The index value of layer based on its unique name (layer_names).
        Output will be [first_layer_index, last_layer_index + 1].
    N   zIlayer_range must be a list or tuple of length 2. Received: layer_range = z of length r      z7layer_range should contain string type only. Received: c                s&   g | ]\}}t  d  |jr|qS )r   )rematchname)r   idxr   )layer_ranger   r
   r%      s   z7get_layer_index_bound_by_layer_name.<locals>.<listcomp>c                s&   g | ]\}}t  d  |jr|qS )r0   )r1   r2   r3   )r   r4   r   )r5   r   r
   r%      s   zHPassed layer_names do not match the layer names in the model. Received: )lenr   r   r   layers	enumerateminmax)modelr5   Zlower_indexZupper_indexr   )r5   r
   #get_layer_index_bound_by_layer_name~   s&    

r<   c                s  dkrt j| jjdkr d	n| js,d	nd	| j }g }xL|D ]D}	t|	dkszt|	dkrttj	
|	d jdkrd	P ||	7 }qDW 	rx@| jD ]6}
d}x&|
jD ]}||kr|rd	P qd}qW 	sP qW 	rpdpdd	d
gd dkrfddD dddg}njp"dp4dddd
gd dkrVfddD ddddg}g x| j D ]}	|	7 qrW 
rd7  |d t| |}d*fdd	d| j d d  | d  d+
fdd 	d,
fd!d"	d- 	fd#d$	x(| j|d |d  D ]}
|
 qJW d  t| d%rt| j}n
t| j}t| j}d&|| d' d(|d' d)|d' d  dS ).a  Prints a summary of a model.

    Args:
        model: Keras model instance.
        line_length: Total length of printed lines
            (e.g. set this to adapt the display to different
            terminal window sizes).
        positions: Relative or absolute positions of log elements in each line.
            If not provided, defaults to `[.33, .55, .67, 1.]`.
        print_fn: Print function to use.
            It will be called on each line of the summary.
            You can set it to a custom function
            in order to capture the string summary.
            It defaults to `print` (prints to stdout).
        expand_nested: Whether to expand the nested models.
            If not provided, defaults to `False`.
        show_trainable: Whether to show if a layer is trainable.
            If not provided, defaults to `False`.
        layer_range: List or tuple containing two strings,
            the starting layer name and ending layer name (both inclusive),
            indicating the range of layers to be printed in the summary. The
            strings could also be regexes instead of an exact name. In this
             case, the starting layer will be the first layer that matches
            `layer_range[0]` and the ending layer will be the last element that
            matches `layer_range[1]`. By default (`None`) all
            layers in the model are included in the summary.
    NZ
SequentialTr0   r   FA   g?g333333?g      ?c                s   g | ]}t  | qS r   )r+   )r   r)   )line_lengthr   r
   r%     s    z!print_summary.<locals>.<listcomp>zLayer (type)zOutput ShapezParam #b   gQ?g?gq=
ףp?c                s   g | ]}t  | qS r   )r+   )r   r)   )r?   r   r
   r%     s    zConnected to   Z	Trainablec                s^  dd | D }xHt |rXd}xtt|D ]}|dkrL||d  }nd}|| }|t|d krldnd}|| | }	|| d |	  d}
 fdd|
D }|rt|}	 d |	  |dkr|d	| d
 7 }| 7 }||rd
| nd7 }|| |	d  ||< |r&|d
|| t| |  7 }q0|d
|| t|  7 }q0W |d	| 7 }| qW d S )Nc             S   s   g | ]}t |qS r   )r   )r   r	   r   r   r
   r%     s    z4print_summary.<locals>.print_row.<locals>.<listcomp>r   r   r0   r/   )z),z},z],z',c                s,   g | ]$}  |d kr  |t| qS )r   )findr6   )r   r	   )fit_into_liner   r
   r%   )  s   | )anyranger6   r9   )fields	positionsnested_levelZleft_to_printlinecol	start_posend_posspacecutoffZline_break_conditionsZcandidate_cutoffs)print_fn)rC   r
   	print_row  s6    
z print_summary.<locals>.print_rowzModel: ""r   =c                s   y
| j }W n. tk
r"   d}Y n tk
r8   d}Y nX | j}| jj}| js`t| dds`d}n|  }|d | d ||g}r|	| j
rdnd	 | | d
S )zPrints a summary for a single layer.

        Args:
            layer: target layer.
            nested_level: level of nesting of the layer inside its parent layer
              (e.g. 0 for a top-level layer, 1 for a nested layer).
        multiple?_is_graph_networkFz
0 (unused)z ()YNN)output_shapeAttributeErrorRuntimeErrorr3   	__class____name__Zbuiltgetattrr.   r   	trainable)r   rJ   r[   r3   cls_nameparamsrH   )rI   rR   show_trainabler   r
   print_layer_summaryD  s    

z*print_summary.<locals>.print_layer_summaryc          
      s   y
| j }W n tk
r"   d}Y nX g }xT| jD ]J}rB|krBq0x6| D ]*\}}}}||j d| d| d qLW q0W | j}	| jj}
|	d |
 d ||  |g}r|| j	rdnd | | d	S )
a  Prints a summary for a single layer (including topological connections).

        Args:
            layer: target layer.
            nested_level: level of nesting of the layer inside its parent layer
              (e.g. 0 for a top-level layer, 1 for a nested layer).
        rU   [z][]z (rX   rY   rZ   N)
r[   r\   r   r   r   r3   r^   r_   r.   ra   )r   rJ   r[   connectionsr   Zinbound_layerr   Ztensor_indexr   r3   rb   rH   )rI   rR   relevant_nodesrd   r   r
   $print_layer_summary_with_connectionsb  s*    

"z;print_summary.<locals>.print_layer_summary_with_connectionsc                s   r| | n
| |  rt | dr| jrʈd|d  dd|  d   d|d    | j}d}x<tt|D ],}|t|d krd}|| |d | qvW d| dd|    d|   |sd| dd|    d|   d S )	Nr7   rD   r0      ¯r/   FTrE   )r   r7   rG   r6   )r   rJ   Zis_nested_lastZnested_layeri)expand_nestedr?   rQ   print_layerre   rj   sequential_liker   r
   rn     s"    
."z"print_summary.<locals>.print_layer_collected_trainable_weightszTotal params: ,zTrainable params: zNon-trainable params: )r   )r   )r   )r   F)r   Z	print_msgr^   r_   rW   Z_nodes_by_depthr*   r6   r   r   r   Zkeras_inputsr7   r   r   r<   r3   r   r.   rp   Ztrainable_weightsZnon_trainable_weights)r;   r?   rI   rQ   rm   rd   r5   Znodes_by_depthZnodesvr   flagr   
to_displayZtrainable_countZnon_trainable_countr   )rm   r?   rI   rQ   rn   re   rj   rR   ri   ro   rd   r
   print_summary   s    $

&



)
*!

ru   channels_firstc             C   s   |dkst |  \}}xt|jd D ]}|dkrl|\}}}|||f}	|dd|f |	}
t|
d}
n6|\}}}|||f}	|dd|f |	}
t|
d}
t|
t|f|dd|f< q(W | ||g dS )a]  Utility useful when changing a convnet's `data_format`.

    When porting the weights of a convnet from one data format to the other,
    if the convnet includes a `Flatten` layer
    (applied to the last convolutional feature map)
    followed by a `Dense` layer, the weights of that `Dense` layer
    should be updated to reflect the new dimension ordering.

    Args:
        dense: The target `Dense` layer.
        previous_feature_map_shape: A shape tuple of 3 integers,
            e.g. `(512, 7, 7)`. The shape of the convolutional
            feature map right before the `Flatten` layer that
            came before the target `Dense` layer.
        target_data_format: One of "channels_last", "channels_first".
            Set it "channels_last"
            if converting a "channels_first" model to "channels_last",
            or reciprocally.
    >   rv   channels_lastr0   rv   N)r/   r   r0   )r0   r/   r   )	AssertionErrorZget_weightsrG   r$   Zreshaper'   Z	transposer(   Zset_weights)ZdenseZprevious_feature_map_shapeZtarget_data_formatZkernelZbiasrl   chr"   Zoriginal_fm_shapeZkir   r   r
   !convert_dense_weights_data_format  s    



$r{   c             C   s$   t | dd sdS | jdko"| jdkS )N_keras_api_namesF)zkeras.layers.Layer)r`   r|   Z_keras_api_names_v1)r   r   r   r
   is_builtin_layer  s
    r}   c                s*   t   t fdd} |_|S )a
  Lightweight decorator for caching lazily constructed properties.

    When to use:
    This decorator provides simple caching with minimal overhead. It is designed
    for properties which are expensive to compute and static over the life of a
    class instance, and provides no mechanism for cache invalidation. Thus it is
    best suited for lazily exposing derived properties of other static data.

    For classes with custom getattr / setattr behavior (such as trackable
    objects), storing cache results as object attributes is not performant.
    Instead, a specialized cache can significantly reduce property lookup
    overhead. (While still allowing the decorated property to be lazily
    computed.) Consider the following class:

    ```
    class MyClass:
      def __setattr__(self, key, value):
        # Some expensive class specific code
        # ...
        # ...

        super(MyClass, self).__setattr__(key, value)

      @property
      def thing(self):
        # `thing` is expensive to compute (and may not even be requested), so we
        # want to lazily compute it and then cache it.
        output = getattr(self, '_thing', None)
        if output is None:
          self._thing = output = compute_thing(self)
        return output
    ```

    It's also worth noting that ANY overriding of __setattr__, even something as
    simple as:
    ```
      def __setattr__(self, key, value):
        super(MyClass, self).__setattr__(key, value)
    ```

    Slows down attribute assignment by nearly 10x.

    By contrast, replacing the definition of `thing` with the following
    sidesteps the expensive __setattr__ altogether:

    '''
    @property
    @tracking.cached_per_instance
    def thing(self):
      # `thing` is expensive to compute (and may not even be requested), so we
      # want to lazily compute it and then cache it.
      return compute_thing(self)
    '''

    Performance:
    The overhead for this decorator is ~0.4 us / call. A much lower overhead
    implementation (~0.085 us / call) can be achieved by using a custom dict
    type:

    ```
    def dict_based_cache(f):
      class Cache(dict):
        __slots__ = ()
        def __missing__(self, key):
          self[key] = output = f(key)
          return output

      return property(Cache().__getitem__)
    ```

    However, that implementation holds class instances as keys, and as a result
    blocks garbage collection. (And modifying it to use weakref's as keys raises
    the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary
    implementation below turns out to be more prudent.

    Args:
      f: The function to cache.

    Returns:
      f decorated with simple caching behavior.
    c                s&     | }|d kr"|   | < }|S )N)get)itemoutput)cachefr   r
   wrappedE  s    
z$cached_per_instance.<locals>.wrapped)weakrefWeakKeyDictionary	functoolswrapsr   )r   r   r   )r   r   r
   cached_per_instance  s    Sr   c             c   s   t  }| ddd }xl|r| }t||kr0q|t| t|drZt|tsZ|V  qt|ddphg }||ddd  qW dS )z4Filter out empty Layer-like containers and uniquify.Nr>   Z	_is_layerr7   )	setpopr!   addr   r   typer`   extend)Z
layer_listexistingZto_visitobjZ
sub_layersr   r   r
   filter_empty_layer_containersP  s    r   c               @   s   e Zd ZdZdd Zedd Zedd Zejdd Zee	d	d
 Z
edd Zejdd Zedd Zejdd Zedd ZdddZdddZdddZdd ZdS ) CallFunctionSpeczKCaches the spec and provides utilities for handling call function
    args.c             C   s   || _ t| j j| _| jr8| jd dkr8| jdd | _|  j| j jpHg 7  _| j jdk	}d| jkpf|| _d| jkpv|| _| j jpg }t	 }x,t
dt| dD ]}|| || j| < qW || j jpi  |d| _dS )zInitialies a `CallFunctionSpec`.

        Args:
          full_argspec: the FullArgSpec of a call function of a layer.
        r   selfr0   NZtrainingmaskr>   )_full_argspeclistargs
_arg_names
kwonlyargsvarkw_expects_training_arg_expects_mask_argdefaultsdictrG   r6   updatekwonlydefaultsr~   _default_training_arg)r   full_argspecZcall_accepts_kwargsZcall_fn_defaultsr   rl   r   r   r
   __init__h  s    zCallFunctionSpec.__init__c             C   s   | j S )z-Returns the FullArgSpec of the call function.)r   )r   r   r   r
   r     s    zCallFunctionSpec.full_argspecc             C   s   | j S )z%List of names of args and kwonlyargs.)r   )r   r   r   r
   	arg_names  s    zCallFunctionSpec.arg_namesc             C   s
   || _ d S )N)r   )r   valuer   r   r
   r     s    c             C   s*   t  }xt| jD ]\}}|||< qW |S )z:Returns a dict mapping arg names to their index positions.)r   r8   r   )r   Zcall_fn_arg_positionsposargr   r   r
   arg_positions  s    zCallFunctionSpec.arg_positionsc             C   s   | j S )z9Whether the call function uses 'training' as a parameter.)r   )r   r   r   r
   expects_training_arg  s    z%CallFunctionSpec.expects_training_argc             C   s
   || _ d S )N)r   )r   r   r   r   r
   r     s    c             C   s   | j S )z5Whether the call function uses `mask` as a parameter.)r   )r   r   r   r
   expects_mask_arg  s    z!CallFunctionSpec.expects_mask_argc             C   s
   || _ d S )N)r   )r   r   r   r   r
   r     s    c             C   s   | j S )z3The default value given to the "training" argument.)r   )r   r   r   r
   default_training_arg  s    z%CallFunctionSpec.default_training_argFc             C   s@   |s|sdS ||krdS | j }|s.|dd }|tt||kS )a  Returns true if argument is present in `args` or `kwargs`.

        Args:
          arg_name: String name of the argument to find.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.

        Returns:
          True if argument with `arg_name` is present in `args` or `kwargs`.
        FTr0   N)r   r   zip)r   r   r   kwargsinputs_in_argscall_fn_argsr   r   r
   arg_was_passed  s    zCallFunctionSpec.arg_was_passedc             C   s<   ||kr|| S | j }|s&|dd }tt||}|| S )ak  Retrieves the value for the argument with name `arg_name`.

        Args:
          arg_name: String name of the argument to find.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.

        Returns:
          The value of the argument with name `arg_name`, extracted from `args`
          or `kwargs`.

        Raises:
          KeyError if the value of `arg_name` cannot be found.
        r0   N)r   r   r   )r   r   r   r   r   r   Z	args_dictr   r   r
   get_arg_value  s    zCallFunctionSpec.get_arg_valuec             C   s   | j jrNy*| j j|}| j jd dkr0|d8 }W q\ tk
rJ   d}Y q\X n| j|d}|dk	r|sp|d }t||krt|}|||< t	||fS |dkr|r|
|d n|||< ||fS )a  Sets the value of an argument into the given args/kwargs.

        Args:
          arg_name: String name of the argument to find.
          new_value: New value to give to the argument.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.
          pop_kwarg_if_none: If the new value is `None`, and this is `True`,
            then the argument is deleted from `kwargs`.

        Returns:
          The updated `(args, kwargs)`.
        r   r   r0   N)r   varargsr   indexr   r   r~   r6   r   tupler   )r   r   	new_valuer   r   r   Zpop_kwarg_if_noneZarg_posr   r   r
   set_arg_value  s&    zCallFunctionSpec.set_arg_valuec             C   sV   |r|d }|dd }n2| j d |krDt|}|| j d }ntd|||fS )z2Splits (args, kwargs) into (inputs, args, kwargs).r   r0   Nz9The first argument to `Layer.call` must always be passed.)r   copyr   r   )r   r   r   inputsr   r   r
   split_out_first_arg  s    
z$CallFunctionSpec.split_out_first_argN)F)F)FF)r_   
__module____qualname____doc__r   propertyr   r   setterr   r   r   r   r   r   r   r   r   r   r   r   r
   r   d  s"   !


  
)r   z&keras.utils.warmstart_embedding_matrixuniformc             C   s   t | } t |}t|}|t||jd f|jd}tt| tt| }g }g }x8t	|D ],\}}	|	|kr^|
||	  |
t| q^W |rt||}
t|tj|dd|
}|S )aY  Warm start embedding matrix with changing vocab.

    This util can be used to warmstart the embedding layer matrix when
    vocabulary changes between previously saved checkpoint and model.
    Vocabulary change could mean, the size of the new vocab is different or the
    vocabulary is reshuffled or new vocabulary has been added to old vocabulary.
    If the vocabulary size changes, size of the embedding layer matrix also
    changes. This util remaps the old vocabulary embeddings to the new embedding
    layer matrix.

    Example:
    Here is an example that demonstrates how to use the
    `warmstart_embedding_matrix` util.
    >>> import keras
    >>> vocab_base = tf.convert_to_tensor(["unk", "a", "b", "c"])
    >>> vocab_new = tf.convert_to_tensor(
    ...        ["unk", "unk", "a", "b", "c", "d", "e"])
    >>> vectorized_vocab_base = np.random.rand(vocab_base.shape[0], 3)
    >>> vectorized_vocab_new = np.random.rand(vocab_new.shape[0], 3)
    >>> warmstarted_embedding_matrix = warmstart_embedding_matrix(
    ...       base_vocabulary=vocab_base,
    ...       new_vocabulary=vocab_new,
    ...       base_embeddings=vectorized_vocab_base,
    ...       new_embeddings_initializer=keras.initializers.Constant(
    ...         vectorized_vocab_new))

    Here is an example that demonstrates how to get vocabulary and embedding
    weights from layers, use the `warmstart_embedding_matrix` util to remap the
    layer embeddings and continue with model training.
    ```
    # get old and new vocabulary by using layer.get_vocabulary()
    # for example assume TextVectorization layer is used
    base_vocabulary = old_text_vectorization_layer.get_vocabulary()
    new_vocabulary = new_text_vectorization_layer.get_vocabulary()
    # get previous embedding layer weights
    embedding_weights_base = model.get_layer('embedding').get_weights()[0]
    warmstarted_embedding = keras.utils.warmstart_embedding_matrix(
                                  base_vocabulary,
                                  new_vocabulary,
                                  base_embeddings=embedding_weights_base,
                                  new_embeddings_initializer="uniform")
    updated_embedding_variable = tf.Variable(warmstarted_embedding)

    # update embedding layer weights
    model.layers[1].embeddings = updated_embedding_variable
    model.fit(..)
    # continue with model training

    ```

    Args:
        base_vocabulary: The list of vocabulary terms that
          the preexisting embedding matrix `base_embeddings` represents.
          It can be either a 1D array/tensor or a tuple/list of vocabulary
          terms (strings), or a path to a vocabulary text file. If passing a
           file path, the file should contain one line per term in the
           vocabulary.
        new_vocabulary: The list of vocabulary terms for the new vocabulary
           (same format as above).
        base_embeddings: NumPy array or tensor representing the preexisting
          embedding matrix.
        new_embeddings_initializer: Initializer for embedding vectors for
          previously unseen terms to be added to the new embedding matrix (see
          `keras.initializers`). Defaults to "uniform". new_embedding matrix
          needs to be specified with "constant" initializer.
          matrix. Default value is None.

    Returns:
      tf.tensor of remapped embedding layer matrix

    r0   )r$   dtype)Zaxis)convert_vocab_to_listr   r~   r6   r$   r   r   r   rG   r8   r   r+   r   gatherZtensor_scatter_nd_updateZexpand_dims)Zbase_vocabularyZnew_vocabularyZbase_embeddingsZnew_embeddings_initializerZnew_embeddingZbase_vocabulary_dictZindices_base_vocabularyZindices_new_vocabularyr   keyZvalues_to_updater   r   r
   warmstart_embedding_matrix/  s*    O

r   c          	   C   s   g }t | rt|  }nt| tjttfr8t| }nft| trt j	j
| s`td|  dt j	j
| d}|  }W dQ R X ntdt|  dt|dkrtd|S )	z!Convert input vacabulary to list.zVocabulary file z does not exist.rNzkVocabulary is expected to be either a NumPy array, list, 1D tensor or a vocabulary text file. Instead type z was received.r   zVocabulary is expected to be either a NumPy array, list, 1D tensor or a vocabulary text file with at least one token. Received 0 instead.)r   Z	is_tensorr   numpyr   r'   Zndarrayr   r   ioZgfileexistsr   ZGFileread
splitlinesr   r6   )ZvocabZ
vocab_listZvocabulary_filer   r   r
   r     s     


r   )NN)FF)N)NNNFFN)rv   )r   )r   r   r   r1   r   r   r'   Ztensorflow.compat.v2compatZv2r   Zkerasr   Zkeras.utilsr   Z tensorflow.python.util.tf_exportr   r   r    r.   r<   ru   r{   r}   r   r   r   r   r   r   r   r   r
   <module>   s@   + 

8     
  
&` Lk