o
    #jI                     @   s  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	Z
d dlZd dlmZ ddlmZmZ dd	lmZmZmZmZ efd
dZdd ZG dd deZe Zdd Zdd Zdd Zdd Zdd Zdd Z dd Z!dd Z"d d! Z#d"d# Z$d$d% Z%d&d' Z&d(d) Z'd*d+ Z(dGd,d-Z)dHd/d0Z*d1d2 Z+d3d4 Z,dId6d7Z-d8d9 Z.dJd;d<Z/d=d> Z0d?d@ Z1dAdB Z2dCdD Z3dEdF Z4dS )K    N)defaultdict)Sequence)uuid4)WeakKeyDictionary)convert_np_dtype_to_dtype_   )check_dtypeconvert_dtype)BlockVariable_current_expected_placein_dygraph_modec              
   C   s  t | |r
| g| S zt| }W n ty#   td| d t|  w t||kr<td| d t| d t|  |D ]H}t |ttjj	frOJ d| z|| W q> ttfy   td| d t| d t| d t|  d	 t| d
 d tt
| w |S )am  
    Converts a single numerical type or iterable of numerical
    types into a numerical type list.

    Arguments:
      value: The value to validate and convert. Could an int, or any iterable
        of ints.
      n: The size of the list to be returned.
      name: The name of the argument being validated, e.g. "stride" or
        "filter_size". This is only used to format error messages.
      dtype: the numerical type of the element of the list to be returned.

    Returns:
      A list of n dtypes.

    Raises:
      ValueError: If something else than an int/long or iterable thereof was
        passed.
    zThe z)'s type must be list or tuple. Received: z's length must be z. Received: z7Required numerical type with '%s', but received Tensor.z#'s type must be a list or tuple of  z . Received: z including element z of type)
isinstancelist	TypeError
ValueErrorstrlenr   paddlepirOpResulttype)valuennamedtypeZ
value_listZsingle_value r   Z/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/utils/layers_utils.pyconvert_to_list#   s   


r   c                 C   s$   t | trdS t | tot | t S )z7
    Whether `seq` is an entry or nested structure
    T)r   dictr   r   )seqr   r   r   is_sequencek   s   
r"   c                       s   e Zd Z fddZ  ZS )UniqueIdMapc                    s   t  |  tt| _d S N)super__init__r   r   data)self	__class__r   r   r&   u   s   zUniqueIdMap.__init__)__name__
__module____qualname__r&   __classcell__r   r   r)   r   r#   t   s    r#   c                 C   s4   t | tr
t| fS t | trt| fS t|  jfS r$   )r   r   hashr   iduniqueidmapintobjr   r   r   uniqueid}   s
   



r5   c                  G   s2   t | dksJ d}| D ]}|t| }qt|S )zM
    Return int hash value calculated by id(arg) or tuple(id1,id2, ...).
    r   r   )r   r5   r/   )argsinfovr   r   r   _hash_with_id   s
   r9   c                 C   s&   zt |  W S  ty   tdw )zR
    Returns a sorted list of the dict keys, with error if keys not sortable.
    z,nest only supports dicts with sortable keys.)sortedkeysr   )Zdict_r   r   r   _sorted   s
   r<   c                 c   s6    t | trt| D ]}| | V  q
d S | E d H  d S r$   )r   r    r<   )iterablekeyr   r   r   _yield_value   s   
r?   c                 c   s2    t | D ]}t|rt|E d H  q|V  qd S r$   )r?   r"   _yield_flat_nest)nestr   r   r   r   r@      s   r@   c                 C   s   t | r| S | gS r$   r"   rA   r   r   r   to_sequence   s   rD   c                 C   s   t | r
tt| S | gS )z
        :alias_main: paddle.flatten
        :alias: paddle.flatten,paddle.tensor.flatten,paddle.tensor.manipulation.flatten
        :old_api: paddle.base.layers.flatten

    Traverse all entries in the nested structure and put them into an list.
    )r"   r   r@   rC   r   r   r   flatten   s   rE   c                    s   t | trttt| | t|  fdd|  D S t | tr=t| dr=t | jt	r=t
dd | jD r=t| | S t| |S )zE
    Convert the sequence `args` to the same type as `instance`.
    c                 3   s    | ]	}| | fV  qd S r$   r   ).0r>   resultr   r   	<genexpr>   s    z!_sequence_like.<locals>.<genexpr>_fieldsc                 s   s    | ]}t |tV  qd S r$   )r   r   )rF   fr   r   r   rI      s    )r   r    zipr<   r   r;   tuplehasattrrJ   r   all)instancer6   r   rG   r   _sequence_like   s   

rQ   c                 C   s^   g }t | D ]$}t|rt|||\}}|t|| |}q|||  |d7 }q||fS )z/
    Helper function for pack_sequence_as.
       )r?   r"   _packed_nest_with_indicesappendrQ   )	structureZflatindexpackedsZ	new_indexchildr   r   r   rS      s   
