o
    _{jÆ1  ã                   @   sø   d dl mZ d dlZd dlZd dlZd dlmZ ddl	m
Z
 dd„ Ze
 ¡ G dd	„ d	ƒƒZe
 ¡ G d
d„ dƒƒZe
 ¡ G dd„ dƒƒZe
 ¡ G dd„ dƒƒZe
 ¡ G dd„ dƒƒZe
 ¡ G dd„ dƒƒZe
 ¡ G dd„ dƒƒZe
 ¡ G dd„ dƒƒZdS )é    )ÚSequenceN)ÚDataContaineré   )Ú	PIPELINESc                 C   s„   t | tjƒr| S t | tjƒrt | ¡S t | tƒr"t | ¡s"t 	| ¡S t | t
ƒr-t | g¡S t | tƒr8t | g¡S tdt| ƒ› d�ƒ‚)zÅConvert objects of various python types to :obj:`torch.Tensor`.

    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
    :class:`Sequence`, :class:`int` and :class:`float`.
    ztype z cannot be converted to tensor.)Ú
isinstanceÚtorchÚTensorÚnpÚndarrayÚ
from_numpyr   ÚmmcvÚis_strÚtensorÚintÚ
LongTensorÚfloatÚFloatTensorÚ	TypeErrorÚtype)Údata© r   ú;/root/disk_3tb/HAC/mmaction/datasets/pipelines/formating.pyÚ	to_tensor   s   



r   c                   @   ó(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚToTensorz¤Convert some values in results dict to `torch.Tensor` type in data
    loader pipeline.

    Args:
        keys (Sequence[str]): Required keys to be converted.
    c                 C   ó
   || _ d S ©N©Úkeys©Úselfr   r   r   r   Ú__init__'   ó   
zToTensor.__init__c                 C   s    | j D ]
}t|| ƒ||< q|S )z´Performs the ToTensor formating.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        )r   r   ©r    ÚresultsÚkeyr   r   r   Ú__call__*   s   
zToTensor.__call__c                 C   ó   | j j› d| j› d�S ©Nú(keys=ú)©Ú	__class__Ú__name__r   ©r    r   r   r   Ú__repr__5   ó   zToTensor.__repr__N©r-   Ú
__module__Ú__qualname__Ú__doc__r!   r&   r/   r   r   r   r   r      s
    r   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚRenamea&  Rename the key in results.

    Args:
        mapping (dict): The keys in results that need to be renamed. The key of
            the dict is the original name, while the value is the new name. If
            the original name not found in results, do nothing.
            Default: dict().
    c                 C   r   r   )Úmapping)r    r6   r   r   r   r!   D   r"   zRename.__init__c                 C   s^   | j  ¡ D ]'\}}||v r,t|tƒrt|tƒsJ ‚||vs!J dƒ‚|| ||< | |¡ q|S )Nz&the new name already exists in results)r6   Úitemsr   ÚstrÚpop)r    r$   r%   Úvaluer   r   r   r&   G   s   
€zRename.__call__N)r-   r2   r3   r4   r!   r&   r   r   r   r   r5   9   s    	r5   c                   @   r   )	ÚToDataContainera\  Convert the data to DataContainer.

    Args:
        fields (Sequence[dict]): Required fields to be converted
            with keys and attributes. E.g.
            fields=(dict(key='gt_bbox', stack=False),).
            Note that key can also be a list of keys, if so, every tensor in
            the list will be converted to DataContainer.
    c                 C   r   r   )Úfields)r    r<   r   r   r   r!   ^   r"   zToDataContainer.__init__c                 C   sh   | j D ].}| ¡ }| d¡}t|tƒr%|D ]}t|| fi |¤Ž||< qqt|| fi |¤Ž||< q|S )z»Performs the ToDataContainer formating.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r%   )r<   Úcopyr9   r   ÚlistÚDC)r    r$   ÚfieldZ_fieldr%   Úitemr   r   r   r&   a   s   


