o
    pi]>                     @  s  d dl mZ d dlZd dlmZmZ d dlZd dlmZ	 d dl
m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mZ ddlmZ ernd dlmZ d dl m!Z!m"Z"m#Z#m$Z$m%Z% g Z&d(ddZ'e		 d)d*ddZ(G dd dZ)d+d&d'Z*dS ),    )annotationsN)TYPE_CHECKINGAny)Self)Variablecore)
check_type)convert_np_dtype_to_dtype_in_pir_modestatic_only)LayerHelper)DataType)get_current_insertion_pointset_insertion_point   _setitem_static)Tensor)	DTypeLike	ShapeLikeSize1TensorIndex
TensorLikereturnboolc                 C  s   t |  dvS )N)falseoff0none)strlower)val r"   Z/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/paddle/static/input.pyevaluate_flag6   s   r$   namer   shaper   dtypeDTypeLike | None	lod_levelintpaddle.Tensorc              
   C  s  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||< t	|| t
rP|| dk rP|| dkrPtd	||  q(|du rYt }t r|}t	|tsjtjj|}t }|  tj| ||t }	t| |	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 DenseTensor. 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

            >>> # doctest: +SKIP("This has diff in xdoctest env")
            >>> 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lenr%   r   )r.   r/   opr"   r"   r#   _reset_data_op_insertion_point   s   
z,data.<locals>._reset_data_op_insertion_pointdatar%   r&   Nr   zIOnly -1 can be used in shape to indicate unknown dimension, but received T)r%   r&   r'   typestop_gradientr)   Zis_dataZneed_check_feedZFLAGS_enable_pir_in_executorout)r&   r'   Zplacer%   )r5   ZinputsZoutputsattrs)r3   )!r   localsr   bytesr   listtupleranger0   
isinstancer*   
ValueErrorr,   Zget_default_dtyper
   r   r-   r   r	   r   Z_pir_opsr3   ZPlacer   Zcreate_global_variableZVarDescZVarTypeZDENSE_TENSORosenvirongetr$   Z	append_op)r%   r&   r'   r)   r2   helperiZir_dtypeZprev_insertion_pointr7   Zis_pir_moder"   r"   r#   r3   :   sd   L
&
r3   c                   @  s   e Zd ZdZ			d/d0ddZdd Zd1ddZed2d3ddZe	d2d4ddZ	d5d!d"Z
d6d#d$Zd%d& Zd7d(d)Zd8d+d,Zd9d-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)
    float32NFr&   r   r'   r   r%   
str | Noner6   r   r   Nonec                 C  sB   |  || _|d urt|tjtfrt|}|| _|| _|| _d S N)	_verifyr&   r>   npr'   r   r	   r%   r6   )selfr&   r'   r%   r6   r"   r"   r#   __init__   s   
zInputSpec.__init__c                 C  s   t | j| j| jdS )Nr&   r'   )r3   r%   r&   r'   rL   r"   r"   r#   _create_feed_layer   s   zInputSpec._create_feed_layerr   c              
   C  s0   t | j d| j d| j d| j d| j d
S )Nz(shape=z, dtype=z, name=z, stop_gradient=))r5   __name__r&   r'   r%   r6   rO   r"   r"   r#   __repr__  s   0zInputSpec.__repr__tensorr   r   c                 C  sD   t |ttjjtjjfr| |j|j	|p|j
S tdt|j d)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)

        z0Input `tensor` should be a Tensor, but received .)r>   r   r   eagerr   r,   r-   Valuer&   r'   r%   r?   r5   rR   )clsrT   r%   r"   r"   r#   from_tensor  s
   zInputSpec.from_tensorndarraynpt.NDArray[Any]c                 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)

        rN   )rX   rZ   r%   r"   r"   r#   
from_numpy$  s   zInputSpec.from_numpy
batch_sizeint | Size1c                 C  s|   t |ttfrt|dkrtd| dt| d|d }nt |ts/tdt|j d|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)

           zLength of batch_size: z shall be 1, but received rU   r   z.type(batch_size) shall be `int`, but received )
r>   r;   r<   r0   r?   r*   	TypeErrorr5   rR   r&   )rL   r]   Z	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.r_   N)r0   r&   r?   rJ   rO   r"   r"   r#   unbatchd  s   zInputSpec.unbatchc              	   C  s   t |ttfstdt|j dt|D ]*\}}|dur4t |ts4td| dt|j d| d|du s<|dk r@d||< qt|S )zI
        Verifies the input shape and modifies `None` into `-1`.
        zJType of `shape` in InputSpec should be one of (tuple, list), but received rU   Nzshape[z$] should be an `int`, but received `z`:r4   )	r>   r;   r<   r`   r5   rR   	enumerater*   r?   )rL   r&   rD   Zeler"   r"   r#   rJ   ~  s   
zInputSpec._verifyr*   c                 C  s   t t| j| j| jfS rI   )hashr<   r&   r'   r6   rO   r"   r"   r#   __hash__  s   zInputSpec.__hash__otherc                   s0   g d}t t  u ot fdd|D S )N)r&   r'   r%   r6   c                 3  s$    | ]}t |t  |kV  qd S rI   )getattr).0attrrf   rL   r"   r#   	<genexpr>  s    
z#InputSpec.__eq__.<locals>.<genexpr>)r5   all)rL   rf   slotsr"   rj   r#   __eq__  s   zInputSpec.__eq__c                 C  s
   | |k S rI   r"   )rL   rf   r"   r"   r#   __ne__  s   
zInputSpec.__ne__)rF   NF)
r&   r   r'   r   r%   rG   r6   r   r   rH   )r   r   rI   )rT   r   r%   rG   r   r   )rZ   r[   r%   rG   r   r   )r]   r^   r   r   )r   r   )r   r*   )rf   r   r   r   r   r   )rR   
__module____qualname____doc__rM   rP   rS   classmethodrY   r\   ra   rb   rJ   re   rn   ro   r"   r"   r"   r#   rE      s&    &


%

rE   xr   indexr   valuer   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   )ru   rv   rw   r"   r"   r#   setitem  s   rx   rp   )Nr   )
r%   r   r&   r   r'   r(   r)   r*   r   r+   )ru   r   rv   r   rw   r   r   r   )+
__future__r   r@   typingr   r   numpyrK   Znumpy.typingZnptZtyping_extensionsr   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paddle.base.libpaddle.pirr   r   Zbase.variable_indexr   r   Zpaddle._typingr   r   r   r   r   __all__r$   r3   rE   rx   r"   r"   r"   r#   <module>   s6   
  f