a
    SicyD                  
   @   s   d 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 dd	lmZ dd
lmZ ddlmZ dd ZedG dd de
jZeddejdddZdS )z,Input layer code (`Input` and `InputLayer`).    N)backend)distributed_training_utils)
base_layer)keras_tensor)node)layer_serialization)tf_utils)traceback_utils)keras_exportc                 C   s   |d urt d|  d S )Nz\When `type_spec` is not None, all other args except `name` must be None, but %s is not None.)
ValueError)arg_namearg r   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/engine/input_layer.py_assert_other_arg_none!   s    r   zkeras.layers.InputLayerc                	       s<   e Zd ZdZejd	 fdd	Zdd Zedd Z	  Z
S )

InputLayera
  Layer to be used as an entry point into a Network (a graph of layers).

    It can either wrap an existing tensor (pass an `input_tensor` argument)
    or create a placeholder tensor (pass arguments `input_shape`, and
    optionally, `dtype`).

    It is generally recommend to use the Keras Functional model via `Input`,
    (which creates an `InputLayer`) without directly using `InputLayer`.

    When using `InputLayer` with the Keras Sequential model, it can be skipped
    by moving the `input_shape` parameter to the first layer after the
    `InputLayer`.

    This class can create placeholders for `tf.Tensors`, `tf.SparseTensors`, and
    `tf.RaggedTensors` by choosing `sparse=True` or `ragged=True`. Note that
    `sparse` and `ragged` can't be configured to `True` at the same time.
    Usage:

    ```python
    # With explicit InputLayer.
    model = tf.keras.Sequential([
      tf.keras.layers.InputLayer(input_shape=(4,)),
      tf.keras.layers.Dense(8)])
    model.compile(tf.keras.optimizers.RMSprop(0.001), loss='mse')
    model.fit(np.zeros((10, 4)),
              np.ones((10, 8)))

    # Without InputLayer and let the first layer to have the input_shape.
    # Keras will add a input for the model behind the scene.
    model = tf.keras.Sequential([
      tf.keras.layers.Dense(8, input_shape=(4,))])
    model.compile(tf.keras.optimizers.RMSprop(0.001), loss='mse')
    model.fit(np.zeros((10, 4)),
              np.ones((10, 8)))
    ```

    Args:
        input_shape: Shape tuple (not including the batch axis), or
            `TensorShape` instance (not including the batch axis).
        batch_size: Optional input batch size (integer or `None`).
        dtype: Optional datatype of the input. When not provided, the Keras
            default `float` type will be used.
        input_tensor: Optional tensor to use as layer input. If set, the layer
            will use the `tf.TypeSpec` of this tensor rather
            than creating a new placeholder tensor.
        sparse: Boolean, whether the placeholder created is meant to be sparse.
            Default to `False`.
        ragged: Boolean, whether the placeholder created is meant to be ragged.
            In this case, values of `None` in the `shape` argument represent
            ragged dimensions. For more information about `tf.RaggedTensor`, see
            [this guide](https://www.tensorflow.org/guide/ragged_tensor).
            Default to `False`.
        type_spec: A `tf.TypeSpec` object to create Input from. This
            `tf.TypeSpec` represents the entire batch. When provided, all other
            args except name must be `None`.
        name: Optional name of the layer (string).
    Nc	                    s  || _ || _|| _|| _|| _|| _tj }
|
rn|d urnt	
|
rn||
j dkrdtd||
j||
j }d|	v r|	d}|r|rtd|r|d }|dd  }|	rtdt|	  |r|rtd|sd}|d	 tt| }|s|d u r
t }n
t|}n,|d urB|j|krBtd
|j d| t j||d d| _|rbdnd| _|rrdnd| _|| _d| _t|tjrt|  }nt|t!r|f}|d urd| j fd| jfd| jfd|fd| jfd| jfg}|D ]\}}t"|| qtj#j$% stdt&'|}t|t&j(r<d| _t|t&j)rPd| _d| _*zt|j+  | _,W n ty   d | _,Y n0 n|d u r|d ur|ft| }nd }t- }|. & tj/||| j0||d}W d    n1 s0    Y  d| _*|| _,nrtj#j$% r.t|t&j1sBt&2|}nt34|sBtdd| _*zt|j+  | _,W n tyv   d | _,Y n0 d |_5t6j7| |d t|t&j1st38|r|j9| _9ntj:|j+|j| j0d| _9d S )Nr   zOThe `batch_size` argument ({}) must be divisible by the number of replicas ({})batch_input_shapezdOnly provide the input_shape OR batch_input_shape argument to InputLayer, not both at the same time.    Unrecognized keyword arguments: z;Cannot set both sparse and ragged to True in a Keras input.input_zH`input_tensor.dtype` differs from `dtype`. Received: input_tensor.dtype=z but expected dtype=)dtypenameTFz(input_)shape
batch_sizer   input_tensorsparseraggedzYCreating Keras inputs from a type_spec is only supported when eager execution is enabled.)shaper   r   r   r   zYou should not pass an EagerTensor to `Input`. For example, instead of creating an `InputLayer`, you should instantiate your model and directly call it on your input.)layeroutputs)r   r   r   );_init_input_shape_init_batch_size_init_dtype_init_sparse_init_ragged_init_type_spectf
distributeget_strategyr   global_batch_size_supportednum_replicas_in_syncr   formatpoplistkeysstrr   get_uidfloatxr   super__init__builtr   r   r   supports_masking
isinstanceTensorShapetupleas_listintr   compatv1#executing_eagerly_outside_functionsr   keras_tensor_from_type_specSparseKerasTensorRaggedKerasTensoris_placeholderr   _batch_input_shape	get_graph
as_defaultplaceholderr   KerasTensorkeras_tensor_from_tensorr   is_symbolic_tensor_keras_masknode_moduleNodeis_extension_type
_type_spec
TensorSpec)selfinput_shaper   r   r   r   r   r   	type_speckwargsstrategyr   prefixargs_that_must_be_noner   r   graph	__class__r   r   r3   f   s    









