o
    #j;                     @   s   d dl Z d dlZd dlZd dlmZmZ d dlmZ d dl	m
Z
mZmZ d dlmZ d dlmZ ddlmZ g Zd	efd
dZedddZG dd dZdd ZdS )    N)Variablecore)
check_type)convert_np_dtype_to_dtype_in_pir_modestatic_only)LayerHelper)DataType   _setitem_staticreturnc                 C   s   t |  dvS )N)falseoff0none)strlower)val r   T/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/static/input.pyevaluate_flag#   s   r   c           
   
   C   sF  dd }t di t }t| dttfd t|dttfd t|}tt|D ]}|| du r4d||< q(|du r=t	
 }t rc|}t|tsNt	jj|}|  t	j| ||t }t	j  |S |j| ||tjjjd|ddd	}tjd
d}	t|	rt di t }t|tjjst|}|jdi d|i||d| dd |S )a_  

    This function creates a variable on the global block. The global variable
    can be accessed by all the following operators in the graph. The variable
    is a placeholder that could be fed with input, such as Executor can feed
    input into the variable. When `dtype` is None, the dtype
    will get from the global dtype by `paddle.get_default_dtype()`.

    Args:
       name (str): The name/alias of the variable, see :ref:`api_guide_Name`
           for more details.
       shape (list|tuple): List|Tuple of integers declaring the shape. You can
           set None or -1 at a dimension to indicate the dimension can be of any
           size. For example, it is useful to set changeable batch size as None or -1.
       dtype (np.dtype|str, optional): The type of the data. Supported
           dtype: bool, float16, float32, float64, int8, int16, int32, int64,
           uint8. Default: None. When `dtype` is not set, the dtype will get
           from the global dtype by `paddle.get_default_dtype()`.
       lod_level (int, optional): The LoD level of the LoDTensor. Usually users
           don't have to set this value. Default: 0.

    Returns:
        Variable: The global variable that gives access to the data.

    Examples:
        .. code-block:: python

            >>> import numpy as np
            >>> import paddle
            >>> paddle.enable_static()

            # Creates a variable with fixed size [3, 2, 1]
            # User can only feed data of the same shape to x
            # the dtype is not set, so it will set "float32" by
            # paddle.get_default_dtype(). You can use paddle.get_default_dtype() to
            # change the global dtype
            >>> x = paddle.static.data(name='x', shape=[3, 2, 1])

            # Creates a variable with changeable batch size -1.
            # Users can feed data of any batch size into y,
            # but size of each data sample has to be [2, 1]
            >>> y = paddle.static.data(name='y', shape=[-1, 2, 1], dtype='float32')

            >>> z = x + y

            # In this example, we will feed x and y with np-ndarray "1"
            # and fetch z, like implementing "1 + 1 = 2" in PaddlePaddle
            >>> feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32)

            >>> exe = paddle.static.Executor(paddle.framework.CPUPlace())
            >>> out = exe.run(paddle.static.default_main_program(),
            ...             feed={
            ...                 'x': feed_data,
            ...                 'y': feed_data
            ...             },
            ...             fetch_list=[z.name])

            # np-ndarray of shape=[3, 2, 1], dtype=float32, whose elements are 2
            >>> print(out)
            [array([[[2.],
                    [2.]],
                [[2.],
                    [2.]],
                [[2.],
                    [2.]]], dtype=float32)]

    c                  S   sR   t jj } |  j}t|dkrd S |D ]}| dkr&t j|  d S qd S )Nr   z
pd_op.data)	paddlepirr   default_main_programZglobal_blockopslennameZset_insertion_point)r   r   opr   r   r   _reset_data_op_insertion_pointm   s   
z,data.<locals>._reset_data_op_insertion_pointdatar   shapeNT)r   r!   dtypetypestop_gradient	lod_levelZis_dataZneed_check_feedZFLAGS_enable_pir_in_executoroutr   )r!   r#   Zplacer   )r$   ZinputsZoutputsattrs)r    )r   localsr   bytesr   listtupleranger   r   Zget_default_dtyper   
isinstancer	   r   r   r   Z_pir_opsr    ZPlaceZreset_insertion_point_to_endZcreate_global_variableZVarDescZVarTypeZ
LOD_TENSORosenvirongetr   Z	append_op)
r   r!   r#   r&   r   helperiZir_dtyper'   Zis_pir_moder   r   r   r    '   sZ   F


