a
    dE                  	   @  sP  d dl mZ d dlZd dlmZ d dlZd dlmZ d dlm	Z	m
Z
 d dlmZ dgZdd ZG d	d
 d
eZe ZG dd deZdd Zdd Zdd Zdd Zdd Zdd Zdd Ze
je
je
je
je
je
j e
j!e
j"e
j#f	D ]Z$e%e$e qdd Z&e
j'fD ]Z$e%e$e& qdd Z(e
j)e
j*e
j+fD ]Z$e%e$e( q6e%e
j,dd  Z-e%e
j.d!d" Z/e%e
j0e g d#Z1ee2e1e3e4e1Z5e%e
j6d$d% Z7e%e
j8d&d' Z9e%e
j:d(d) Z;g d*Z<ee2e<e3e4e<Z=e%e
j>d+d, Z?e%e
j@d-d. ZAe%e
jBd/d0 ZCe%e
jDd1d2 ZEdS )3    )annotationsN)defaultdict)Dataset)
datapointsdatasets)
functionalwrap_dataset_for_transforms_v2c                 C  s   t | S )a\  [BETA] Wrap a ``torchvision.dataset`` for usage with :mod:`torchvision.transforms.v2`.

    .. v2betastatus:: wrap_dataset_for_transforms_v2 function

    Example:
        >>> dataset = torchvision.datasets.CocoDetection(...)
        >>> dataset = wrap_dataset_for_transforms_v2(dataset)

    .. note::

       For now, only the most popular datasets are supported. Furthermore, the wrapper only supports dataset
       configurations that are fully supported by ``torchvision.transforms.v2``. If you encounter an error prompting you
       to raise an issue to ``torchvision`` for a dataset or configuration that you need, please do so.

    The dataset samples are wrapped according to the description below.

    Special cases:

        * :class:`~torchvision.datasets.CocoDetection`: Instead of returning the target as list of dicts, the wrapper
          returns a dict of lists. In addition, the key-value-pairs ``"boxes"`` (in ``XYXY`` coordinate format),
          ``"masks"`` and ``"labels"`` are added and wrap the data in the corresponding ``torchvision.datapoints``.
          The original keys are preserved.
        * :class:`~torchvision.datasets.VOCDetection`: The key-value-pairs ``"boxes"`` and ``"labels"`` are added to
          the target and wrap the data in the corresponding ``torchvision.datapoints``. The original keys are
          preserved.
        * :class:`~torchvision.datasets.CelebA`: The target for ``target_type="bbox"`` is converted to the ``XYXY``
          coordinate format and wrapped into a :class:`~torchvision.datapoints.BoundingBox` datapoint.
        * :class:`~torchvision.datasets.Kitti`: Instead returning the target as list of dictsthe wrapper returns a dict
          of lists. In addition, the key-value-pairs ``"boxes"`` and ``"labels"`` are added and wrap the data
          in the corresponding ``torchvision.datapoints``. The original keys are preserved.
        * :class:`~torchvision.datasets.OxfordIIITPet`: The target for ``target_type="segmentation"`` is wrapped into a
          :class:`~torchvision.datapoints.Mask` datapoint.
        * :class:`~torchvision.datasets.Cityscapes`: The target for ``target_type="semantic"`` is wrapped into a
          :class:`~torchvision.datapoints.Mask` datapoint. The target for ``target_type="instance"`` is *replaced* by
          a dictionary with the key-value-pairs ``"masks"`` (as :class:`~torchvision.datapoints.Mask` datapoint) and
          ``"labels"``.
        * :class:`~torchvision.datasets.WIDERFace`: The value for key ``"bbox"`` in the target is converted to ``XYXY``
          coordinate format and wrapped into a :class:`~torchvision.datapoints.BoundingBox` datapoint.

    Image classification datasets

        This wrapper is a no-op for image classification datasets, since they were already fully supported by
        :mod:`torchvision.transforms` and thus no change is needed for :mod:`torchvision.transforms.v2`.

    Segmentation datasets

        Segmentation datasets, e.g. :class:`~torchvision.datasets.VOCSegmentation` return a two-tuple of
        :class:`PIL.Image.Image`'s. This wrapper leaves the image as is (first item), while wrapping the
        segmentation mask into a :class:`~torchvision.datapoints.Mask` (second item).

    Video classification datasets

        Video classification datasets, e.g. :class:`~torchvision.datasets.Kinetics` return a three-tuple containing a
        :class:`torch.Tensor` for the video and audio and a :class:`int` as label. This wrapper wraps the video into a
        :class:`~torchvision.datapoints.Video` while leaving the other items as is.

        .. note::

            Only datasets constructed with ``output_format="TCHW"`` are supported, since the alternative
            ``output_format="THWC"`` is not supported by :mod:`torchvision.transforms.v2`.

    Args:
        dataset: the dataset instance to wrap for compatibility with transforms v2.
    )VisionDatasetDatapointWrapperdataset r   p/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchvision/datapoints/_dataset_wrapper.pyr      s    Ac                   @  s   e Zd Zdd ZdS )WrapperFactoriesc                   s    fdd}|S )Nc                   s   |  < | S Nr   )wrapper_factorydataset_clsselfr   r   	decoratorW   s    z,WrapperFactories.register.<locals>.decoratorr   )r   r   r   r   r   r   registerV   s    zWrapperFactories.registerN)__name__