ÿzToDataContainer.__call__c                 C   s   | j jd| j› d� S )Nz(fields=r*   )r,   r-   r<   r.   r   r   r   r/   r   r0   zToDataContainer.__repr__Nr1   r   r   r   r   r;   R   s
    
r;   c                   @   r   )	ÚImageToTensorzwConvert image type to `torch.Tensor` type.

    Args:
        keys (Sequence[str]): Required keys to be converted.
    c                 C   r   r   r   r   r   r   r   r!   ~   r"   zImageToTensor.__init__c                 C   s*   | j D ]}t||  ddd¡ƒ||< q|S )z¹Performs the ImageToTensor formating.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   r   é   )r   r   Ú	transposer#   r   r   r   r&   �   s   
zImageToTensor.__call__c                 C   r'   r(   r+   r.   r   r   r   r/   Œ   r0   zImageToTensor.__repr__Nr1   r   r   r   r   rB   v   s
    rB   c                   @   r   )	Ú	Transposez«Transpose image channels to a given order.

    Args:
        keys (Sequence[str]): Required keys to be converted.
        order (Sequence[int]): Image channel order.
    c                 C   s   || _ || _d S r   )r   Úorder)r    r   rF   r   r   r   r!   ™   s   
zTranspose.__init__c                 C   s$   | j D ]}||  | j¡||< q|S )z¶Performs the Transpose formatting.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        )r   rD   rF   r#   r   r   r   r&   �   s   
zTranspose.__call__c                 C   s   | j j› d| j› d| j› d�S )Nr)   z, order=r*   )r,   r-   r   rF   r.   r   r   r   r/   ¨   s
   
ÿÿzTranspose.__repr__Nr1   r   r   r   r   rE   �   s
    rE   c                   @   s0   e Zd ZdZ			ddd„Zdd„ Zd	d
„ ZdS )ÚCollecta·  Collect data from the loader relevant to the specific task.

    This keeps the items in ``keys`` as it is, and collect items in
    ``meta_keys`` into a meta item called ``meta_name``.This is usually
    the last stage of the data loader pipeline.
    For example, when keys='imgs', meta_keys=('filename', 'label',
    'original_shape'), meta_name='img_metas', the results will be a dict with
    keys 'imgs' and 'img_metas', where 'img_metas' is a DataContainer of
    another dict with keys 'filename', 'label', 'original_shape'.

    Args:
        keys (Sequence[str]): Required keys to be collected.
        meta_name (str): The name of the key that contains meta infomation.
            This key is always populated. Default: "img_metas".
        meta_keys (Sequence[str]): Keys that are collected under meta_name.
            The contents of the ``meta_name`` dictionary depends on
            ``meta_keys``.
            By default this includes:

            - "filename": path to the image file
            - "label": label of the image file
            - "original_shape": original shape of the image as a tuple
                (h, w, c)
            - "img_shape": shape of the image input to the network as a tuple
                (h, w, c).  Note that images may be zero padded on the
                bottom/right, if the batch tensor is larger than this shape.
            - "pad_shape": image shape after padding
            - "flip_direction": a str in ("horiziontal", "vertival") to
                indicate if the image is fliped horizontally or vertically.
            - "img_norm_cfg": a dict of normalization information:
                - mean - per channel mean subtraction
                - std - per channel std divisor
                - to_rgb - bool indicating if bgr was converted to rgb
        nested (bool): If set as True, will apply data[x] = [data[x]] to all
            items in data. The arg is added for compatibility. Default: False.
    ©ÚfilenameÚlabelÚoriginal_shapeÚ	img_shapeZ	pad_shapeÚflip_directionÚimg_norm_cfgÚ	img_metasFc                 C   s   || _ || _|| _|| _d S r   )r   Ú	meta_keysÚ	meta_nameÚnested)r    r   rP   rQ   rR   r   r   r   r!   Ô   s   
zCollect.__init__c                 C   sz   i }| j D ]}|| ||< qt| jƒdkr,i }| jD ]}|| ||< qt|dd�|| j< | jr;|D ]	}|| g||< q1|S )z³Performs the Collect formating.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   T)Úcpu_only)r   ÚlenrP   r?   rQ   rR   )r    r$   r   r%   ÚmetaÚkr   r   r   r&   ß   s   