r    c                   @   sv   e Zd ZdZdddZdd Zd	d
 ZedddZedddZ	dd Z
dd Zdd Zdd Zdd Zdd ZdS )	InputSpeca@  
    InputSpec describes the signature information of the model input, such as ``shape`` , ``dtype`` , ``name`` .

    This interface is often used to specify input tensor information of models in high-level API.
    It's also used to specify the tensor information for each input parameter of the forward function
    decorated by `@paddle.jit.to_static`.

    Args:
        shape (tuple(integers)|list[integers]): List|Tuple of integers
            declaring the shape. You can set "None" or -1 at a dimension
            to indicate the dimension can be of any size. For example,
            it is useful to set changeable batch size as "None" or -1.
        dtype (np.dtype|str, optional): The type of the data. Supported
            dtype: bool, float16, float32, float64, int8, int16, int32, int64,
            uint8. Default: float32.
        name (str): The name/alias of the variable, see :ref:`api_guide_Name`
            for more details.
        stop_gradient (bool, optional): A boolean that mentions whether gradient should flow. Default is False, means don't stop calculate gradients.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle.static import InputSpec

            >>> input = InputSpec([None, 784], 'float32', 'x')
            >>> label = InputSpec([None, 1], 'int64', 'label')

            >>> print(input)
            InputSpec(shape=(-1, 784), dtype=paddle.float32, name=x, stop_gradient=False)

            >>> print(label)
            InputSpec(shape=(-1, 1), dtype=paddle.int64, name=label, stop_gradient=False)
    float32NFc                 C   sB   |  || _|d urt|tjtfrt|}|| _|| _|| _d S N)	_verifyr!   r.   npr#   r   r   r   r%   )selfr!   r#   r   r%   r   r   r   __init__   s   
zInputSpec.__init__c                 C   s   t | j| j| jdS )Nr!   r#   )r    r   r!   r#   r9   r   r   r   _create_feed_layer   s   zInputSpec._create_feed_layerc                 C   s    d t| j| j| j| j| jS )Nz1{}(shape={}, dtype={}, name={}, stop_gradient={}))formatr$   __name__r!   r#   r   r%   r<   r   r   r   __repr__   s   zInputSpec.__repr__c                 C   s<   t |ttjjfr| |j|j|p|jS td	t
|j)a  
        Generates a InputSpec based on the description of input tensor.

        Args:
            tensor(Tensor): the source tensor to generate a InputSpec instance

        Returns:
            A InputSpec instance generated from Tensor.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> from paddle.static import InputSpec

                >>> paddle.disable_static()

                >>> x = paddle.ones([2, 2], dtype="float32")
                >>> x_spec = InputSpec.from_tensor(x, name='x')
                >>> print(x_spec)
                InputSpec(shape=(2, 2), dtype=paddle.float32, name=x, stop_gradient=False)

        z3Input `tensor` should be a Tensor, but received {}.)r.   r   r   eagerZTensorr!   r#   r   
ValueErrorr>   r$   r?   )clsZtensorr   r   r   r   from_tensor   s   zInputSpec.from_tensorc                 C   s   | |j |j|S )a  
        Generates a InputSpec based on the description of input np.ndarray.

        Args:
            tensor(Tensor): the source numpy ndarray to generate a InputSpec instance

        Returns:
            A InputSpec instance generated from Tensor.

        Examples:
            .. code-block:: python

                >>> import numpy as np
                >>> from paddle.static import InputSpec

                >>> x = np.ones([2, 2], np.float32)
                >>> x_spec = InputSpec.from_numpy(x, name='x')
                >>> print(x_spec)
                InputSpec(shape=(2, 2), dtype=paddle.float32, name=x, stop_gradient=False)

        r;   )rC   Zndarrayr   r   r   r   
from_numpy  s   zInputSpec.from_numpyc                 C   st   t |ttfrt|dkrtd|t||d }nt |ts+tdt|j	|gt| j
 }t|| _
