o
    _{j((  ã                   @   s€   d dl Z d dlZd dlmZ d dlZd dlmZ d dlZd dl	Z
ddlmZ ddlmZ ddlmZ e ¡ G dd	„ d	eƒƒZdS )
é    N)ÚOrderedDicté   )Úaverage_recall_at_avg_proposalsé   )ÚBaseDataset)ÚDATASETSc                	       s”   e Zd ZdZd‡ fdd„	Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	e
d dd„ƒZe
dd„ ƒZd!dd„Zddede ddd¡d�idfdd„Z‡  ZS )"ÚActivityNetDatasetaÐ  ActivityNet dataset for temporal action localization.

    The dataset loads raw features and apply specified transforms to return a
    dict containing the frame tensors and other information.

    The ann_file is a json file with multiple objects, and each object has a
    key of the name of a video, and value of total frames of the video, total
    seconds of the video, annotations of a video, feature frames (frames
    covered by features) of the video, fps and rfps. Example of a
    annotation file:

    .. code-block:: JSON

        {
            "v_--1DO2V4K74":  {
                "duration_second": 211.53,
                "duration_frame": 6337,
                "annotations": [
                    {
                        "segment": [
                            30.025882995319815,
                            205.2318595943838
                        ],
                        "label": "Rock climbing"
                    }
                ],
                "feature_frame": 6336,
                "fps": 30.0,
                "rfps": 29.9579255898
            },
            "v_--6bJUbfpnQ": {
                "duration_second": 26.75,
                "duration_frame": 647,
                "annotations": [
                    {
                        "segment": [
                            2.578755070202808,
                            24.914101404056165
                        ],
                        "label": "Drinking beer"
                    }
                ],
                "feature_frame": 624,
                "fps": 24.0,
                "rfps": 24.1869158879
            },
            ...
        }


    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.
    NFc                    s   t ƒ  ||||¡ d S )N)ÚsuperÚ__init__)ÚselfÚann_fileÚpipelineÚdata_prefixZ	test_mode©Ú	__class__© ú;/root/disk_3tb/HAC/mmaction/datasets/activitynet_dataset.pyr
   L   s   zActivityNetDataset.__init__c                 C   s8   g }t  | j¡}|D ]}|| }||d< | |¡ q
|S )z;Load the annotation according to ann_file into video_infos.Ú
video_name)ÚmmcvÚloadr   Úappend)r   Úvideo_infosZanno_databaser   Ú
video_infor   r   r   Úload_annotationsO   s   z#ActivityNetDataset.load_annotationsc                 C   ó$   t  | j| ¡}| j|d< |  |¡S )z/Prepare the frames for testing given the index.r   ©ÚcopyÚdeepcopyr   r   r   ©r   ÚidxÚresultsr   r   r   Úprepare_test_framesY   ó   

z&ActivityNetDataset.prepare_test_framesc                 C   r   )z0Prepare the frames for training given the index.r   r   r   r   r   r   Úprepare_train_frames_   r"   z'ActivityNetDataset.prepare_train_framesc                 C   s
   t | jƒS )zGet the size of the dataset.)Úlenr   )r   r   r   r   Ú__len__e   s   
zActivityNetDataset.__len__c           	      C   sh   i }| j D ],}|d dd… }g }|d D ]}|d \}}|d }| |||g¡ qt |¡||< q|S )z(Read ground truth data from video_infos.r   r   NÚannotationsÚsegmentÚlabel)r   r   ÚnpÚarray)	r   Úground_truthr   Úvideo_idZthis_video_ground_truthsÚannÚt_startÚt_endr(   r   r   r   Ú_import_ground_truthi   s   
z'ActivityNetDataset._import_ground_truthc                 C   sT   i }t dƒ |rt t| ƒ¡}| D ]}|d }|d ||dd… < |r'| ¡  q|S )aÏ  Convert all proposals to a final dict(json) format.

        Args:
            results (list[dict]): All proposals.
            show_progress (bool): Whether to show the progress bar.
                Defaults: False.

        Returns:
            dict: The final result dict. E.g.

            .. code-block:: Python

                dict(video-1=[dict(segment=[1.1,2.0]. score=0.9),
                              dict(segment=[50.1, 129.3], score=0.6)])
        z Convert proposals to json formatr   Úproposal_listr   N)Úprintr   ÚProgressBarr$   Úupdate)r    Úshow_progressÚresult_dictÚprog_barÚresultr   r   r   r   Úproposals2jsonv   s   €z!ActivityNetDataset.proposals2jsonc           
      C   sv   i }d}| D ]0}|d dd… }g }|d D ]}|d \}}|d }	|  |||	g¡ |d7 }qt |¡||< q||fS )	zRead predictions from results.r   r   r   Nr1   r'   Úscorer   )r   r)   r*   )
