o
    _{j,  ã                   @   s¨   d dl Z d dlmZ d dlZd dlmZmZ d dlm	Z	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lmZmZmZmZ dd	lmZ G d
d„ deed�ZdS )é    N)ÚABCMetaÚabstractmethod)ÚOrderedDictÚdefaultdict)Ú	print_log)ÚDataseté   )Úmean_average_precisionÚmean_class_accuracyÚmmit_mean_average_precisionÚtop_k_accuracyé   )ÚComposec                       s¢   e Zd ZdZ								d ‡ fdd„	Zedd	„ ƒZd
d„ Zdd„ Ze	dd„ ƒZ
deedd�d�dfdd„Ze	dd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Z‡  ZS )!ÚBaseDataseta2  Base class for datasets.

    All datasets to process video should subclass it.
    All subclasses should overwrite:

    - Methods:`load_annotations`, supporting to load information from an
    annotation file.
    - Methods:`prepare_train_frames`, providing train data.
    - Methods:`prepare_test_frames`, providing test data.

    Args:
        ann_file (str): Path to the annotation file.
        pipeline (list[dict | callable]): A sequence of data transforms.
        data_prefix (str | None): Path to a directory where videos are held.
            Default: None.
        test_mode (bool): Store True when building test or validation dataset.
            Default: False.
        multi_class (bool): Determines whether the dataset is a multi-class
            dataset. Default: False.
        num_classes (int | None): Number of classes of the dataset, used in
            multi-class datasets. Default: None.
        start_index (int): Specify a start index for frames in consideration of
            different filename format. However, when taking videos as input,
            it should be set to 0, since frames loaded from videos count
            from 0. Default: 1.
        modality (str): Modality of data. Support 'RGB', 'Flow', 'Audio'.
            Default: 'RGB'.
        sample_by_class (bool): Sampling by class, should be set `True` when
            performing inter-class data balancing. Only compatible with
            `multi_class == False`. Only applies for training. Default: False.
        power (float | None): We support sampling data with the probability
            proportional to the power of its label frequency (freq ^ power)
            when sampling data. `power == 1` indicates uniformly sampling all
            data; `power == 0` indicates uniformly sampling all classes.
            Default: None.
    NFr   ÚRGBc                    s˜   t ƒ  ¡  || _|d urt |¡rt |¡n|| _|| _|| _|| _	|| _
|| _|	| _|
| _| jr6| jr6J ‚t|ƒ| _|  ¡ | _| jrJ|  ¡ | _d S d S )N)ÚsuperÚ__init__Úann_fileÚospÚisdirÚrealpathÚdata_prefixÚ	test_modeÚmulti_classÚnum_classesÚstart_indexÚmodalityÚsample_by_classÚpowerr   ÚpipelineÚload_annotationsÚvideo_infosÚparse_by_classÚvideo_infos_by_class)Úselfr   r   r   r   r   r   r   r   r   r   ©Ú	__class__© ú,/root/disk_3tb/HAC/mmaction/datasets/base.pyr   8   s.   
ÿÿÿþ

ÿzBaseDataset.__init__c                 C   s   dS )z;Load the annotation according to ann_file into video_infos.Nr'   ©r$   r'   r'   r(   r    W   s    zBaseDataset.load_annotationsc                 C   s°   t  | j¡}t|ƒ}d|d v rdnd}t|ƒD ]=}|| | }| jdur,t | j|¡}||| |< | jr=| j	dus<J ‚qt|| d ƒdksIJ ‚|| d d || d< q|S )z3Load json annotation file to get video information.Ú	frame_dirr   ÚfilenameNÚlabelr   )
ÚmmcvÚloadr   ÚlenÚranger   r   Újoinr   r   )r$   r!   Ú
num_videosZpath_keyÚiZ
path_valuer'   r'   r(   Úload_json_annotations]   s   
z!BaseDataset.load_json_annotationsc                 C   s.   t tƒ}| jD ]}|d }||  |¡ q|S )Nr,   )r   Úlistr!   Úappend)r$   r#   Úitemr,   r'   r'   r(   r"   n   s
   
zBaseDataset.parse_by_classc                 C   s   t j| t jd�}d||< |S )N)Údtypeç      ð?)ÚnpÚzerosÚfloat32)Únumr,   Úarrr'   r'   r(   Úlabel2arrayu   s   zBaseDataset.label2arrayr   ©r   é   )Útopk)r   c              	      sV  t  |¡}|i krt d¡ t|d fi |¤Ž|d< t|tƒs(tdt|ƒ› �ƒ‚t	|ƒt	ˆ ƒks>J dt	|ƒ› dt	ˆ ƒ› �ƒ‚t|tt
fƒrG|n|g}g d¢}|D ]}||vr^td|› d�ƒ‚qPtƒ }d	d
„ ˆ jD ƒ}	|D ]¼}d|› d�}
|du r|d|
 }