__module____qualname__r   r   r   r   r   r   U   s   r   c                   @  s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r	   c                 C  s   t |}t|tjs&td|j d| D ]R}|tv rHt| } qq.|tju r.d|j d}|tj	 v rx| d}t|q.|| _
||| _|jd  | _|_|jd  | _|_|jd  | _|_d S )NzYThis wrapper is meant for subclasses of `torchvision.datasets.VisionDataset`, but got a 'z
' instead.z$No wrapper exists for dataset class z". Please wrap the output yourself.z If an automated wrapper for this dataset would be useful for you, please open an issue at https://github.com/pytorch/vision/issues.)type
isinstancer   ZVisionDataset	TypeErrorr   mroWRAPPER_FACTORIES__dict__values_dataset_wrapperZ	transformZtarget_transform
transforms)r   r   r   clsr   msgr   r   r   __init__f   s,    


z&VisionDatasetDatapointWrapper.__init__c                 C  sB   t t t| |W  d    S 1 s,0    Y  t| j|S r   )
contextlibsuppressAttributeErrorobject__getattribute__getattrr    )r   itemr   r   r   __getattr__   s    *z)VisionDatasetDatapointWrapper.__getattr__c                 C  s.   | j | }| ||}| jd ur*| j| }|S r   )r    r!   r"   )r   idxsampler   r   r   __getitem__   s
    


z)VisionDatasetDatapointWrapper.__getitem__c                 C  s
   t | jS r   )lenr    )r   r   r   r   __len__   s    z%VisionDatasetDatapointWrapper.__len__N)r   r   r   r%   r-   r0   r2   r   r   r   r   r	   e   s   $r	   c                 C  s   t |  dd S )Nz is currently not supported by this wrapper. If this would be helpful for you, please open an issue at https://github.com/pytorch/vision/issues.)RuntimeError)descriptionr   r   r   raise_not_supported   s    r5   c                 C  s   | S r   r   r,   r   r   r   identity   s    r7   c                 C  s   dd }|S )Nc                 S  s   |S r   r   )r.   r/   r   r   r   wrapper   s    z)identity_wrapper_factory.<locals>.wrapperr   r   r8   r   r   r   identity_wrapper_factory   s    r:   c                 C  s
   t | S r   )r   Mask)Z	pil_imager   r   r   pil_image_to_mask   s    r<   c                 C  s:   t t}| D ]$}| D ]\}}|| | qqt|S r   )r   listitemsappenddict)Zlist_of_dictsZdict_of_listsdctkeyvaluer   r   r   list_of_dicts_to_dict_of_lists   s
    rD   c                  sH   t | ttfs| g} t fddt|| D }t|dkrD|d }|S )Nc                 3  s"   | ]\}}  |t|V  qd S r   )getr7   ).0target_typer,   type_wrappersr   r   	<genexpr>   s   z&wrap_target_by_type.<locals>.<genexpr>   r   )r   tupler=   zipr1   )targettarget_typesrI   Zwrapped_targetr   rH   r   wrap_target_by_type   s    rP   c                 C  s   t | S r   )r:   r
   r   r   r   classification_wrapper_factory   s    rQ   c                 C  s   dd }|S )Nc                 S  s   |\}}|t |fS r   )r<   )r.   r/   imagemaskr   r   r   r8      s    z-segmentation_wrapper_factory.<locals>.wrapperr   r9   r   r   r   segmentation_wrapper_factory   s    rT   c                 C  s,   | j jdkr tt| j ddd }|S )NZTHWCz with `output_format='THWC'` is not supported by this wrapper, since it is not compatible with the transformations. Please use `output_format='TCHW'` instead.c                 S  s   |\}}}t |}|||fS r   )r   ZVideo)r.   r/   videoaudiolabelr   r   r   r8      s    