rS   c                 C   s   t |stdt | st|dkrtdt| |d S t| }t|t|kr8tdt|t|| |f t| |d\}}t| |S )zA
    Pack a given flattened sequence into a given structure.
    z flat_sequence must be a sequencerR   z6Structure is a scalar but len(flat_sequence) == %d > 1r   zyCould not pack sequence. Structure had %d elements, but flat_sequence had %d elements.  Structure: %s, flat_sequence: %s.)r"   r   r   r   rE   rS   rQ   )rU   Zflat_sequenceflat_structure_rW   r   r   r   pack_sequence_as   s.   

r\   c                    s2   dd |D }t | }t|d  fdd|D S )zO
    Apply `func` to each entry in `structure` and return a new structure.
    c                 S   s   g | ]}t |qS r   )rE   )rF   rX   r   r   r   
<listcomp>      z!map_structure.<locals>.<listcomp>r   c                    s   g | ]} | qS r   r   rF   xfuncr   r   r]     r^   )rL   r\   )rb   rU   rZ   entriesr   ra   r   map_structure  s   rd   c                 C   s   | D ]	}t |r dS qdS )zD
    Returns whether structure holds sequence like `list/dict`.
    TFrB   )rU   rX   r   r   r   hold_mutable_vars  s
   re   c                 C   s   t  t| }t| |S )zE
    Returns vars copied from sequence without mutable property.
    )copyrE   r\   )rU   rZ   r   r   r   copy_mutable_vars  s   
rg   c                 C   s   t | }|t |krtd|  d| d|sdS |rLt| }t|}||kr/td||t| trLt|  }t| }||krLtd||t	t
| }t	t
|}	t||	D ]
\}
}t|
|| q]dS )z6
    Helper function for `assert_same_structure`.
    zKThe two structures don't have the same nested structure.

First structure: z

Second structure: .NzvThe two structures don't have the same sequence type. First structure has type {}, while second structure has type {}.zvThe two dictionaries don't have the same set of keys. First structure has keys {}, while second structure has keys {}.)r"   r   r   r   formatr   r    setr;   r   r?   rL    _recursive_assert_same_structure)nest1nest2check_typesZis_sequence_nest1Z
type_nest1Z
type_nest2Zkeys1keys2Znest1_as_sequenceZnest2_as_sequenceZn1Zn2r   r   r   rk   &  sH   
rk   c                 C   s$   dd }|| |} |||}| |fS )Nc                    s@   fdd t | rt|  fddt| D } | S  | } | S )Nc                    s   | d u r S | S r$   r   )r`   r3   r   r   change_none_to_objN  s   z`padding_to_same_structure.<locals>._padding_to_same_structure_single.<locals>.change_none_to_objc                    s   g | ]} |qS r   r   )rF   item)rp   r   r   r]   U  r^   zXpadding_to_same_structure.<locals>._padding_to_same_structure_single.<locals>.<listcomp>)r"   r\   rE   )r   r4   r   )rp   r4   r   !_padding_to_same_structure_singleM  s   zDpadding_to_same_structure.<locals>._padding_to_same_structure_singler   )rl   rm   r4   rr   r   r   r   padding_to_same_structureL  s   

rs   Tc                 C   s\   t | r
tt| nd}t |rtt|nd}||kr&td|| ||f t| || dS )z@
    Confirm two nested structures with the same structure.
    rR   zThe two structures don't have the same number of elements.

First structure (%i elements): %s

Second structure (%i elements): %sN)r"   r   rE   r   rk   )rl   rm   rn   Z	len_nest1Z	len_nest2r   r   r   assert_same_structure`  s   
rt   c                 C   sf   t | |d kst | |ksJ d}t | |d kr1t|D ]}| |d  | |d d  kr0d}q|S )z/
    Check whether padding is symmetrical.
    r   TrR   F)r   range)paddingZdata_dimZis_sysir   r   r   _is_symmetric_paddingp  s    rx   c                 C   s&   | D ]}t |ttjjfr dS qdS )zC
    Check whether list or tuple contains variable / OpResult.
    TF)r   r   r   r   r   )Zlist_or_tuplerq   r   r   r   _contain_var}  s
   ry   int64c              	   C   s   |d u rt  }g }| D ]=}t|tjjr6d|_t|j|kr%tj||d}|j	g kr0t
