o
    oi9                     @   s   d dl mZ d dlmZ d dlmZmZmZmZm	Z	m
Z
 d dlZd dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d
dlmZmZmZmZ d
dlmZ g dZ G dd dej!Z"G dd de"Z#G dd de#Z$G dd dZ%dS )    )OrderedDict)zip_longest)AnyDictIteratorListOptionalTupleN)nn)_AugmentationBase)ModuleTensor)Boxes)	Keypoints   )BoxSequentialOpsInputSequentialOpsKeypointSequentialOpsMaskSequentialOps	ParamItem)BasicSequentialBaseImageSequentialBaseSequentialBasec                       s   e Zd ZdZdeddf fddZdedefdd	Zdd
dZde	j
dee fddZdedeeeef  fddZdee deeeef  fddZdeeeef  dee fddZ  ZS )r   zBasicSequential for creating kornia modulized processing pipeline.

    Args:
        *args : a list of kornia augmentation and image operation modules.

    argsreturnNc                    sd   t  }t|D ]\}}t|tstd| d||jj d| |i qt 	| d | _
d S )Nz.Only Module are supported at this moment. Got ._)r   	enumerate
isinstancer   NotImplementedErrorupdate	__class____name__super__init___params)selfr   _argsidxmodr"    V/home/ubuntu/.local/lib/python3.10/site-packages/kornia/augmentation/container/base.pyr%   -   s   