r    Ú	proposalsÚnum_proposalsr8   r,   Úthis_video_proposalsÚproposalr.   r/   r:   r   r   r   Ú_import_proposals’   s   
z$ActivityNetDataset._import_proposalsúVERSION 1.3c                 C   s’   |dkr|   |¡}||i dœ}t ||¡ dS |dkrAtj|dd� d}|D ]}|\}	}
t ||	d ¡}tj||
|dd	d
� q&dS t	d|› d�ƒ‚)zDump data to json/csv files.Újson)Úversionr    Zexternal_dataÚcsvT)Úexist_okzaction,start,end,tmin,tmaxz.csvÚ,Ú )ÚheaderÚ	delimiterÚcommentszThe output format z is not supported.N)
r9   r   ÚdumpÚosÚmakedirsÚospÚjoinr)   ÚsavetxtÚ
ValueError)r   r    ÚoutZoutput_formatrB   r6   Zoutput_dictrG   r8   r   ÚoutputsZoutput_pathr   r   r   Údump_results¢   s0   
ýûý

ÿzActivityNetDataset.dump_resultsúAR@ANéd   ç      à?çffffffî?é
   ©Úmax_avg_proposalsÚtemporal_iou_thresholdsc              	   K   s¾  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}dg}|D ]}||vr]td|› d�ƒ‚qOtƒ }|  ¡ }	|  |¡\}
}|D ]n}|dkrÜ| di ¡ dt d	d
d¡¡}| di ¡ dd¡}t|tƒr—t |¡}t|	|
|||d�\}}}}||d< t |dd…df ¡|d< t |dd…df ¡|d< t |dd…df ¡|d< t |dd…df ¡|d< qn|S )a6  Evaluation in feature dataset.

        Args:
            results (list[dict]): Output results.
            metrics (str | sequence[str]): Metrics to be performed.
                Defaults: 'AR@AN'.
            metric_options (dict): Dict for metric options. Options are
                ``max_avg_proposals``, ``temporal_iou_thresholds`` for
                ``AR@AN``.
                default: ``{'AR@AN': dict(max_avg_proposals=100,
                temporal_iou_thresholds=np.linspace(0.5, 0.95, 10))}``.
            logger (logging.Logger | None): Training logger. Defaults: None.
            deprecated_kwargs (dict): Used for containing deprecated arguments.
                See 'https://github.com/open-mmlab/mmaction2/pull/286'.

        Returns:
            dict: Evaluation results for evaluation metrics.
        zŠOption arguments for metrics has been changed to `metric_options`, See 'https://github.com/open-mmlab/mmaction2/pull/286' for more detailsrT   z results must be a list, but got z7The length of results is not equal to the dataset len: z != zmetric z is not supportedr[   rV   rW   rX   rZ   rU   rY   ÚaucNr   zAR@1é   zAR@5é	   zAR@10éc   zAR@100)r   r   ÚwarningsÚwarnÚdictÚ
isinstanceÚlistÚ	TypeErrorÚtyper$   ÚtupleÚKeyErrorr   r0   r?   Ú
setdefaultr)   Úlinspacer*   r   Úmean)r   r    ÚmetricsZmetric_optionsÚloggerZdeprecated_kwargsZallowed_metricsÚmetricZeval_resultsr+   r>   r<   r[   rZ   ÚrecallÚ_r\   r   r   r   Úevaluate½   sr   
ÿ
ÿ
ÿÿÿÿÿÿÿÿÿ

û
ÿ€zActivityNetDataset.evaluate)NF)F)r@   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r   r!   r#   r%   r0   Ústaticmethodr9   r?   rS   rb   r)   rj   rq   Ú__classcell__r   r   r   r   r      s,    ;


þþör   )r   rK   Úos.pathÚpathrM   r`   Úcollectionsr   r   Únumpyr)   Úcorer   Úbaser   Úregistryr   Úregister_moduler   r   r   r   r   Ú<module>   s    