|g }|| qtg |tt||}|| q|S )NTr`   r   )r   r   r   r   r   stop_gradientr	   r   castshapeZreshaperT   fullr   np)Zele_listZplaceZdefault_dtypeZint_tensor_listeletemp_outr   r   r   get_int_tensor_list  s&   
r   c                    s   ddl m  dd } fdd}t|tr;d|_t|jdd	d
gdd d  t|jd
kr5t	|d	}|| d< d S t|t
tfrV|||d< t|rT||| d< d S d S td)Nr   fill_constantc                 S   s:   g }t | D ]\}}t|tr|d q|| q|S )N)	enumerater   r   rT   )
list_shapeZ
attr_shapeidxdimr   r   r   _get_attr_shape  s   
z0get_shape_tensor_inputs.<locals>._get_attr_shapec                    s   g }t | D ]B\}}t|tr;d|_t|jdt| d ddgd d  t|jdkr5tj	|dd}|
| q g d|dd	}|
| q|S )
NTzshape[]int32rz   (When type of shape inzis list or tuple.)r{   Z	force_cpu)r   r   r   r|   r   r   r   r	   r   r}   rT   )r   Zshape_tensor_listr   r   r   r   op_typer   r   _get_shape_tensor  s"   

z2get_shape_tensor_inputs.<locals>._get_shape_tensorTr~   r   rz   r   r   z is Variable.)ZShapeTensorZShapeTensorListz0Shape only supports Variable, or list, or tuple.)paddle.tensorr   r   r   r|   r   r   r	   r   r}   r   rM   ry   r   )Zinputsattrsr~   r   r   r   r   r   r   get_shape_tensor_inputs  s*   	

r   r   c                 C   sl   ddl m} g }| D ])}t|ttjjfrd|_|| q
t|t	s%J |dg||dd}|| q
|S )zA
    Converts all elements of a list to Variable / OpResult.
    r   r   TrR   r   )
r   r   r   r   r   r   r   r|   rT   r2   )Zold_listr   r   Znew_list_tensorr   r   r   r   r   _convert_to_tensor_list  s   r   c                 C   s8   t | ttfrdd | D } | S t r| t } | S )zI
    Convert shape(list, tuple, variable) to list in imperative mode
    c                 S   s$   g | ]}t |tr|d n|qS )r   )r   r   rq   r_   r   r   r   r]     s   $ z)convert_shape_to_list.<locals>.<listcomp>)r   r   rM   r   Zastyper2   tolist)r~   r   r   r   convert_shape_to_list  s   r   c                 C   s\   t | trt| jdddgd dS | D ]}t |ts+|dk r"tdt |ts+tdqdS )	zU
    Check shape type and shape elements type before passing it to fill_constant
    r~   r   rz   r   r   zDAll elements in ``shape`` must be positive when it's a list or tuplezDAll elements in ``shape`` must be integers when it's a list or tupleN)r   r   r   r   r   r2   r   )r~   r   r   r   r   check_shape  s   


r   c                 C   sF   t  sd| jv rt|trt|}|r!| j| dS dS dS dS dS )aQ  Try to set static shape of tensor from a shape tensor.

    For example,

    import paddle
    paddle.enable_static()
    data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32')
    shape = paddle.shape(data)  # shape should be [-1, 2] instead of [-1, -1]
    x = paddle.uniform(shape)
    print(x.shape)
    # (-1, 2)

    r   N)r   r~   r   r   "try_get_constant_shape_from_tensordesc	set_shape)Ztensorr~   r   r   r   try_set_static_shape_tensor  s   

r   c                 C   sX   t  s*z | jdur| j}|jdkr!| jj|jd  }|jW S W dS W dS    Y dS dS )aN  Try to get shape from a tensor with constant value.

    For example,

    import paddle
    paddle.enable_static()
    data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32')
    shape = paddle.shape(data)  # shape should be [-1, 2] instead of [-1, -1]
    x = paddle.uniform(shape)
    print(x.shape)
    # (-1, 2)

    Nr~   r   )r   opr   blockvarsZinput_arg_namesr~   )Zshape_tensorZgenerate_opvarr   r   r   r     s    


r   c                 C   s   t | ts	J d| jdksJ dt }t }| jD ]2}|jD ]}||D ]}| |s3|| q'q |j	D ]}|
|D ]}| |sK|| q?q8q||fS )zg
    Returns the inputs and outputs variable used in this block but not
    created in this block.
    z9input non-Block argument for get_inputs_outputs_in_block.r   z2input block should be a sub-block, not main block.)r   r
   Z
parent_idxrj   opsZinput_namesinputZhas_varaddZoutput_namesoutput)r   Zinner_inputsZinner_outputsr   ZinameZin_var_nameZonameZout_var_namer   r   r   get_inputs_outputs_in_block8  s2   






r   r$   )T)Nrz   )r   )5rf   collectionsr   collections.abcr   uuidr   weakrefr   numpyr   r   Zpaddle.pir.corer   Zbase.data_feederr   r	   Zbase.frameworkr
   r   r   r   r2   r   r"   r#   r1   r5   r9   r<   r?   r@   rD   rE   rQ   rS   r\   rd   re   rg   rk   rs   rt   rx   ry   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sP   H		
	

&



4