zBasicSequentialBase.__init__targetc                 C   sr   t |dkr| S |d}| }|D ]%}t||s$t| d | d t||}t|ts6td| d q|S )a  Get submodule.

        This code is taken from torch 1.9.0 since it is not introduced
        back to torch 1.7.1. We included this for maintaining more
        backward torch versions.

        Args:
            target: The fully-qualified string name of the submodule
                to look for. (See above example for how to specify a
                fully-qualified string.)

        Returns:
            Module: The submodule referenced by ``target``

        Raises:
            AttributeError: If the target string references an invalid
                path or resolves to something that is not an
                ``Module``

        r   r   z has no attribute ``z` is not an Module)lensplithasattrAttributeError	_get_namegetattrr   r   )r'   r.   atomsr*   itemr,   r,   r-   get_submodule7   s   



z!BasicSequentialBase.get_submodulec                 C   s
   d| _ dS )z!Reset self._params state to None.N)r&   r'   r,   r,   r-   clear_state]   s   
zBasicSequentialBase.clear_statebatch_shapec                 C      t Nr    r'   r;   r,   r,   r-   forward_parametersb      z&BasicSequentialBase.forward_parametersindicesc                 c   s&    t |  }|D ]}|| V  q	d S r=   )listnamed_children)r'   rB   modulesr)   r,   r,   r-   get_children_by_indicese   s
   z+BasicSequentialBase.get_children_by_indicesparamsc                 c   s>    t |  }|D ]}|t t|   |j V  q	d S r=   )rC   rD   dictkeysindexname)r'   rG   rE   paramr,   r,   r-   get_children_by_paramsj   s
   $z*BasicSequentialBase.get_children_by_paramsnamed_modulesc                 c   s     |D ]
\}}t |d V  qd S r=   r   )r'   rN   rK   r   r,   r,   r-   get_params_by_modulep   s   z(BasicSequentialBase.get_params_by_moduler   N)r#   
__module____qualname____doc__r   r%   strr8   r:   torchSizer   r   r@   r   r   r	   rF   rM   rO   __classcell__r,   r,   r+   r-   r   %   s    

&"*r   c                	       s   e Zd ZdZddddedee dee ddf fdd	Z			ddee d
ee dee ddfddZe	dee fddZ
e
jdee ddfddZ
e	dee fddZejdee ddfddZddedeeef deejejf fddZ  ZS )r   a  SequentialBase for creating kornia modulized processing pipeline.

    Args:
        *args : a list of kornia augmentation and image operation modules.
        same_on_batch: apply the same transformation across the batch.
            If None, it will not overwrite the function-wise settings.
        return_transform: if ``True`` return the matrix describing the transformation
            applied to each. If None, it will not overwrite the function-wise settings.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
            to the batch form (False). If None, it will not overwrite the function-wise settings.

    N)same_on_batchkeepdimr   rX   rY   r   c                   s*   t  j|  || _|| _| j||d d S N)rY   )r$   r%   _same_on_batch_keepdimupdate_attribute)r'   rX   rY   r   r+   r,   r-   r%      s   zSequentialBase.__init__return_transformc                 C   sV   |   D ]$}t|ttjfr|d ur||_|d ur||_t|tr(|||| qd S r=   )	childrenr   r   KMixAugmentationBaseV2rX   rY   r   r]   )r'   rX   r^   rY   r*   r,   r,   r-   r]      s   
zSequentialBase.update_attributec                 C      | j S r=   )r[   r9   r,   r,   r-   rX         zSequentialBase.same_on_batchc                 C      || _ | j|d d S )N)rX   )r[   r]   )r'   rX   r,   r,   r-   rX         c                 C   rb   r=   )r\   r9   r,   r,   r-   rY      rc   zSequentialBase.keepdimc                 C   rd   rZ   )r\   r]   )r'   rY   r,   r,   r-   rY      re         input	dim_rangec                 C   sr   |j }t||d k st||d krtd| d| dt|j |d k r4|d }t|j |d k s'||j fS )zFill tensor dim to the upper bound of dim_range.

        If input tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.
        r   r   zinput shape expected to be in z while got r   N)shaper0   RuntimeError)r'   ri   rj   	ori_shaper,   r,   r-   autofill_dim   s    
zSequentialBase.autofill_dim)NNN)rf   )r#   rQ   rR   rS   r   r   boolr%   r]   propertyrX   setterrY   r   r	   intrU   rV   rn   rW   r,   r,   r+   r-   r   v   s0    .	
4r   c                   @   sp  e Zd ZdedefddZ			d%dedeee  ded	ee	e
ef  dee f
d
dZdejdee fddZd&deee  deee
ef  fddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defddZ	d&dedee d	ee	e
ef  defdd Z	d'dedeee  d	ee	e
ef  defd!d"Z	d'dedeee  d	ee	e
ef  defd#d$ZdS )(r   ri   r   c                 C   r<   )zReturn identity matrix.r>   )r'   ri   r,   r,   r-   identity_matrix      z#ImageSequentialBase.identity_matrixNFrG   	recompute
extra_argsc                 C   r<   )a  Compute the transformation matrix according to the provided parameters.

        Args:
            input: the input tensor.
            params: params for the sequence.
            recompute: if to recompute the transformation matrix according to the params.
                default: False.
            extra_args: Optional dictionary of extra arguments with specific options for different input types.
        r>   )r'   ri   rG   ru   rv   r,   r,   r-   get_transformation_matrix   s   z-ImageSequentialBase.get_transformation_matrixr;   c                 C   r<   r=   r>   r?   r,   r,   r-   r@      rA   z&ImageSequentialBase.forward_parametersc                 C   r<   )z$Get module sequence by input params.r>   )r'   rG   r,   r,   r-   get_forward_sequence   rt   z(ImageSequentialBase.get_forward_sequencec                 C   ,   |D ]}|  |j}tj||||d}q|S NmodulerL   rv   )r8   rK   r   	transformr'   ri   rG   rv   rL   r|   r,   r,   r-   transform_inputs      z$ImageSequentialBase.transform_inputsc                 C   L   t t| |d d d |d d d D ]\\}}}tj||||d}q|S Nr{   )r   rC   rx   r   inverser'   ri   rG   rv   r   r|   rL   r,   r,   r-   inverse_inputs      4z"ImageSequentialBase.inverse_inputsc                 C   ry   rz   )r8   rK   r   r}   r~   r,   r,   r-   transform_masks   r   z#ImageSequentialBase.transform_masksc                 C   r   r   )r   rC   rx   r   r   r   r,   r,   r-   inverse_masks   r   z!ImageSequentialBase.inverse_masksc                 C   ry   rz   )r8   rK   r   r}   r~   r,   r,   r-   transform_boxes   r   z#ImageSequentialBase.transform_boxesc                 C   r   r   )r   rC   rx   r   r   r   r,   r,   r-   inverse_boxes   r   z!ImageSequentialBase.inverse_boxesc                 C   ry   rz   )r8   rK   r   r}   r~   r,   r,   r-   transform_keypoints  r   z'ImageSequentialBase.transform_keypointsc                 C   r   r   )r   rC   rx   r   r   r   r,   r,   r-   inverse_keypoints  r   z%ImageSequentialBase.inverse_keypointsc                 C   s4   |du r| j du rtd| j }| j|||d}|S )zInverse transformation.

        Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
        provided parameters.
        NzrNo parameters available for inversing, please run a forward pass first or passing valid params into this function.)rv   )r&   
ValueErrorr   )r'   ri   rG   rv   r,   r,   r-   r     s   
zImageSequentialBase.inversec                 C   sJ   |    |d u r|}| j|dd\}}| |}| j|||d}|| _|S )Nrf   )rj   )rG   rv   )r:   rn   r@   r   r&   )r'   ri   rG   rv   inpr   	out_shaper,   r,   r-   forward(  s   
zImageSequentialBase.forward)NFNr=   )NN) r#   rQ   rR   r   rs   r   r   r   ro   r   rT   r   rw   rU   rV   r@   r   r	   r   rx   r   r   r   r   r   r   r   r   r   r   r   r   r,   r,   r,   r-   r      s    

(
	

	

	

	



r   c                       s   e Zd ZU dZdZeedf ed< dZe	ed< d fd	d
Z
de	ddfddZedee fddZdeddfddZdeddfddZdee ddfddZdddZ  ZS )TransformMatrixMinInz'Enables computation matrix computation.r,   .$_valid_ops_for_transform_computationsilent_transformation_matrix_argr   Nc                    s"   t  j|i | d | _g | _d S r=   )r$   r%   _transform_matrix_transform_matrices)r'   r   kwargsr+   r,   r-   r%   >  s   
zTransformMatrixMinIn.__init__transformation_matrix_modec                 C   s0   h d}||vrt d| d| d|| _d S )N>   skiprigidr   silencez)`transformation_matrix` has to be one of z. Got r   )r   r   )r'   r   !_valid_transformation_matrix_argsr,   r,   r-   !_parse_transformation_matrix_modeC  s   
z6TransformMatrixMinIn._parse_transformation_matrix_modec                 C   sH   | j d u r!t| jdkr!| jd | _ | jdd  D ]}| | q| j S )Nr   r   )r   r0   r   _update_transform_matrix)r'   matr,   r,   r-   transform_matrixL  s
   z%TransformMatrixMinIn.transform_matrixr|   c                 C   s   t |r=   r>   r'   r|   r,   r,   r-   %_update_transform_matrix_for_valid_opV  s   z:TransformMatrixMinIn._update_transform_matrix_for_valid_opc                 C   sF   | j dkrd S t|| jr| | d S | j dkr!td| dd S )Nr   r   zNon-rigid module `z` is not supported under `rigid` computation mode. Please either update the module or change the `transformation_matrix` argument.)r   r   r   r   rl   r   r,   r,   r-   "_update_transform_matrix_by_moduleY  s   


z7TransformMatrixMinIn._update_transform_matrix_by_moduler   c                 C   s$   | j d u r
|| _ d S || j  | _ d S r=   )r   )r'   r   r,   r,   r-   r   d  s   

z-TransformMatrixMinIn._update_transform_matrixc                 C   s   d | _ g | _d S r=   )r   r   r9   r,   r,   r-   _reset_transform_matrix_statej  s   
z2TransformMatrixMinIn._reset_transform_matrix_staterP   )r#   rQ   rR   rS   r   r	   r   __annotations__r   rT   r%   r   rp   r   r   r   r   r   r   r   r   rW   r,   r,   r+   r-   r   8  s   
 		r   )&collectionsr   	itertoolsr   typingr   r   r   r   r   r	   rU   r
   kornia.augmentationaugmentationr`   kornia.augmentation.baser   kornia.corer   r   kornia.geometry.boxesr   kornia.geometry.keypointsr   opsr   r   r   r   rG   r   __all__
Sequentialr   r   r   r   r,   r,   r,   r-   <module>   s"    QD~