t|
|d� |dkrÚ| di ¡ dd¡}t|tt
fƒs tdt|ƒ› �ƒ‚t|tƒr¨|f}t||	|ƒ}g }t||ƒD ]\}}||d|› d�< | d|› d|d›�¡ qµd |¡}t||d� ql|dkrôt||	ƒ}||d< d|d›�}t||d� ql|dv �r(‡ fdd
„|	D ƒ}	|dk�rt||	ƒ}n
|dk�rt||	ƒ}||d< d|d›�}t||d� qlql|S ) aÏ  Perform evaluation for common datasets.

        Args:
            results (list): Output results.
            metrics (str | sequence[str]): Metrics to be performed.
                Defaults: 'top_k_accuracy'.
            metric_options (dict): Dict for metric options. Options are
                ``topk`` for ``top_k_accuracy``.
                Default: ``dict(top_k_accuracy=dict(topk=(1, 5)))``.
            logger (logging.Logger | None): Logger for recording.
                Default: None.
            deprecated_kwargs (dict): Used for containing deprecated arguments.
                See 'https://github.com/open-mmlab/mmaction2/pull/286'.

        Returns:
            dict: Evaluation results dict.
        zŠOption arguments for metrics has been changed to `metric_options`, See 'https://github.com/open-mmlab/mmaction2/pull/286' for more detailsr   z results must be a list, but got z7The length of results is not equal to the dataset len: z != )r   r
   r	   r   zmetric z is not supportedc                 S   s   g | ]}|d  ‘qS )r,   r'   )Ú.0Úannr'   r'   r(   Ú
<listcomp>®   s    z(BaseDataset.evaluate.<locals>.<listcomp>zEvaluating z ...NÚ
)ÚloggerrB   r@   z*topk must be int or tuple of int, but got ÚtopZ_accz
topz_acc	z.4fÚ r
   z

mean_acc	)r	   r   c                    s   g | ]	}ˆ   ˆ j|¡‘qS r'   )r?   r   )rC   r,   r)   r'   r(   rE   Ó   s    ÿÿr	   r   z
mean_average_precision	)ÚcopyÚdeepcopyÚwarningsÚwarnÚdictÚ
isinstancer5   Ú	TypeErrorÚtyper/   ÚtupleÚKeyErrorr   r!   r   Ú
setdefaultÚintr   Úzipr6   r1   r
   r	   r   )r$   ÚresultsÚmetricsÚmetric_optionsrG   Údeprecated_kwargsÚallowed_metricsÚmetricÚeval_resultsÚ	gt_labelsÚmsgrB   Z	top_k_accÚlog_msgÚkÚaccZmean_accÚmAPr'   r)   r(   Úevaluate{   s”   
ÿÿ
ÿ
ÿÿÿÿÿÿÿÿ




þ


òzBaseDataset.evaluatec                 C   s   t  | |¡S )z/Dump data to json/yaml/pickle strings or files.)r-   Údump)rW   Úoutr'   r'   r(   Údump_resultsâ   s   zBaseDataset.dump_resultsc                 C   ó†   | j r| j| }t tj |¡¡}nt | j| ¡}| j|d< | j	|d< | j
r>t|d tƒr>t | j¡}d||d < ||d< |  |¡S )z0Prepare the frames for training given the index.r   r   r,   r9   ©r   r#   rJ   rK   r:   ÚrandomÚchoicer!   r   r   r   rO   r5   Útorchr;   r   r   ©r$   ÚidxÚsamplesrW   Zonehotr'   r'   r(   Úprepare_train_framesç   ó   



z BaseDataset.prepare_train_framesc                 C   rh   )z/Prepare the frames for testing given the index.r   r   r,   r9   ri   rm   r'   r'   r(   Úprepare_test_framesû   rq   zBaseDataset.prepare_test_framesc                 C   s
   t | jƒS )zGet the size of the dataset.)r/   r!   r)   r'   r'   r(   Ú__len__  s   
zBaseDataset.__len__c                 C   s   | j r|  |¡S |  |¡S )z:Get the sample for either training or testing given index.)r   rr   rp   )r$   rn   r'   r'   r(   Ú__getitem__  s   

zBaseDataset.__getitem__)NFFNr   r   FN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r    r4   r"   Ústaticmethodr?   rN   rd   rg   rp   rr   rs   rt   Ú__classcell__r'   r'   r%   r(   r      s6    (ö


üg
r   )Ú	metaclass)rJ   Úos.pathÚpathr   rL   Úabcr   r   Úcollectionsr   r   r-   Únumpyr:   rl   Z
mmcv.utilsr   Útorch.utils.datar   Úcorer	   r
   r   r   Z	pipelinesr   r   r'   r'   r'   r(   Ú<module>   s    