&
zInputLayer.__init__c                 C   s8   | j d ur| j| j d}n| j| j| j| j| jd}|S )N)r   rQ   )r   r   r   r   r   )r%   r   rB   r   r   r   )rO   configr   r   r   
get_config  s    
zInputLayer.get_configc                 C   s
   t | S )N)r   InputLayerSavedModelSaver)rO   r   r   r   _trackable_saved_model_saver  s    z'InputLayer._trackable_saved_model_saver)NNNNNNNN)__name__
__module____qualname____doc__r	   filter_tracebackr3   rZ   propertyr\   __classcell__r   r   rW   r   r   *   s   :         (r   zkeras.Inputzkeras.layers.Inputc                 K   s   |r|rt d||||||d}	|d|dd}
| durN|
durNt d|
du rv| du rv|du rv|du rvt d|rt dt|  |
r|
d	d } |	d|
i n|	|| d
 tf i |	}|jd j}t|trt	|d	kr|d S |S dS )a  `Input()` is used to instantiate a Keras tensor.

    A Keras tensor is a symbolic tensor-like object, which we augment with
    certain attributes that allow us to build a Keras model just by knowing the
    inputs and outputs of the model.

    For instance, if `a`, `b` and `c` are Keras tensors,
    it becomes possible to do:
    `model = Model(input=[a, b], output=c)`

    Args:
        shape: A shape tuple (integers), not including the batch size.
            For instance, `shape=(32,)` indicates that the expected input
            will be batches of 32-dimensional vectors. Elements of this tuple
            can be None; 'None' elements represent dimensions where the shape is
            not known.
        batch_size: optional static batch size (integer).
        name: An optional name string for the layer.
            Should be unique in a model (do not reuse the same name twice).
            It will be autogenerated if it isn't provided.
        dtype: The data type expected by the input, as a string
            (`float32`, `float64`, `int32`...)
        sparse: A boolean specifying whether the placeholder to be created is
            sparse. Only one of 'ragged' and 'sparse' can be True. Note that,
            if `sparse` is False, sparse tensors can still be passed into the
            input - they will be densified with a default value of 0.
        tensor: Optional existing tensor to wrap into the `Input` layer.
            If set, the layer will use the `tf.TypeSpec` of this tensor rather
            than creating a new placeholder tensor.
        ragged: A boolean specifying whether the placeholder to be created is
            ragged. Only one of 'ragged' and 'sparse' can be True. In this case,
            values of 'None' in the 'shape' argument represent ragged
            dimensions.  For more information about RaggedTensors, see
            [this guide](https://www.tensorflow.org/guide/ragged_tensor).
        type_spec: A `tf.TypeSpec` object to create the input placeholder from.
            When provided, all other args except name must be None.
        **kwargs: deprecated arguments support. Supports `batch_shape` and
            `batch_input_shape`.

    Returns:
      A `tensor`.

    Example:

    ```python
    # this is a logistic regression in Keras
    x = Input(shape=(32,))
    y = Dense(16, activation='softmax')(x)
    model = Model(x, y)
    ```

    Note that even if eager execution is enabled,
    `Input` produces a symbolic tensor-like object (i.e. a placeholder).
    This symbolic tensor-like object can be used with lower-level
    TensorFlow ops that take tensors as inputs, as such:

    ```python
    x = Input(shape=(32,))
    y = tf.square(x)  # This op will be treated like a layer
    model = Model(x, y)
    ```

    (This behavior does not work for higher-order TensorFlow APIs such as
    control flow and being directly watched by a `tf.GradientTape`).

    However, the resulting model will not track any variables that were
    used as inputs to TensorFlow ops. All variable usages must happen within
    Keras layers to make sure they will be tracked by the model's weights.

    The Keras Input can also create a placeholder from an arbitrary
    `tf.TypeSpec`, e.g:

    ```python
    x = Input(type_spec=tf.RaggedTensorSpec(shape=[None, None],
                                            dtype=tf.float32, ragged_rank=1))
    y = x.values
    model = Model(x, y)
    ```
    When passing an arbitrary `tf.TypeSpec`, it must represent the signature of
    an entire batch instead of just one example.

    Raises:
      ValueError: If both `sparse` and `ragged` are provided.
      ValueError: If both `shape` and (`batch_input_shape` or `batch_shape`) are
        provided.
      ValueError: If `shape`, `tensor` and `type_spec` are None.
      ValueError: If arguments besides `type_spec` are non-None while
        `type_spec` is passed.
      ValueError: if any unrecognized parameters are provided.
    zCCannot set both `sparse` and `ragged` to `True` in a Keras `Input`.)r   r   r   r   r   rQ   r   batch_shapeNz]Only provide the `shape` OR `batch_input_shape` argument to Input, not both at the same time.zPlease provide to Input a `shape` or a `tensor` or a `type_spec` argument. Note that `shape` does not include the batch dimension.r   r   )r   rP   r   )
r   r,   r-   r.   updater   _inbound_nodesr   r6   len)r   r   r   r   r   tensorr   rQ   rR   input_layer_configr   input_layerr   r   r   r   Input   sX    g	rk   )NNNNNNNN)r`   tensorflow.compat.v2r;   v2r&   kerasr   Zkeras.distributer   keras.enginer   r   r   rJ   keras.saving.saved_modelr   keras.utilsr   r	    tensorflow.python.util.tf_exportr
   r   Layerr   ra   rk   r   r   r   r   <module>   s2   	 v        