z5video_classification_wrapper_factory.<locals>.wrapper)Zvideo_clipsZoutput_formatr3   r   r   r9   r   r   r   $video_classification_wrapper_factory   s    rX   c                 C  s   d| j v rtd t| S )N
annotationz9Caltech101 dataset with `target_type=['annotation', ...]`)rG   r5   rQ   r
   r   r   r   caltech101_wrapper_factory  s    
rZ   c                   s   dd  fdd}|S )Nc                S  sP   ddl m} t| tr(|j| g|R  n||j| g|R  } t|| S )Nr   )rS   )	ZpycocotoolsrS   r   r@   ZfrPyObjectsmergetorchZ
from_numpydecode)segmentationspatial_sizerS   r   r   r   segmentation_to_mask  s    z=coco_dectection_wrapper_factory.<locals>.segmentation_to_maskc                   s   j |  }|\}}|s$|t|dfS t|}||d< tt| tjtj|d tj	j
 dtj	jd|d< tt fdd|d	 D |d
< t|d |d< ||fS )N)image_idra   bboxformatr_   Z
new_formatboxesc                   s   g | ]} |d qS )r_   r   )rF   r^   )r`   r_   r   r   
<listcomp>2  s   zDcoco_dectection_wrapper_factory.<locals>.wrapper.<locals>.<listcomp>r^   masksZcategory_idlabels)idsr@   rD   rL   FZget_spatial_sizeconvert_format_bounding_boxr   BoundingBoxBoundingBoxFormatXYWHXYXYr;   r\   stacktensor)r.   r/   ra   rR   rN   Zbatched_targetr   r`   rg   r   r8     s0    

z0coco_dectection_wrapper_factory.<locals>.wrapperr   r9   r   rt   r   coco_dectection_wrapper_factory  s    
!ru   )Z__background__Z	aeroplaneZbicycleZbirdZboatZbottleZbusZcarcatZchairZcowZdiningtableZdogZhorseZ	motorbikeZpersonZpottedplantZsheepZsofaZtrainZ	tvmonitorc                 C  s   dd }|S )Nc                 S  sj   |\}}t |d d }tjdd |d D tjj|j|jfd|d< tdd |d	 D |d
< ||fS )NrY   r)   c                   s   g | ]  fd ddD qS )c                   s   g | ]}t  | qS r   )int)rF   partbndboxr   r   rh   e      zMvoc_detection_wrapper_factory.<locals>.wrapper.<locals>.<listcomp>.<listcomp>)ZxminZyminZxmaxZymaxr   )rF   r   ry   r   rh   d  s   zBvoc_detection_wrapper_factory.<locals>.wrapper.<locals>.<listcomp>rz   rc   rf   c                 S  s   g | ]}t | qS r   )VOC_DETECTION_CATEGORY_TO_IDXrF   categoryr   r   r   rh   l  r{   namerj   	rD   r   rn   ro   rq   heightwidthr\   rs   )r.   r/   rR   rN   Zbatched_instancesr   r   r   r8   ^  s    

z.voc_detection_wrapper_factory.<locals>.wrapperr   r9   r   r   r   voc_detection_wrapper_factory\  s    r   c                 C  s   | j dkrtd t| S )NZ
boundariesz SBDataset with mode='boundaries')moder5   rT   r
   r   r   r   sbd_wrappert  s    