| S )ac  
        Inserts `batch_size` in front of the `shape`.

        Args:
            batch_size(int): the inserted integer value of batch size.

        Returns:
            The original InputSpec instance by inserting `batch_size` in front of `shape`.

        Examples:
            .. code-block:: python

                >>> from paddle.static import InputSpec

                >>> x_spec = InputSpec(shape=[64], dtype='float32', name='x')
                >>> x_spec.batch(4)
                >>> print(x_spec)
                InputSpec(shape=(4, 64), dtype=paddle.float32, name=x, stop_gradient=False)

           z5Length of batch_size: {} shall be 1, but received {}.z1type(batch_size) shall be `int`, but received {}.)r.   r+   r,   r   rB   r>   int	TypeErrorr$   r?   r!   )r9   Z
batch_sizeZ	new_shaper   r   r   batch!  s"   


zInputSpec.batchc                 C   s0   t | jdkrtd| | jdd | _| S )a:  
        Removes the first element of `shape`.

        Returns:
            The original InputSpec instance by removing the first element of `shape` .

        Examples:
            .. code-block:: python

                >>> from paddle.static import InputSpec

                >>> x_spec = InputSpec(shape=[4, 64], dtype='float32', name='x')
                >>> x_spec.unbatch()
                >>> print(x_spec) # InputSpec(shape=(64,), dtype=paddle.float32, name=x)
                InputSpec(shape=(64,), dtype=paddle.float32, name=x, stop_gradient=False)

        r   z8Not support to unbatch a InputSpec when len(shape) == 0.rF   N)r   r!   rB   r7   r<   r   r   r   unbatchJ  s   zInputSpec.unbatchc                 C   s~   t |ttfstdt|jt|D ]%\}}|dur.t |ts.t	d|t|j||du s6|dk r:d||< qt|S )zI
        Verifies the input shape and modifies `None` into `-1`.
        zMType of `shape` in InputSpec should be one of (tuple, list), but received {}.Nz3shape[{}] should be an `int`, but received `{}`:{}.r"   )
r.   r+   r,   rH   r>   r$   r?   	enumeraterG   rB   )r9   r!   r3   Zeler   r   r   r7   d  s$   
zInputSpec._verifyc                 C   s   t t| j| j| jfS r6   )hashr,   r!   r#   r%   r<   r   r   r   __hash__|  s   zInputSpec.__hash__c                    s0   g d}t t  u ot fdd|D S )N)r!   r#   r   r%   c                 3   s$    | ]}t |t  |kV  qd S r6   )getattr).0attrotherr9   r   r   	<genexpr>  s    
z#InputSpec.__eq__.<locals>.<genexpr>)r$   all)r9   rR   slotsr   rQ   r   __eq__  s   zInputSpec.__eq__c                 C   s
   | |k S r6   r   )r9   rR   r   r   r   __ne__  s   
zInputSpec.__ne__)r5   NFr6   )r?   
__module____qualname____doc__r:   r=   r@   classmethodrD   rE   rI   rJ   r7   rM   rV   rW   r   r   r   r   r4      s    
#	!)r4   c                 C   s   t | ||S )a=  
    x(Tensor): input Tensor.
    index(Scalar|Tuple|List|Tensor): Where should be set value.
    value(Scalar|Tensor): The value which is going to be set.

    [How to write index?]
    1. ':' -> slice(),
       (1) a[:]=v -> setitem(a, slice(None,None,None), v)
       (2) a[1::2] -> setitem(a, slice(1,None,2), v)

    2. if there are multiple indexes for axes, use TUPLE (Not LIST) to pack them.
       (1) a[1, 2]=v -> setitem(a, (1, 2), v)
       (2) a[[1,2],[2,3]]=v -> setitem(a, ([1,2],[2,3]), v)
       (3) a[1,:, 3] = v -> setitem(a, (1, slice(None,None,None),3), v)
       (4) a[1, ..., 2]=v -> setitem(a, (1, ..., 2), v)

    3. You can always use TUPLE as index input, even there is only one index.
       (1) a[Tensor([10,10])]=v -> setitem(a, (Tensor([10,10]),), v)
       (2) a[1] = v -> setitem(a, (1,), v)
    r   )xindexvaluer   r   r   setitem  s   r_   )Nr   )r/   numpyr8   r   Zpaddle.baser   r   Zpaddle.base.data_feederr   Zpaddle.base.frameworkr   r   r   Zpaddle.base.layer_helperr   Zpaddle.base.libpaddler	   Zbase.variable_indexr   __all__boolr   r    r4   r_   r   r   r   r   <module>   s"     n