zCollect.__call__c                 C   s&   | j j› d| j› d| j› d| j› d�S )Nr)   z, meta_keys=z	, nested=r*   )r,   r-   r   rP   rR   r.   r   r   r   r/   õ   s   
ÿÿþzCollect.__repr__N)rH   rO   Fr1   r   r   r   r   rG   ­   s    '
ûrG   c                   @   s*   e Zd ZdZd
dd„Zdd„ Zdd„ Zd	S )ÚFormatShapea²  Format final imgs shape to the given input_format.

    Required keys are "imgs", "num_clips" and "clip_len", added or modified
    keys are "imgs" and "input_shape".

    Args:
        input_format (str): Define the final imgs format.
        collapse (bool): To collpase input_format N... to ... (NCTHW to CTHW,
            etc.) if N is 1. Should be set as True when training and testing
            detectors. Default: False.
    Fc                 C   s,   || _ || _| j dvrtd| j › d�ƒ‚d S )N)ÚNCTHWÚNCHWÚ	NCHW_FlowÚNPTCHWúThe input format ú is invalid.)Úinput_formatÚcollapseÚ
ValueError)r    r^   r_   r   r   r   r!   	  s   
ÿÿzFormatShape.__init__c                 C   s®  t |d tjƒst |d ¡|d< |d }| jr |d dks J ‚| jdkrO|d }|d }| d||f|jdd…  ¡}t |d¡}| d	|jd
d…  ¡}nl| jdkr[t |d¡}n`| jdkr”|d }|d }| d||f|jdd…  ¡}t |d¡}| d|jd
 |jd  f|jdd…  ¡}n'| jdkr»|d }|d }|d }| ||| f|jdd…  ¡}t |d¡}| jrÌ|jd dksÇJ ‚| 	d¡}||d< |j|d< |S )z·Performs the FormatShape formating.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        ÚimgsÚ	num_clipsrC   rX   Úclip_lenéÿÿÿÿN)r   rC   é   r   é   é   )rd   r   rY   )r   rf   rC   r   rZ   )r   rC   r   re   rf   rg   rf   rg   r[   Únum_proposals)r   rC   rg   r   rf   r   Úinput_shape)
r   r	   r
   Úarrayr_   r^   ÚreshapeÚshaperD   Úsqueeze)r    r$   ra   rb   rc   rh   r   r   r   r&     sF   


ÿ
ÿ

zFormatShape.__call__c                 C   ó   | j j}|d| j› d�7 }|S ©Nz(input_format='z')©r,   r-   r^   ©r    Úrepr_strr   r   r   r/   K  ó   zFormatShape.__repr__N)Fr1   r   r   r   r   rW   û   s
    
;rW   c                   @   r   )	ÚFormatAudioShapezñFormat final audio shape to the given input_format.

    Required keys are "imgs", "num_clips" and "clip_len", added or modified
    keys are "imgs" and "input_shape".

    Args:
        input_format (str): Define the final imgs format.
    c                 C   s&   || _ | j dvrtd| j › d�ƒ‚d S )N)ZNCTFr\   r]   )r^   r`   )r    r^   r   r   r   r!   \  s   
ÿÿzFormatAudioShape.__init__c                 C   s:   |d }|j \}}}| |d||¡}||d< |j |d< |S )z¸Performs the FormatShape formatting.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        ÚaudiosrC   ri   )rl   rk   )r    r$   ru   ÚclipÚsampleÚfreqr   r   r   r&   b  s   
zFormatAudioShape.__call__c                 C   rn   ro   rp   rq   r   r   r   r/   q  rs   zFormatAudioShape.__repr__Nr1   r   r   r   r   rt   Q  s
    	rt   )Úcollections.abcr   r   Únumpyr	   r   Úmmcv.parallelr   r?   Úregistryr   r   Úregister_moduler   r5   r;   rB   rE   rG   rW   rt   r   r   r   r   Ú<module>   s.    #MU