r   c                   s.   t  fdddD rtd  fdd}|S )Nc                 3  s   | ]}| j v V  qd S r   rG   rF   rG   r
   r   r   rJ   ~  r{   z)celeba_wrapper_factory.<locals>.<genexpr>)attrZ	landmarksz>`CelebA` dataset with `target_type=['attr', 'landmarks', ...]`c                   s,   |\ }t |jd fddid} |fS )Nrb   c                   s*   t jtj| tjj j jfdtjjdS )Nrc   re   	rl   rm   r   rn   ro   rp   r   r   rq   r6   rR   r   r   <lambda>  s   
z9celeba_wrapper_factory.<locals>.wrapper.<locals>.<lambda>rO   rI   )rP   rG   )r.   r/   rN   r
   r   r   r8     s    z'celeba_wrapper_factory.<locals>.wrapperanyr5   r9   r   r
   r   celeba_wrapper_factory|  s    r   )	ZCarZVanZTruckZ
PedestrianZPerson_sittingZCyclistZTramZMiscZDontCarec                 C  s   dd }|S )Nc                 S  s`   |\}}|d urXt |}tj|d tjj|j|jfd|d< tdd |d D |d< ||fS )Nrb   rc   rf   c                 S  s   g | ]}t | qS r   )KITTI_CATEGORY_TO_IDXr}   r   r   r   rh     r{   z:kitti_wrapper_factory.<locals>.wrapper.<locals>.<listcomp>r   rj   r   r.   r/   rR   rN   r   r   r   r8     s    
z&kitti_wrapper_factory.<locals>.wrapperr   r9   r   r   r   kitti_wrapper_factory  s    r   c                   s    fdd}|S )Nc                   s,   |\}}|d ur$t | jdtid}||fS )Nr^   r   )rP   Z_target_typesr<   r   r
   r   r   r8     s    z/oxford_iiit_pet_wrapper_factor.<locals>.wrapperr   r9   r   r
   r   oxford_iiit_pet_wrapper_factor  s    r   c                   s8   t  fdddD rtd dd  fdd}|S )	Nc                 3  s   | ]}| j v V  qd S r   r   r   r
   r   r   rJ     r{   z-cityscapes_wrapper_factory.<locals>.<genexpr>)ZpolygoncolorzA`Cityscapes` dataset with `target_type=['polygon', 'color', ...]`c                 S  sh   t | }g }g }| D ]0}|||k |}|dkr>|d }|| qttt|t|dS )Ni  )ri   rj   )r<   uniquer?   r@   r   r;   r\   rr   )rS   datari   rj   idrW   r   r   r   instance_segmentation_wrapper  s    zAcityscapes_wrapper_factory.<locals>.instance_segmentation_wrapperc                   s&   |\}}t | jtdd}||fS )N)instanceZsemanticr   )rP   rG   r<   r   r   r   r   r   r8     s    	z+cityscapes_wrapper_factory.<locals>.wrapperr   r9   r   r   r   cityscapes_wrapper_factory  s
    r   c                 C  s   dd }|S )Nc                 S  sJ   |\}}|d urBt jtj|d tjj|j|jfdtjjd|d< ||fS )Nrb   rc   re   r   r   r   r   r   r8     s    
z"widerface_wrapper.<locals>.wrapperr   r9   r   r   r   widerface_wrapper  s    r   )F
__future__r   r&   collectionsr   r\   Ztorch.utils.datar   Ztorchvisionr   r   Ztorchvision.transforms.v2r   rl   __all__r   r@   r   r   r	   r5   r7   r:   r<   rD   rP   rQ   Z
Caltech256ZCIFAR10ZCIFAR100ZImageNetZMNISTZFashionMNISTZGTSRBZDatasetFolderZImageFolderr   r   rT   ZVOCSegmentationrX   ZHMDB51ZKineticsZUCF101Z
Caltech101rZ   ZCocoDetectionru   ZCocoCaptionsZVOC_DETECTION_CATEGORIESrM   ranger1   r|   ZVOCDetectionr   Z	SBDatasetr   ZCelebAr   ZKITTI_CATEGORIESr   ZKittir   ZOxfordIIITPetr   Z
Cityscapesr   Z	WIDERFacer   r   r   r   r   <module>   s|   D=	



/











"
