Ë
    S^(hdÊ  ã                   óL	  — d dl 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	 d dl
mZmZmZmZ d dlZd dlZd dlmZ dd	lmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# dd
l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*  e«       �rd dl+Z,d dl-Z, ej\                   ej\                  e,j^                  «      j`                  «       ej\                  d«      k\  re,jb                  jd                  Z3ne,jb                  Z3 e«       r’d dl4mZ5 d dl6m7Z7 e3jp                  e7jp                  e3jr                  e7jr                  e3jt                  e7jt                  e3jv                  e7jv                  e3jx                  e7jx                  e3jz                  e7jz                  iZ>er e«       rd dl?Z? e!j€                  eA«      ZBedej†                  deDd   eDej†                     eDd   f   ZEeeDd   ddeDd   eDd   eDeDd      eDeDd      eDeDd      f   ZF G d„ de«      ZG G d„ de«      ZH G d„ de«      ZIe G d„ d«      «       ZJeKeLeeMeLeDeK   f   f   ZNd„ ZO G d„ de«      ZPd„ ZQd„ ZRdeDfd„ZSd „ ZTd!„ ZUd"ej†                  d#eVfd$„ZWdhd%eMd#eDeE   fd&„ZXdeeDeE   eEf   d#eEfd'„ZYdeeDeE   eEf   d#eEfd(„ZZd#eFfd)„Z[d#ej†                  fd*„Z\	 did"ej†                  d+eeeMe]eMd,f   f      d#eGfd-„Z^	 did"ej†                  d.eeeGeLf      d#eMfd/„Z_did"ej†                  d0eGd#e]eMeMf   fd1„Z`d2e]eMeMf   d3eMd4eMd#e]eMeMf   fd5„Zad6eKeLeeDe]f   f   d#eVfd7„Zbd6eKeLeeDe]f   f   d#eVfd8„Zcd9eeKeLeeDe]f   f      d#eVfd:„Zdd9eeKeLeeDe]f   f      d#eVfd;„Zedid"eeLdf   d<eef   d#dfd=„Zgdjd>eJfd?„Zhd@eLdAefdB„Zi	 did@eLdAee   fdC„Zjd@eLdAefdD„Zkd@eLdAefdE„ZlejeiekeldFœZm	 	 	 	 dkdGeeLdHf   dIeeM   dJeeM   dKeLdAee   d#ejÜ                  fdL„Zo	 dideeDe]eLdf   d<eef   d#edeDd   eDeDd      f   fdM„Zp	 	 	 	 	 	 	 	 	 	 	 	 dldNeeV   dOeef   dPeeV   dQeeefeDef   f      dReeefeDef   f      dSeeV   dTeeM   dUeeV   dVeeKeLeMf      dWeeV   dXeeKeLeMf      dYedZ   fd[„Zq G d\„ d]«      Zrd^eHd_e]eHd,f   d9eDeK   d#dfd`„ZsdaeDeL   dbeDeL   fdc„Zt edd¬e«       G df„ dg«      «       Zuy)mé    N)ÚIterable)Úredirect_stdout)Ú	dataclass)ÚBytesIO)ÚTYPE_CHECKINGÚCallableÚOptionalÚUnion)Úversioné   )ÚExplicitEnumÚis_av_availableÚis_cv2_availableÚis_decord_availableÚis_jax_tensorÚis_numpy_arrayÚis_tf_tensorÚis_torch_availableÚis_torch_tensorÚis_torchvision_availableÚis_vision_availableÚis_yt_dlp_availableÚloggingÚrequires_backendsÚto_numpy)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚIMAGENET_STANDARD_MEANÚIMAGENET_STANDARD_STDÚOPENAI_CLIP_MEANÚOPENAI_CLIP_STDz9.1.0)Úio)ÚInterpolationModezPIL.Image.Imageztorch.Tensorz
np.ndarrayc                   ó   — e Zd ZdZdZy)ÚChannelDimensionÚchannels_firstÚchannels_lastN)Ú__name__Ú
__module__Ú__qualname__ÚFIRSTÚLAST© ó    úV/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/image_utils.pyr%   r%   f   s   „ Ø€EØ�Dr.   r%   c                   ó   — e Zd ZdZdZy)ÚAnnotationFormatÚcoco_detectionÚcoco_panopticN)r(   r)   r*   ÚCOCO_DETECTIONÚCOCO_PANOPTICr-   r.   r/   r1   r1   k   s   „ Ø%€NØ#�Mr.   r1   c                   ód   — e Zd Zej                  j
                  Zej                  j
                  Zy)ÚAnnotionFormatN)r(   r)   r*   r1   r4   Úvaluer5   r-   r.   r/   r7   r7   p   s$   „ Ø%×4Ñ4×:Ñ:€NØ$×2Ñ2×8Ñ8�Mr.   r7   c                   ó6   — e Zd ZU eed<   eed<   eed<   eed<   y)ÚVideoMetadataÚtotal_num_framesÚfpsÚdurationÚvideo_backendN)r(   r)   r*   ÚintÚ__annotations__ÚfloatÚstrr-   r.   r/   r:   r:   u   s   … àÓØ	ƒJØƒOØÔr.   r:   c                 ób   — t        «       xr$ t        | t        j                  j                  «      S ©N)r   Ú
isinstanceÚPILÚImage©Úimgs    r/   Úis_pil_imagerJ   €   s   € ÜÓ ÒE¤Z°´S·Y±Y·_±_Ó%EÐEr.   c                   ó    — e Zd ZdZdZdZdZdZy)Ú	ImageTypeÚpillowÚtorchÚnumpyÚ
tensorflowÚjaxN)r(   r)   r*   rF   ÚTORCHÚNUMPYÚ
TENSORFLOWÚJAXr-   r.   r/   rL   rL   „   s   „ Ø
€CØ€EØ€EØ€JØ
�Cr.   rL   c                 ó>  — t        | «      rt        j                  S t        | «      rt        j                  S t        | «      rt        j                  S t        | «      rt        j                  S t        | «      rt        j                  S t        dt        | «      › �«      ‚)NzUnrecognised image type )rJ   rL   rF   r   rR   r   rS   r   rT   r   rU   Ú
ValueErrorÚtype©Úimages    r/   Úget_image_typer[   Œ   su   € Ü�EÔÜ�}‰}ÐÜ�uÔÜ�‰ÐÜ�eÔÜ�‰ÐÜ�EÔÜ×#Ñ#Ð#Ü�UÔÜ�}‰}ÐÜ
Ð/´°U³¨}Ð=Ó
>Ð>r.   c                 ó€   — t        | «      xs2 t        | «      xs% t        | «      xs t        | «      xs t	        | «      S rD   )rJ   r   r   r   r   rH   s    r/   Úis_valid_imager]   š   s8   € Ü˜ÓÒv¤¨sÓ 3Òv´ÀsÓ7KÒvÌ|Ð\_ÓO`ÒvÔdqÐruÓdvÐvr.   Úimagesc                 ó.   — | xr t        d„ | D «       «      S )Nc              3   ó2   K  — | ]  }t        |«      –— Œ y ­wrD   )r]   )Ú.0rZ   s     r/   ú	<genexpr>z*is_valid_list_of_images.<locals>.<genexpr>Ÿ   s   è ø€ ÒD°Eœ.¨×/ÑDùó   ‚©Úall)r^   s    r/   Úis_valid_list_of_imagesrf   ž   s   € ØÒD”cÑD¸VÔDÓDÐDr.   c                 ór   — t        | t        t        f«      r| D ]  }t        |«      rŒ y yt	        | «      syy)NFT)rE   ÚlistÚtupleÚvalid_imagesr]   )ÚimgsrI   s     r/   rj   rj   ¢   s?   € ä�$œœu˜Ô&Øò 	ˆCÜ Õ$Ùð	ð ô ˜DÔ!ØØr.   c                 óL   — t        | t        t        f«      rt        | d   «      S y)Nr   F)rE   rh   ri   r]   rH   s    r/   Ú
is_batchedrm   ®   s"   € Ü�#œœe�}Ô%Ü˜c !™fÓ%Ð%Ør.   rZ   Úreturnc                 ó¢   — | j                   t        j                  k(  ryt        j                  | «      dk\  xr t        j                  | «      dk  S )zV
    Checks to see whether the pixel values have already been rescaled to [0, 1].
    Fr   r   )ÚdtypeÚnpÚuint8ÚminÚmaxrY   s    r/   Úis_scaled_imageru   ´   s>   € ð ‡{�{”b—h‘hÒØô �6‰6�%‹=˜AÑÒ4¤"§&¡&¨£-°1Ñ"4Ð4r.   Úexpected_ndimsc           	      ó(  — t        | «      r| S t        | «      r| gS t        | «      rU| j                  |dz   k(  rt	        | «      } | S | j                  |k(  r| g} | S t        d|dz   › d|› d| j                  › d�«      ‚t        dt        | «      › d�«      ‚)a  
    Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1.
    If the input is a batch of images, it is converted to a list of images.

    Args:
        images (`ImageInput`):
            Image of images to turn into a list of images.
        expected_ndims (`int`, *optional*, defaults to 3):
            Expected number of dimensions for a single input image. If the input image has a different number of
            dimensions, an error is raised.
    r   z%Invalid image shape. Expected either z or z dimensions, but got z dimensions.ztInvalid image type. Expected either PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray, but got ú.)rm   rJ   r]   Úndimrh   rW   rX   )r^   rv   s     r/   Úmake_list_of_imagesrz   ¿   sÅ   € ô �&ÔØˆô �FÔàˆxˆä�fÔØ�;‰;˜.¨1Ñ,Ò,ä˜&“\ˆFð ˆð �[‰[˜NÒ*à�XˆFð ˆô	 Ø7¸ÈÑ8JÐ7KÈ4ÐP^ÐO_ð `Ø—K‘K�= ð.óð ô
 ð	 Ü $ V£˜~¨Qð	0óð r.   c                 ó<  — t        | t        t        f«      r=t        d„ | D «       «      r+t        d„ | D «       «      r| D ��cg c]  }|D ]  }|‘Œ Œ c}}S t        | t        t        f«      rXt	        | «      rMt        | d   «      s| d   j                  dk(  r| S | d   j                  dk(  r| D ��cg c]  }|D ]  }|‘Œ Œ c}}S t        | «      r7t        | «      s| j                  dk(  r| gS | j                  dk(  rt        | «      S t        d| › �«      ‚c c}}w c c}}w )a|  
    Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1.
    If the input is a nested list of images, it is converted to a flat list of images.
    Args:
        images (`Union[List[ImageInput], ImageInput]`):
            The input image.
    Returns:
        list: A list of images or a 4d array of images.
    c              3   óH   K  — | ]  }t        |t        t        f«      –— Œ y ­wrD   ©rE   rh   ri   ©ra   Úimages_is     r/   rb   z+make_flat_list_of_images.<locals>.<genexpr>õ   ó   è ø€ ÒK¸”
˜8¤d¬E ]×3ÑKùó   ‚ "c              3   ó2   K  — | ]  }t        |«      –— Œ y ­wrD   ©rf   r~   s     r/   rb   z+make_flat_list_of_images.<locals>.<genexpr>ö   ó   è ø€ ÒI°hÔ'¨×1ÑIùrc   r   é   é   z*Could not make a flat list of images from ©	rE   rh   ri   re   rf   rJ   ry   r]   rW   )r^   Úimg_listrI   s      r/   Úmake_flat_list_of_imagesr‰   æ   s  € ô 	�6œD¤%˜=Ô)ÜÑKÀFÔKÔKÜÑIÀ&ÔIÔIà$*×?˜°hÒ?¨s’Ð?�Ó?Ð?ä�&œ4¤˜-Ô(Ô-DÀVÔ-LÜ˜˜q™	Ô" f¨Q¡i§n¡n¸Ò&9ØˆMØ�!‰9�>‰>˜QÒØ(.×C˜H¸(ÒC°3’CÐC�CÓCÐCä�fÔÜ˜Ô 6§;¡;°!Ò#3Ø�8ˆOØ�;‰;˜!ÒÜ˜“<Ðä
ÐAÀ&ÀÐJÓ
KÐKùó @ùó Ds   Á DÂ.Dc                 ó   — t        | t        t        f«      r&t        d„ | D «       «      rt        d„ | D «       «      r| S t        | t        t        f«      rYt	        | «      rNt        | d   «      s| d   j                  dk(  r| gS | d   j                  dk(  r| D �cg c]  }t        |«      ‘Œ c}S t        | «      r9t        | «      s| j                  dk(  r| ggS | j                  dk(  rt        | «      gS t        d«      ‚c c}w )zð
    Ensure that the output is a nested list of images.
    Args:
        images (`Union[List[ImageInput], ImageInput]`):
            The input image.
    Returns:
        list: A list of list of images or a list of 4d array of images.
    c              3   óH   K  — | ]  }t        |t        t        f«      –— Œ y ­wrD   r}   r~   s     r/   rb   z-make_nested_list_of_images.<locals>.<genexpr>  r€   r�   c              3   ó2   K  — | ]  }t        |«      –— Œ y ­wrD   rƒ   r~   s     r/   rb   z-make_nested_list_of_images.<locals>.<genexpr>  r„   rc   r   r…   r†   z]Invalid input type. Must be a single image, a list of images, or a list of batches of images.r‡   )r^   rZ   s     r/   Úmake_nested_list_of_imagesr�   	  sâ   € ô 	�6œD¤%˜=Ô)ÜÑKÀFÔKÔKÜÑIÀ&ÔIÔIàˆô �&œ4¤˜-Ô(Ô-DÀVÔ-LÜ˜˜q™	Ô" f¨Q¡i§n¡n¸Ò&9Ø�8ˆOØ�!‰9�>‰>˜QÒØ-3Ö4 E”D˜•KÒ4Ð4ô �fÔÜ˜Ô 6§;¡;°!Ò#3Ø�H�:ÐØ�;‰;˜!ÒÜ˜“L�>Ð!ä
ÐtÓ
uÐuùò 5s   ÂC;c                 óÒ  — t        | t        t        f«      r|t        | d   t        t        f«      rct        | d   d   «      rRt	        | d   d   «      s?| d   d   j
                  dk(  r*| D ���cg c]  }|D ��cg c]  }|D ]  }|‘Œ Œ c}}‘Œ } }}}| S t        | t        t        f«      r\t        | d   «      rNt	        | d   «      s| d   j
                  dk(  r| gS | d   j
                  dk(  r]| D �cg c]  }t        |«      ‘Œ c}S t        | «      r9t	        | «      s| j
                  dk(  r| ggS | j
                  dk(  rt        | «      gS t        d| › �«      ‚c c}}w c c}}}w c c}w )zÅ
    Ensure that the input is a list of videos.
    Args:
        videos (`VideoInput`):
            Video or videos to turn into a list of videos.
    Returns:
        list: A list of videos.
    r   r†   r…   z"Could not make batched video from )rE   rh   ri   r]   rJ   ry   rW   )ÚvideosÚbatched_videosÚ
batch_listÚvideos       r/   Úmake_batched_videosr“   -  sN  € ô �&œ4¤˜-Ô(¬Z¸¸q¹	ÄDÌ%À=Ô-QÔVdÐekÐlmÑenÐopÑeqÔVrä˜F 1™I a™LÔ)¨f°Q©i¸©l×.?Ñ.?À1Ò.DØms×tÐtÐ[i¨~×V È:ÒVÀ%’uÐV�uÕVÐtˆFÒtàˆä	�FœT¤5˜MÔ	*¬~¸fÀQ¹iÔ/HÜ˜˜q™	Ô" f¨Q¡i§n¡n¸Ò&9Ø�8ˆOØ�A‰Y�^‰^˜qÒ Ø-3Ö4 E”D˜•KÒ4Ð4ä	˜Ô	Ü˜Ô 6§;¡;°!Ò#3Ø�H�:ÐØ�[‰[˜AÒÜ˜“L�>Ð!ä
Ð9¸&¸ÐBÓ
CÐCùó! WùÔtùò 5s   Á-
EÁ7EÂEÃ0E$ÅEc                 óâ   — t        | «      st        dt        | «      › �«      ‚t        «       r9t	        | t
        j                  j                  «      rt        j                  | «      S t        | «      S )NzInvalid image type: )
r]   rW   rX   r   rE   rF   rG   rq   Úarrayr   rH   s    r/   Úto_numpy_arrayr–   L  sP   € Ü˜#ÔÜÐ/´°S³	¨{Ð;Ó<Ð<äÔ¤¨C´·±·±Ô!AÜ�x‰x˜‹}ÐÜ�C‹=Ðr.   Únum_channels.c                 ó   — |�|nd}t        |t        «      r|fn|}| j                  dk(  rd\  }}n-| j                  dk(  rd\  }}nt        d| j                  › �«      ‚| j                  |   |v rD| j                  |   |v r3t
        j                  d| j                  › d�«       t        j                  S | j                  |   |v rt        j                  S | j                  |   |v rt        j                  S t        d«      ‚)	a[  
    Infers the channel dimension format of `image`.

    Args:
        image (`np.ndarray`):
            The image to infer the channel dimension of.
        num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):
            The number of channels of the image.

    Returns:
        The channel dimension of the image.
    ©r   r…   r…   )r   é   r†   z(Unsupported number of image dimensions: z4The channel dimension is ambiguous. Got image shape z,. Assuming channels are the first dimension.z(Unable to infer channel dimension format)
rE   r?   ry   rW   ÚshapeÚloggerÚwarningr%   r+   r,   )rZ   r—   Ú	first_dimÚlast_dims       r/   Úinfer_channel_dimension_formatr    U  sõ   € ð $0Ð#;‘<À€LÜ&0°¼sÔ&C�L‘?È€Là‡z�z�Q‚Ø"Ñˆ	‘8Ø	�‰�qŠØ"Ñˆ	‘8äÐCÀEÇJÁJÀ<ÐPÓQÐQà‡{�{�9Ñ Ñ-°%·+±+¸hÑ2GÈ<Ñ2WÜ�‰ØBÀ5Ç;Á;À-ÐO{Ð|ô	
ô  ×%Ñ%Ð%Ø	�‰�YÑ	 <Ñ	/Ü×%Ñ%Ð%Ø	�‰�XÑ	 ,Ñ	.Ü×$Ñ$Ð$Ü
Ð?Ó
@Ð@r.   Úinput_data_formatc                 óÀ   — |€t        | «      }|t        j                  k(  r| j                  dz
  S |t        j                  k(  r| j                  dz
  S t        d|› �«      ‚)a–  
    Returns the channel dimension axis of the image.

    Args:
        image (`np.ndarray`):
            The image to get the channel dimension axis of.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format of the image. If `None`, will infer the channel dimension from the image.

    Returns:
        The channel dimension axis of the image.
    r…   r   úUnsupported data format: )r    r%   r+   ry   r,   rW   )rZ   r¡   s     r/   Úget_channel_dimension_axisr¤   z  sd   € ð Ð Ü:¸5ÓAÐØÔ,×2Ñ2Ò2Ø�z‰z˜A‰~ÐØ	Ô.×3Ñ3Ò	3Ø�z‰z˜A‰~ÐÜ
Ð0Ð1BÐ0CÐDÓ
EÐEr.   Úchannel_dimc                 óü   — |€t        | «      }|t        j                  k(  r| j                  d   | j                  d   fS |t        j                  k(  r| j                  d   | j                  d   fS t        d|› �«      ‚)a�  
    Returns the (height, width) dimensions of the image.

    Args:
        image (`np.ndarray`):
            The image to get the dimensions of.
        channel_dim (`ChannelDimension`, *optional*):
            Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.

    Returns:
        A tuple of the image's height and width.
    éþÿÿÿéÿÿÿÿéýÿÿÿr£   )r    r%   r+   r›   r,   rW   )rZ   r¥   s     r/   Úget_image_sizerª   ’  s{   € ð ÐÜ4°UÓ;ˆàÔ&×,Ñ,Ò,Ø�{‰{˜2‰ §¡¨B¡Ð/Ð/Ø	Ô(×-Ñ-Ò	-Ø�{‰{˜2‰ §¡¨B¡Ð/Ð/äÐ4°[°MÐBÓCÐCr.   Ú
image_sizeÚ
max_heightÚ	max_widthc                 óx   — | \  }}||z  }||z  }t        ||«      }t        ||z  «      }t        ||z  «      }	||	fS )aË  
    Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
    Important, even if image_height < max_height and image_width < max_width, the image will be resized
    to at least one of the edges be equal to max_height or max_width.

    For example:
        - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
        - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)

    Args:
        image_size (`Tuple[int, int]`):
            The image to resize.
        max_height (`int`):
            The maximum allowed height.
        max_width (`int`):
            The maximum allowed width.
    )rs   r?   )
r«   r¬   r­   ÚheightÚwidthÚheight_scaleÚwidth_scaleÚ	min_scaleÚ
new_heightÚ	new_widths
             r/   Ú#get_image_size_for_max_height_widthr¶   ª  sV   € ð, �M€FˆEØ Ñ&€LØ˜eÑ#€KÜ�L +Ó.€IÜ�V˜iÑ'Ó(€JÜ�E˜IÑ%Ó&€IØ�yÐ Ð r.   Ú
annotationc                 ó¶   — t        | t        «      rId| v rEd| v rAt        | d   t        t        f«      r(t	        | d   «      dk(  st        | d   d   t        «      ryy)NÚimage_idÚannotationsr   TF©rE   Údictrh   ri   Úlen©r·   s    r/   Ú"is_valid_annotation_coco_detectionr¿   É  s`   € ä�:œtÔ$Ø˜*Ñ$Ø˜ZÑ'Ü�z -Ñ0´4¼°-Ô@ô �
˜=Ñ)Ó*¨aÒ/´:¸jÈÑ>WÐXYÑ>ZÔ\`Ô3að Ør.   c                 ó¾   — t        | t        «      rMd| v rId| v rEd| v rAt        | d   t        t        f«      r(t	        | d   «      dk(  st        | d   d   t        «      ryy)Nr¹   Úsegments_infoÚ	file_namer   TFr»   r¾   s    r/   Ú!is_valid_annotation_coco_panopticrÃ   Ø  sh   € ä�:œtÔ$Ø˜*Ñ$Ø˜zÑ)Ø˜:Ñ%Ü�z /Ñ2´T¼5°MÔBô �
˜?Ñ+Ó,°Ò1´ZÀ
È?Ñ@[Ð\]Ñ@^Ô`dÔ5eð Ør.   rº   c                 ó&   — t        d„ | D «       «      S )Nc              3   ó2   K  — | ]  }t        |«      –— Œ y ­wrD   )r¿   ©ra   Úanns     r/   rb   z3valid_coco_detection_annotations.<locals>.<genexpr>é  s   è ø€ ÒN¸3Ô1°#×6ÑNùrc   rd   ©rº   s    r/   Ú valid_coco_detection_annotationsrÉ   è  s   € ÜÑNÀ+ÔNÓNÐNr.   c                 ó&   — t        d„ | D «       «      S )Nc              3   ó2   K  — | ]  }t        |«      –— Œ y ­wrD   )rÃ   rÆ   s     r/   rb   z2valid_coco_panoptic_annotations.<locals>.<genexpr>í  s   è ø€ ÒM¸#Ô0°×5ÑMùrc   rd   rÈ   s    r/   Úvalid_coco_panoptic_annotationsrÌ   ì  s   € ÜÑMÀÔMÓMÐMr.   Útimeoutc                 óˆ  — t        t        dg«       t        | t        «      �r| j	                  d«      s| j	                  d«      rHt
        j                  j                  t        t        j                  | |¬«      j                  «      «      } nãt        j                  j                  | «      r t
        j                  j                  | «      } n¤| j	                  d«      r| j                  d«      d   } 	 t!        j"                  | j%                  «       «      }t
        j                  j                  t        |«      «      } n2t        | t
        j                  j                  «      r| } nt+        d«      ‚t
        j,                  j/                  | «      } | j1                  d«      } | S # t&        $ r}t)        d| › d	|› �«      ‚d
}~ww xY w)a3  
    Loads `image` to a PIL Image.

    Args:
        image (`str` or `PIL.Image.Image`):
            The image to convert to the PIL Image format.
        timeout (`float`, *optional*):
            The timeout value in seconds for the URL request.

    Returns:
        `PIL.Image.Image`: A PIL Image.
    Úvisionúhttp://úhttps://©rÍ   zdata:image/ú,r   z’Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got z. Failed with NzuIncorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image.ÚRGB)r   Ú
load_imagerE   rB   Ú
startswithrF   rG   Úopenr   ÚrequestsÚgetÚcontentÚosÚpathÚisfileÚsplitÚbase64ÚdecodebytesÚencodeÚ	ExceptionrW   Ú	TypeErrorÚImageOpsÚexif_transposeÚconvert)rZ   rÍ   Úb64Úes       r/   rÕ   rÕ   ð  sv  € ô ”j 8 *Ô-Ü�%œÕØ×Ñ˜IÔ&¨%×*:Ñ*:¸:Ô*Fô —I‘I—N‘N¤7¬8¯<©<¸ÀwÔ+O×+WÑ+WÓ#XÓY‰EÜ�W‰W�^‰^˜EÔ"Ü—I‘I—N‘N 5Ó)‰Eà×Ñ Ô.ØŸ™ CÓ(¨Ñ+�ðÜ×(Ñ(¨¯©«Ó8�ÜŸ	™	Ÿ™¤w¨s£|Ó4‘ô
 
�Eœ3Ÿ9™9Ÿ?™?Ô	+Ø‰äð Dó
ð 	
ô �L‰L×'Ñ'¨Ó.€EØ�M‰M˜%Ó €EØ€Løô ò Ü ð ið  joð  ipð  p~ð  @ð  ~Að  Bóð ûðús   Ã2AF" Æ"	GÆ+F<Æ<GÚmetadatac           	      ó  — | j                   }| j                  }|€-|�+t        ||z  |z  «      }||kD  rt        d|› d|› d|› d�«      ‚|�"t	        j
                  d|||z  t        ¬«      }|S t	        j
                  d|t        ¬«      }|S )a`  
    A default sampling function that replicates the logic used in get_uniform_frame_indices,
    while optionally handling `fps` if `num_frames` is not provided.

    Args:
        metadata (`VideoMetadata`):
            `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps".
        num_frames (`int`, *optional*):
            Number of frames to sample uniformly.
        fps (`int`, *optional*):
            Desired frames per second. Takes priority over num_frames if both are provided.

    Returns:
        `np.ndarray`: Array of frame indices to sample.
    z When loading the video with fps=z, we computed num_frames=z  which exceeds total_num_frames=z. Check fps or video metadata.r   )rp   )r;   r<   r?   rW   rq   Úarange)ré   Ú
num_framesr<   Úkwargsr;   Ú	video_fpsÚindicess          r/   Údefault_sample_indices_fnrð     sº   € ð   ×0Ñ0ÐØ—‘€Ið Ð˜c˜oÜÐ)¨IÑ5¸Ñ;Ó<ˆ
ØÐ(Ò(ÜØ2°3°%Ð7PÐQ[ÐP\ð ]2Ø2BÐ1CÐCaðcóð ð
 ÐÜ—)‘)˜AÐ/Ð1AÀJÑ1NÔVYÔZˆð €Nô —)‘)˜AÐ/´sÔ;ˆØ€Nr.   Ú
video_pathÚsample_indices_fnc                 óÌ  — t        t        dg«       ddl}|j                  | «      }t	        |j                  |j                  «      «      }|j                  |j                  «      }|r||z  nd}t        t	        |«      t        |«      t        |«      d¬«      } |dd|i|¤Ž}	d}
g }|j                  «       r�|j                  «       \  }}|snk|
|	v rI|j                  \  }}}|j                  ||j                  «      }|j                  |d|…d|…d|…f   «       |r|
dz  }
|
|k\  rn|j                  «       rŒ�|j!                  «        |	|_        t%        j&                  |«      |fS )	av  
    Decode a video using the OpenCV backend.

    Args:
        video_path (`str`):
            Path to the video file.
        sample_indices_fn (`Callable`):
            A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
            by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
            If not provided, simple uniform sampling with fps is performed.
            Example:
            def sample_indices_fn(metadata, **kwargs):
                return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

    Returns:
        Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
            - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
            - `VideoMetadata` object.
    Úcv2r   NÚopencv©r;   r<   r=   r>   ré   r   r-   )r   Úread_video_opencvrô   ÚVideoCapturer?   rÙ   ÚCAP_PROP_FRAME_COUNTÚCAP_PROP_FPSr:   rA   ÚisOpenedÚreadr›   ÚcvtColorÚCOLOR_BGR2RGBÚappendÚreleaseÚframes_indicesrq   Ústack)rñ   rò   rí   rô   r’   r;   rî   r=   ré   rï   ÚindexÚframesÚsuccessÚframer¯   r°   Úchannels                    r/   r÷   r÷   ?  s_  € ô2 Ô'¨%¨Ô1Ûà×Ñ˜ZÓ(€EÜ˜5Ÿ9™9 S×%=Ñ%=Ó>Ó?ÐØ—	‘	˜#×*Ñ*Ó+€IÙ/8Ð )Ò+¸a€HÜÜÐ-Ó.´E¸)Ó4DÌuÐU]ËÐnvô€Hñ  Ñ<¨Ð<°VÑ<€Gà€EØ€FØ
�.‰.Ô
ØŸ™›‰ˆ�ÙØØ�GÑØ%*§[¡[Ñ"ˆF�E˜7Ø—L‘L ¨×(9Ñ(9Ó:ˆEØ�M‰M˜%  & ¨!¨E¨'°1°W°9Ð <Ñ=Ô>ÙØ�Q‰JˆEØÐ$Ò$Øð �.‰.Õ
ð 
‡M�M„OØ%€HÔÜ�8‰8�FÓ˜XÐ%Ð%r.   c                 óX  — t        t        dg«       ddlm}m}  ||  |d«      ¬«      }|j                  «       }t        |«      }|r||z  nd}t        t        |«      t        |«      t        |«      d¬«      }	 |dd|	i|¤Ž}
|j                  |
«      j                  «       }|
|	_        ||	fS )a‚  
    Decode a video using the Decord backend.

    Args:
        video_path (`str`):
            Path to the video file.
        sample_indices_fn (`Callable`, *optional*):
            A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
            by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
            If not provided, simple uniform sampling with fps is performed.
            Example:
            def sample_indices_fn(metadata, **kwargs):
                return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

    Returns:
        Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
            - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
            - `VideoMetadata` object.
    Údecordr   )ÚVideoReaderÚcpu)ÚuriÚctxrö   ré   r-   )r   Úread_video_decordr	  r
  r  Úget_avg_fpsr½   r:   r?   rA   Ú	get_batchÚasnumpyr  )rñ   rò   rí   r
  r  Úvrrî   r;   r=   ré   rï   r  s               r/   r  r  x  s«   € ô2 Ô'¨(¨Ô4ß'á	˜©¨Q«Ô	0€BØ—‘Ó €IÜ˜2“wÐÙ/8Ð )Ò+¸a€HÜÜÐ-Ó.´E¸)Ó4DÌuÐU]ËÐnvô€Hñ  Ñ<¨Ð<°VÑ<€Gà�\‰\˜'Ó"×*Ñ*Ó,€FØ%€HÔØ�8ÐÐr.   c                 ó–  — t        t        dg«       ddl}|j                  | «      }|j                  j
                  d   j                  }|j                  j
                  d   j                  }|r||z  nd}t        t        |«      t        |«      t        |«      d¬«      } |dd|i|¤Ž}	g }
|j                  d«       |	d   }t        |j                  d¬«      «      D ](  \  }}||kD  r n|dk\  sŒ||	v sŒ|
j                  |«       Œ* t        j                   |
D �cg c]  }|j#                  d	¬
«      ‘Œ c}«      }|	|_        ||fS c c}w )a}  
    Decode the video with PyAV decoder.

    Args:
        video_path (`str`):
            Path to the video file.
        sample_indices_fn (`Callable`, *optional*):
            A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
            by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
            If not provided, simple uniform sampling with fps is performed.
            Example:
            def sample_indices_fn(metadata, **kwargs):
                return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

    Returns:
        Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
            - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
            - `VideoMetadata` object.
    Úavr   NÚpyavrö   ré   r¨   )r’   Úrgb24)Úformatr-   )r   Úread_video_pyavr  r×   Ústreamsr’   r  Úaverage_rater:   r?   rA   ÚseekÚ	enumerateÚdecoderÿ   rq   r  Ú
to_ndarrayr  )rñ   rò   rí   r  Ú	containerr;   rî   r=   ré   rï   r  Ú	end_indexÚir  Úxr’   s                   r/   r  r  £  sB  € ô2 ”o¨ vÔ.Ûà—‘˜
Ó#€IØ ×(Ñ(×.Ñ.¨qÑ1×8Ñ8ÐØ×!Ñ!×'Ñ'¨Ñ*×7Ñ7€IÙ/8Ð )Ò+¸a€HÜÜÐ-Ó.´E¸)Ó4DÌuÐU]ËÐntô€Hñ  Ñ<¨Ð<°VÑ<€Gà€FØ‡N�N�1ÔØ˜‘€IÜ˜i×.Ñ.°QÐ.Ó7Ó8ò !‰ˆˆ5ØˆyŠ=ÙØ�‹6�a˜7’lØ�M‰M˜%Õ ð	!ô �H‰H¸FÖC°q�a—l‘l¨'�lÕ2ÒCÓD€EØ%€HÔØ�(ˆ?Ðùò Ds   ÄEc                 ó<  — t        j                  | dddd¬«      \  }}}|d   }|j                  d«      }|r||z  nd}t        t	        |«      t        |«      t        |«      d¬	«      }	 |dd
|	i|¤Ž}
||
   j                  «       j                  «       }|
|	_        ||	fS )a„  
    Decode the video with torchvision decoder.

    Args:
        video_path (`str`):
            Path to the video file.
        sample_indices_fn (`Callable`, *optional*):
            A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
            by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
            If not provided, simple uniform sampling with fps is performed.
            Example:
            def sample_indices_fn(metadata, **kwargs):
                return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

    Returns:
        Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
            - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
            - `VideoMetadata` object.
    g        NÚsecÚTHWC)Ú	start_ptsÚend_ptsÚpts_unitÚoutput_formatrî   r   Útorchvisionrö   ré   r-   )	Útorchvision_ioÚ
read_videoÚsizer:   r?   rA   Ú
contiguousrO   r  )rñ   rò   rí   r’   Ú_Úinforî   r;   r=   ré   rï   s              r/   Úread_video_torchvisionr1  Ö  s¸   € ô0 $×.Ñ.ØØØØØô�N€Eˆ1ˆdð �[Ñ!€IØ—z‘z !“}ÐÙ/8Ð )Ò+¸a€HÜÜÐ-Ó.Ü�)ÓÜ�x“Ø#ô	€Hñ  Ñ<¨Ð<°VÑ<€Gà�'‰N×%Ñ%Ó'×-Ñ-Ó/€EØ%€HÔØ�(ˆ?Ðr.   )r	  rõ   r  r*  r’   Ú
VideoInputrì   r<   Úbackendc                 óZ  ‡‡— ‰�‰�|€t        d«      ‚|€ˆˆfd„}|}| j                  d«      s| j                  d«      rˆt        «       st        d«      ‚t	        t
        dg«       dd	lm} t        «       }t        |«      5   |«       5 }	|	j                  | g«       ddd«       ddd«       |j                  «       }
t        |
«      }nª| j                  d
«      s| j                  d«      r)t        t        j                  | «      j                  «      }n_t        j                   j#                  | «      r| }n=t%        | «      s$t'        | t(        t*        f«      rt%        | d   «      rd}nt-        d«      ‚| j                  d
«      xs | j                  d«      }|r|dv rt        d«      ‚|€| S t/        «       s|dk(  s-t1        «       s|dk(  st3        «       s|dk(  st5        «       s|dk(  rt        d|› d|› d�«      ‚t6        |   } |||fi |¤Ž\  } }| |fS # 1 sw Y   �ŒyxY w# 1 sw Y   �Œ~xY w)aÍ  
    Loads `video` to a numpy array.

    Args:
        video (`str` or `VideoInput`):
            The video to convert to the numpy array format. Can be a link to video or local path.
        num_frames (`int`, *optional*):
            Number of frames to sample uniformly. If not passed, the whole video is loaded.
        fps (`int`, *optional*):
            Number of frames to sample per second. Should be passed only when `num_frames=None`.
            If not specified and `num_frames==None`, all frames are sampled.
        backend (`str`, *optional*, defaults to `"opencv"`):
            The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision"]. Defaults to "opencv".
        sample_indices_fn (`Callable`, *optional*):
            A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
            by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
            If not provided, simple uniformt sampling with fps is performed, otherwise `sample_indices_fn` has priority over other args.
            The function expects at input the all args along with all kwargs passed to `load_video` and should output valid
            indices at which the video should be sampled. For example:

            Example:
            def sample_indices_fn(metadata, **kwargs):
                return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)

    Returns:
        Tuple[`np.array`, Dict]: A tuple containing:
            - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
            - Metadata dictionary.
    Nzc`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!c                 ó"   •— t        | f‰‰dœ|¤ŽS )N)rì   r<   )rð   )ré   Ú	fn_kwargsr<   rì   s     €€r/   Úsample_indices_fn_funcz*load_video.<locals>.sample_indices_fn_func=  s   ø€ Ü,¨XÐcÀ*ÐRUÑcÐYbÑcÐcr.   zhttps://www.youtube.comzhttp://www.youtube.comzETo load a video from YouTube url you have  to install `yt_dlp` first.Úyt_dlpr   )Ú	YoutubeDLrÐ   rÑ   zVIncorrect format used for video. Should be an url linking to an video or a local path.)rõ   r*  zlIf you are trying to load a video from URL, you can decode the video only with `pyav` or `decord` as backendr	  r  rõ   r*  zYou chose backend=zf for loading the video but the required library is not found in your environment Make sure to install z before loading the video.)rW   rÖ   r   ÚImportErrorr   Ú
load_videor8  r9  r   r   ÚdownloadÚgetvaluerØ   rÙ   rÚ   rÛ   rÜ   rÝ   r]   rE   rh   ri   rã   r   r   r   r   ÚVIDEO_DECODERS)r’   rì   r<   r3  rò   rí   r7  r9  ÚbufferÚfÚ	bytes_objÚfile_objÚvideo_is_urlÚvideo_decoderré   s    ``            r/   r;  r;    s.  ù€ ðN €˜:Ð1Ð6GÐ6OÜØqó
ð 	
ð
 Ð õ	dð 3Ðà×ÑÐ1Ô2°e×6FÑ6FÐG_Ô6`Ü"Ô$ÜÐeÓfÐfäœ* x jÔ1Ý$ä“ˆÜ˜VÓ$ñ 	 ¡i£kð 	 °QØ�J‰J˜�wÔ÷	 ÷ 	 à—O‘OÓ%ˆ	Ü˜9Ó%‰Ø	×	Ñ	˜)Ô	$¨×(8Ñ(8¸Ô(DÜœ8Ÿ<™<¨Ó.×6Ñ6Ó7‰Ü	�‰�‰˜Ô	Ø‰Ü	˜Ô	¤:¨e´d¼E°]Ô#CÌÐW\Ð]^ÑW_ÔH`Ø‰äÐpÓqÐqð ×#Ñ# IÓ.ÒN°%×2BÑ2BÀ:Ó2N€LÙ˜Ð#<Ñ<ÜØzó
ð 	
ð ÐØˆô !Ô" w°(Ò':ÜÔ! g°Ò&7Ü Ô" w°(Ò':Ü(Ô*¨w¸-Ò/GäØ   	ð *$Ø$+ 9Ð,FðHó
ð 	
ô
 # 7Ñ+€MÙ# HÐ.?ÑJÀ6ÑJ�O€Eˆ8Ø�(ˆ?Ð÷K	 ñ 	 ú÷ 	 ñ 	 ús$   ÂH Â	HÂH ÈH	ÈH È H*c                 ó<  — t        | t        t        f«      rjt        | «      rDt        | d   t        t        f«      r+| D ��cg c]  }|D �cg c]  }t	        ||¬«      ‘Œ c}‘Œ c}}S | D �cg c]  }t	        ||¬«      ‘Œ c}S t	        | |¬«      S c c}w c c}}w c c}w )a  Loads images, handling different levels of nesting.

    Args:
      images: A single image, a list of images, or a list of lists of images to load.
      timeout: Timeout for loading images.

    Returns:
      A single image, a list of images, a list of lists of images.
    r   rÒ   )rE   rh   ri   r½   rÕ   )r^   rÍ   Úimage_grouprZ   s       r/   Úload_imagesrG  r  s   € ô �&œ4¤˜-Ô(ÜˆvŒ;œ: f¨Q¡i´$¼°Ô?Øek×lÐVaÀ[ÖQ¸E”Z ¨wÖ7ÔQÓlÐlàDJÖK¸5”J˜u¨gÖ6ÒKÐKä˜&¨'Ô2Ð2ùò	 RùÓlùâKs   Á 	BÁ	BÁBÁ*BÂBÚ
do_rescaleÚrescale_factorÚdo_normalizeÚ
image_meanÚ	image_stdÚdo_padÚsize_divisibilityÚdo_center_cropÚ	crop_sizeÚ	do_resizer-  ÚresampleÚPILImageResamplingc                 ó¤   — | r|€t        d«      ‚|r|€t        d«      ‚|r|�|€t        d«      ‚|r|€t        d«      ‚|	r|
�|€t        d«      ‚yy)a‡  
    Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method.
    Raises `ValueError` if arguments incompatibility is caught.
    Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`,
    sometimes `size_divisibility`, and sometimes `size`. New models and processors added should follow
    existing arguments when possible.

    Nz=`rescale_factor` must be specified if `do_rescale` is `True`.zzDepending on the model, `size_divisibility`, `size_divisor`, `pad_size` or `size` must be specified if `do_pad` is `True`.zP`image_mean` and `image_std` must both be specified if `do_normalize` is `True`.z<`crop_size` must be specified if `do_center_crop` is `True`.zA`size` and `resample` must be specified if `do_resize` is `True`.)rW   )rH  rI  rJ  rK  rL  rM  rN  rO  rP  rQ  r-  rR  s               r/   Úvalidate_preprocess_argumentsrU  ‡  s‚   € ñ, �nÐ,ÜÐXÓYÐYáÐ#Ð+äð Ió
ð 	
ñ ˜Ð+¨yÐ/@ÜÐkÓlÐlá˜)Ð+ÜÐWÓXÐXá�d�l hÐ&6ÜÐ\Ó]Ð]ð '7€yr.   c                   óœ   — e Zd ZdZd„ Zdd„Zd„ Zdej                  de	e
ef   dej                  fd	„Zdd
„Zd„ Zdd„Zdd„Zd„ Zd„ Zdd„Zy)ÚImageFeatureExtractionMixinzD
    Mixin that contain utilities for preparing image features.
    c                 ó´   — t        |t        j                  j                  t        j                  f«      s$t        |«      st        dt        |«      › d�«      ‚y y )Nz	Got type zS which is not supported, only `PIL.Image.Image`, `np.array` and `torch.Tensor` are.)rE   rF   rG   rq   Úndarrayr   rW   rX   ©ÚselfrZ   s     r/   Ú_ensure_format_supportedz4ImageFeatureExtractionMixin._ensure_format_supported¶  sQ   € Ü˜%¤#§)¡)§/¡/´2·:±:Ð!>Ô?ÌÐX]ÔH^ÜØœD ›K˜=ð )&ð &óð ð I_Ð?r.   Nc                 óÔ  — | j                  |«       t        |«      r|j                  «       }t        |t        j
                  «      r¡|€'t        |j                  d   t        j                  «      }|j                  dk(  r$|j                  d   dv r|j                  ddd«      }|r|dz  }|j                  t        j                  «      }t        j                  j                  |«      S |S )a"  
        Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
        needed.

        Args:
            image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
                The image to convert to the PIL Image format.
            rescale (`bool`, *optional*):
                Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
                default to `True` if the image type is a floating type, `False` otherwise.
        r   r…   r™   r   rš   éÿ   )r\  r   rO   rE   rq   rY  ÚflatÚfloatingry   r›   Ú	transposeÚastyperr   rF   rG   Ú	fromarray)r[  rZ   Úrescales      r/   Úto_pil_imagez(ImageFeatureExtractionMixin.to_pil_image½  s´   € ð 	×%Ñ% eÔ,ä˜5Ô!Ø—K‘K“MˆEä�eœRŸZ™ZÔ(Øˆä$ U§Z¡Z°¡]´B·K±KÓ@�à�z‰z˜QŠ 5§;¡;¨q¡>°VÑ#;ØŸ™¨¨1¨aÓ0�ÙØ ™�Ø—L‘L¤§¡Ó*ˆEÜ—9‘9×&Ñ& uÓ-Ð-Øˆr.   c                 ó’   — | j                  |«       t        |t        j                  j                  «      s|S |j	                  d«      S )z—
        Converts `PIL.Image.Image` to RGB format.

        Args:
            image (`PIL.Image.Image`):
                The image to convert.
        rÔ   )r\  rE   rF   rG   ræ   rZ  s     r/   Úconvert_rgbz'ImageFeatureExtractionMixin.convert_rgbÛ  s8   € ð 	×%Ñ% eÔ,Ü˜%¤§¡§¡Ô1ØˆLà�}‰}˜UÓ#Ð#r.   rZ   Úscalern   c                 ó.   — | j                  |«       ||z  S )z7
        Rescale a numpy image by scale amount
        )r\  )r[  rZ   rh  s      r/   rd  z#ImageFeatureExtractionMixin.rescaleé  s   € ð 	×%Ñ% eÔ,Ø�u‰}Ðr.   c                 óÐ  — | j                  |«       t        |t        j                  j                  «      rt	        j
                  |«      }t        |«      r|j                  «       }|€'t        |j                  d   t        j                  «      n|}|r/| j                  |j                  t        j                  «      d«      }|r"|j                  dk(  r|j                  ddd«      }|S )aÓ  
        Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
        dimension.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image to convert to a NumPy array.
            rescale (`bool`, *optional*):
                Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will
                default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise.
            channel_first (`bool`, *optional*, defaults to `True`):
                Whether or not to permute the dimensions of the image to put the channel dimension first.
        r   çp?r…   rš   r   )r\  rE   rF   rG   rq   r•   r   rO   r_  Úintegerrd  rb  Úfloat32ry   ra  )r[  rZ   rd  Úchannel_firsts       r/   r–   z*ImageFeatureExtractionMixin.to_numpy_arrayð  s§   € ð 	×%Ñ% eÔ,ä�eœSŸY™YŸ_™_Ô-Ü—H‘H˜U“OˆEä˜5Ô!Ø—K‘K“MˆEà;B¸?”*˜UŸZ™Z¨™]¬B¯J©JÔ7ÐPWˆáØ—L‘L §¡¬b¯j©jÓ!9¸9ÓEˆEá˜UŸZ™Z¨1š_Ø—O‘O A q¨!Ó,ˆEàˆr.   c                 óÞ   — | j                  |«       t        |t        j                  j                  «      r|S t	        |«      r|j                  d«      }|S t        j                  |d¬«      }|S )z½
        Expands 2-dimensional `image` to 3 dimensions.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image to expand.
        r   )Úaxis)r\  rE   rF   rG   r   Ú	unsqueezerq   Úexpand_dimsrZ  s     r/   rr  z'ImageFeatureExtractionMixin.expand_dims  s_   € ð 	×%Ñ% eÔ,ô �eœSŸY™YŸ_™_Ô-ØˆLä˜5Ô!Ø—O‘O AÓ&ˆEð ˆô —N‘N 5¨qÔ1ˆEØˆr.   c                 óÊ  — | j                  |«       t        |t        j                  j                  «      r| j	                  |d¬«      }nw|rut        |t
        j                  «      r0| j                  |j                  t
        j                  «      d«      }n+t        |«      r | j                  |j                  «       d«      }t        |t
        j                  «      r‘t        |t
        j                  «      s.t        j                  |«      j                  |j                  «      }t        |t
        j                  «      sèt        j                  |«      j                  |j                  «      }n¹t        |«      r®ddl}t        ||j                  «      s?t        |t
        j                  «      r |j                   |«      }n |j"                  |«      }t        ||j                  «      s?t        |t
        j                  «      r |j                   |«      }n |j"                  |«      }|j$                  dk(  r)|j&                  d   dv r||dd…ddf   z
  |dd…ddf   z  S ||z
  |z  S )a  
        Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array
        if it's a PIL Image.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image to normalize.
            mean (`List[float]` or `np.ndarray` or `torch.Tensor`):
                The mean (per channel) to use for normalization.
            std (`List[float]` or `np.ndarray` or `torch.Tensor`):
                The standard deviation (per channel) to use for normalization.
            rescale (`bool`, *optional*, defaults to `False`):
                Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will
                happen automatically.
        T)rd  rk  r   Nr…   r™   )r\  rE   rF   rG   r–   rq   rY  rd  rb  rm  r   rA   r•   rp   rN   ÚTensorÚ
from_numpyÚtensorry   r›   )r[  rZ   ÚmeanÚstdrd  rN   s         r/   Ú	normalizez%ImageFeatureExtractionMixin.normalize$  s¿  € ð  	×%Ñ% eÔ,ä�eœSŸY™YŸ_™_Ô-Ø×'Ñ'¨°tÐ'Ó<‰Eñ Ü˜%¤§¡Ô,ØŸ™ U§\¡\´"·*±*Ó%=¸yÓI‘Ü  Ô'ØŸ™ U§[¡[£]°IÓ>�ä�eœRŸZ™ZÔ(Ü˜d¤B§J¡JÔ/Ü—x‘x “~×,Ñ,¨U¯[©[Ó9�Ü˜c¤2§:¡:Ô.Ü—h‘h˜s“m×*Ñ*¨5¯;©;Ó7‘Ü˜UÔ#Ûä˜d E§L¡LÔ1Ü˜d¤B§J¡JÔ/Ø+˜5×+Ñ+¨DÓ1‘Dà'˜5Ÿ<™<¨Ó-�DÜ˜c 5§<¡<Ô0Ü˜c¤2§:¡:Ô.Ø*˜%×*Ñ*¨3Ó/‘Cà&˜%Ÿ,™, sÓ+�Cà�:‰:˜Š?˜uŸ{™{¨1™~°Ñ7Ø˜D¢ D¨$ Ñ/Ñ/°3²q¸$À°}Ñ3EÑEÐEà˜D‘L CÑ'Ð'r.   c                 óª  — |�|nt         j                  }| j                  |«       t        |t        j
                  j
                  «      s| j                  |«      }t        |t        «      rt        |«      }t        |t        «      st        |«      dk(  r®|rt        |t        «      r||fn	|d   |d   f}n�|j                  \  }}||k  r||fn||f\  }}	t        |t        «      r|n|d   }
||
k(  r|S |
t        |
|	z  |z  «      }}|�.||
k  rt        d|› d|› �«      ‚||kD  rt        ||z  |z  «      |}}||k  r||fn||f}|j                  ||¬«      S )a›  
        Resizes `image`. Enforces conversion of input to PIL.Image.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image to resize.
            size (`int` or `Tuple[int, int]`):
                The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be
                matched to this.

                If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
                `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to
                this number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
            resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
                The filter to user for resampling.
            default_to_square (`bool`, *optional*, defaults to `True`):
                How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a
                square (`size`,`size`). If set to `False`, will replicate
                [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
                with support for resizing only the smallest edge and providing an optional `max_size`.
            max_size (`int`, *optional*, defaults to `None`):
                The maximum allowed for the longer edge of the resized image: if the longer edge of the image is
                greater than `max_size` after being resized according to `size`, then the image is resized again so
                that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller
                edge may be shorter than `size`. Only used if `default_to_square` is `False`.

        Returns:
            image: A resized `PIL.Image.Image`.
        r   r   zmax_size = zN must be strictly greater than the requested size for the smaller edge size = )rR  )rS  ÚBILINEARr\  rE   rF   rG   re  rh   ri   r?   r½   r-  rW   Úresize)r[  rZ   r-  rR  Údefault_to_squareÚmax_sizer°   r¯   ÚshortÚlongÚrequested_new_shortÚ	new_shortÚnew_longs                r/   r|  z"ImageFeatureExtractionMixin.resizeX  sy  € ð<  (Ð3‘8Ô9K×9TÑ9Tˆà×%Ñ% eÔ,ä˜%¤§¡§¡Ô1Ø×%Ñ% eÓ,ˆEä�dœDÔ!Ü˜“;ˆDä�dœCÔ ¤C¨£I°¢NÙ Ü'1°$¼Ô'<˜˜d‘|À4ÈÁ7ÈDÐQRÉGÐBT‘à %§
¡
‘��và16¸&²˜u f™oÀvÈuÀo‘��tÜ.8¸¼sÔ.C¡dÈÈaÉÐ#àÐ/Ò/Ø �Là&9¼3Ð?RÐUYÑ?YÐ\aÑ?aÓ;b˜8�	àÐ'ØÐ#6Ò6Ü(Ø)¨(¨ð 4@Ø@D¸vðGóð ð   (Ò*Ü.1°(¸YÑ2FÈÑ2QÓ.RÐT\ 8˜	à05¸²˜	 8Ñ,ÀhÐPYÐEZ�à�|‰|˜D¨8ˆ|Ó4Ð4r.   c                 óˆ  — | j                  |«       t        |t        «      s||f}t        |«      st        |t        j
                  «      rP|j                  dk(  r| j                  |«      }|j                  d   dv r|j                  dd n|j                  dd }n|j                  d   |j                  d   f}|d   |d   z
  dz  }||d   z   }|d   |d   z
  dz  }||d   z   }t        |t        j                  j                  «      r|j                  ||||f«      S |j                  d   dv rdnd}|sKt        |t        j
                  «      r|j                  ddd«      }t        |«      r|j                  ddd«      }|dk\  r!||d   k  r|dk\  r||d   k  r|d||…||…f   S |j                  dd	 t        |d   |d   «      t        |d   |d   «      fz   }	t        |t        j
                  «      rt	        j                   ||	¬
«      }
nt        |«      r|j#                  |	«      }
|	d	   |d   z
  dz  }||d   z   }|	d   |d   z
  dz  }||d   z   }|
d||…||…f<   ||z  }||z  }||z  }||z  }|
dt        d|«      t%        |
j                  d	   |«      …t        d|«      t%        |
j                  d   |«      …f   }
|
S )a•  
        Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the
        size given, it will be padded (so the returned result has the size asked).

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):
                The image to resize.
            size (`int` or `Tuple[int, int]`):
                The size to which crop the image.

        Returns:
            new_image: A center cropped `PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape: (n_channels,
            height, width).
        rš   r   r™   r   NTF.r§   )r›   r¨   )r\  rE   ri   r   rq   rY  ry   rr  r›   r-  rF   rG   Úcropra  Úpermutert   Ú
zeros_likeÚ	new_zerosrs   )r[  rZ   r-  Úimage_shapeÚtopÚbottomÚleftÚrightrn  Ú	new_shapeÚ	new_imageÚtop_padÚ
bottom_padÚleft_padÚ	right_pads                  r/   Úcenter_cropz'ImageFeatureExtractionMixin.center_crop›  sý  € ð 	×%Ñ% eÔ,ä˜$¤Ô&Ø˜$�<ˆDô ˜5Ô!¤Z°´r·z±zÔ%BØ�z‰z˜QŠØ×(Ñ(¨Ó/�Ø-2¯[©[¸©^¸vÑ-E˜%Ÿ+™+ a b™/È5Ï;É;ÐWYÐXYÈ?‰Kà Ÿ:™: a™=¨%¯*©*°Q©-Ð8ˆKà˜1‰~  Q¡Ñ'¨AÑ-ˆØ�t˜A‘w‘ˆØ˜A‘  a¡Ñ(¨QÑ.ˆØ�t˜A‘w‘ˆô �eœSŸY™YŸ_™_Ô-Ø—:‘:˜t S¨%°Ð8Ó9Ð9ð !&§¡¨A¡°&Ñ 8™¸eˆñ Ü˜%¤§¡Ô,ØŸ™¨¨1¨aÓ0�Ü˜uÔ%ØŸ™ a¨¨AÓ.�ð �!Š8˜ +¨a¡.Ò0°T¸Q²YÀ5ÈKÐXYÉNÒCZØ˜˜c &˜j¨$¨u¨*Ð4Ñ5Ð5ð —K‘K  Ð$¬¨D°©G°[À±^Ó(DÄcÈ$ÈqÉ'ÐS^Ð_`ÑSaÓFbÐ'cÑcˆ	Ü�eœRŸZ™ZÔ(ÜŸ™ e°9Ô=‰IÜ˜UÔ#ØŸ™¨	Ó2ˆIà˜R‘= ;¨q¡>Ñ1°aÑ7ˆØ˜{¨1™~Ñ-ˆ
Ø˜b‘M K°¡NÑ2°qÑ8ˆØ˜{¨1™~Ñ-ˆ	ØAFˆ	�#�w˜zÐ)¨8°IÐ+=Ð=Ñ>àˆw‰ˆØ�'ÑˆØ�ÑˆØ�ÑˆàØ”�Q˜“œs 9§?¡?°2Ñ#6¸Ó?Ð?ÄÀQÈÃÔPSÐT]×TcÑTcÐdfÑTgÐinÓPoÐAoÐoñ
ˆ	ð Ðr.   c                 ó¬   — | j                  |«       t        |t        j                  j                  «      r| j	                  |«      }|ddd…dd…dd…f   S )a   
        Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of
        `image` to a NumPy array if it's a PIL Image.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel dimension should
                be first.
        Nr¨   )r\  rE   rF   rG   r–   rZ  s     r/   Úflip_channel_orderz.ImageFeatureExtractionMixin.flip_channel_orderæ  sI   € ð 	×%Ñ% eÔ,ä�eœSŸY™YŸ_™_Ô-Ø×'Ñ'¨Ó.ˆEà‘T�r�Tš1ša�ZÑ Ð r.   c                 óø   — |�|nt         j                  j                  }| j                  |«       t	        |t         j                  j                  «      s| j                  |«      }|j                  ||||||¬«      S )aÖ  
        Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
        counter clockwise around its centre.

        Args:
            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
                The image to rotate. If `np.ndarray` or `torch.Tensor`, will be converted to `PIL.Image.Image` before
                rotating.

        Returns:
            image: A rotated `PIL.Image.Image`.
        )rR  ÚexpandÚcenterÚ	translateÚ	fillcolor)rF   rG   ÚNEARESTr\  rE   re  Úrotate)r[  rZ   ÚanglerR  r˜  r™  rš  r›  s           r/   r�  z"ImageFeatureExtractionMixin.rotate÷  sn   € ð  (Ð3‘8¼¿¹×9JÑ9Jˆà×%Ñ% eÔ,ä˜%¤§¡§¡Ô1Ø×%Ñ% eÓ,ˆEà�|‰|Ø˜H¨V¸FÈiÐclð ó 
ð 	
r.   rD   )NT)F)NTN)Nr   NNN)r(   r)   r*   Ú__doc__r\  re  rg  rq   rY  r
   rA   r?   rd  r–   rr  ry  r|  r”  r–  r�  r-   r.   r/   rW  rW  ±  sj   „ ñòóò<$ð˜RŸZ™Zð °°e¸S°jÑ0Að ÀbÇjÁjó óò@ó(2(óhA5òFIòV!ô"
r.   rW  Úannotation_formatÚsupported_annotation_formatsc                 óØ   — | |vrt        dt        › d|› �«      ‚| t        j                  u rt	        |«      st        d«      ‚| t        j
                  u rt        |«      st        d«      ‚y y )NzUnsupported annotation format: z must be one of zäInvalid COCO detection annotations. Annotations must a dict (single image) or list of dicts (batch of images) with the following keys: `image_id` and `annotations`, with the latter being a list of annotations in the COCO format.zòInvalid COCO panoptic annotations. Annotations must a dict (single image) or list of dicts (batch of images) with the following keys: `image_id`, `file_name` and `segments_info`, with the latter being a list of annotations in the COCO format.)rW   r  r1   r4   rÉ   r5   rÌ   )r   r¡  rº   s      r/   Úvalidate_annotationsr£    s‰   € ð
 Ð <Ñ<ÜÐ:¼6¸(ÐBRÐSoÐRpÐqÓrÐràÔ,×;Ñ;Ñ;Ü/°Ô<ÜðBóð ð Ô,×:Ñ:Ñ:Ü.¨{Ô;ÜðMóð ð <ð ;r.   Úvalid_processor_keysÚcaptured_kwargsc                 ó¤   — t        |«      j                  t        | «      «      }|r+dj                  |«      }t        j	                  d|› d�«       y y )Nz, zUnused or unrecognized kwargs: rx   )ÚsetÚ
differenceÚjoinrœ   r�   )r¤  r¥  Úunused_keysÚunused_key_strs       r/   Úvalidate_kwargsr¬  )  sJ   € Ü�oÓ&×1Ñ1´#Ð6JÓ2KÓL€KÙØŸ™ ;Ó/ˆä�‰Ð8¸Ð8HÈÐJÕKð r.   T)Úfrozenc                   ó�   — e Zd ZU dZdZee   ed<   dZee   ed<   dZ	ee   ed<   dZ
ee   ed<   dZee   ed<   dZee   ed<   d	„ Zy)
ÚSizeDictz>
    Hashable dictionary to store image size information.
    Nr¯   r°   Úlongest_edgeÚshortest_edger¬   r­   c                 óP   — t        | |«      rt        | |«      S t        d|› d�«      ‚)NzKey z not found in SizeDict.)ÚhasattrÚgetattrÚKeyError)r[  Úkeys     r/   Ú__getitem__zSizeDict.__getitem__>  s.   € Ü�4˜ÔÜ˜4 Ó%Ð%Ü˜˜c˜UÐ"9Ð:Ó;Ð;r.   )r(   r)   r*   rŸ  r¯   r	   r?   r@   r°   r°  r±  r¬   r­   r·  r-   r.   r/   r¯  r¯  1  sb   … ñð !€FˆH�S‰MÓ Ø€Eˆ8�C‰=ÓØ"&€L�(˜3‘-Ó&Ø#'€M�8˜C‘=Ó'Ø $€J�˜‘Ó$Ø#€Iˆx˜‰}Ó#ó<r.   r¯  )r…   rD   )NN)NNrõ   N)NNNNNNNNNNNN)vrß   rÛ   Úcollections.abcr   Ú
contextlibr   Údataclassesr   r"   r   Útypingr   r   r	   r
   rO   rq   rØ   Ú	packagingr   Úutilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Úutils.constantsr   r   r   r   r    r!   Ú	PIL.ImagerF   ÚPIL.ImageOpsÚparseÚ__version__Úbase_versionrG   Ú
ResamplingrS  r*  r+  Útorchvision.transformsr#   rœ  ÚBOXr{  ÚHAMMINGÚBICUBICÚLANCZOSÚpil_torch_interpolation_mappingrN   Ú
get_loggerr(   rœ   rY  rh   Ú
ImageInputr2  r%   r1   r7   r:   r¼   rB   r?   ÚAnnotationTyperJ   rL   r[   r]   rf   rj   rm   Úboolru   rz   r‰   r�   r“   r–   ri   r    r¤   rª   r¶   r¿   rÃ   rÉ   rÌ   rA   rÕ   rð   r÷   r  r  r1  r>  r•   r;  rG  rU  rW  r£  r¬  r¯  r-   r.   r/   ú<module>rÏ     s¤  ðó Û 	Ý $Ý &Ý !Ý ß ;Ó ;ã Û Ý ÷÷ ÷ ÷ ñ ÷"÷ ñ ÕÛÛà€w‡}�}�]�W—]‘] 3§?¡?Ó3×@Ñ@ÓAÀ]ÀWÇ]Á]ÐSZÓE[Ò[Ø ŸY™Y×1Ñ1Ñà ŸY™YÐáÔ!Ý4Ý<ð ×&Ñ&Ð(9×(AÑ(AØ×"Ñ"Ð$5×$9Ñ$9Ø×'Ñ'Ð):×)CÑ)CØ×&Ñ&Ð(9×(AÑ(AØ×&Ñ&Ð(9×(AÑ(AØ×&Ñ&Ð(9×(AÑ(Að+
Ð'ñ ÙÔÛð 
ˆ×	Ñ	˜HÓ	%€ð Ø�r—z‘z >°4Ð8IÑ3JÈDÐQS×Q[ÑQ[ÑL\Ð^bÐcqÑ^rÐrñ€
ð
 ØÐ	ÑØØØˆÑØˆÑØˆÐÑ	 Ñ!ØˆˆlÑ	ÑØˆˆnÑ	Ñð ñ	€
ô�|ô ô
$�|ô $ô
9�\ô 9ð
 ÷ð ó ðð �c˜5  c¨4°©:Ð!5Ñ6Ð6Ñ7€òFô�ô ò?òwðE Dó Eò	òð5˜2Ÿ:™:ð 5¨$ó 5ñ$°ð $¸DÀÑ<Ló $ðN LØ�$�zÑ" JÐ.Ñ/ð Làó LðF!vØ�$�zÑ" JÐ.Ñ/ð!vàó!vðHD :ó Dð>˜2Ÿ:™:ó ð NRñ"AØ�:‰:ð"AØ%-¨e°C¸¸sÀC¸x¹Ð4HÑ.IÑ%Jð"Aàó"AðL TXñFØ�:‰:ðFØ*2°5Ð9IÈ3Ð9NÑ3OÑ*PðFàóFñ0D˜"Ÿ*™*ð DÐ3Cð DÈuÐUXÐZ]ÐU]Éó Dð0!Ø�c˜3�h‘ð!àð!ð ð!ð ˆ3�ˆ8�_ó	!ð>°4¸¸UÀ4ÈÀ;Ñ=OÐ8OÑ3Pð ÐUYó ð°$°s¸EÀ$ÈÀ+Ñ<NÐ7NÑ2Oð ÐTXó ð O°(¸4ÀÀUÈ4ÐQVÈ;ÑEWÐ@WÑ;XÑ2Yð OÐ^bó OðN°¸$¸sÀEÈ$ÐPUÈ+ÑDVÐ?VÑ:WÑ1Xð NÐ]aó Nñ)�e˜CÐ!2Ð2Ñ3ð )¸hÀu¹oð )ÐYjó )ñX ¨ó  ðF6&Øð6&àó6&ðv -1ñ(Øð(à Ñ)ó(ðV0Øð0àó0ðf-Øð-àó-ðb  ØØØ)ñ	€ð !%ØØØ,0ñaØ��lÐ"Ñ#ðaà˜‘ðað 
�#‰ðað ð	að
   Ñ)ðað ‡X�XóaðJ TXñ3Ø�$˜˜sÐ$5Ð5Ñ6ð3ØAIÈ%Áð3à
Ð˜dÐ#4Ñ5°t¸DÐARÑ<SÑ7TÐTÑUó3ð, "&Ø&*Ø#'Ø6:Ø59Ø!Ø'+Ø%)Ø*.Ø $Ø%)Ø/3ñ&^Ø˜‘ð&^à˜U‘Oð&^ð ˜4‘.ð&^ð ˜˜u d¨5¡kÐ1Ñ2Ñ3ð	&^ð
 ˜˜e T¨%¡[Ð0Ñ1Ñ2ð&^ð �T‰Nð&^ð   ‘}ð&^ð ˜T‘Nð&^ð ˜˜S #˜X™Ñ'ð&^ð ˜‰~ð&^ð �4˜˜S˜‘>Ñ
"ð&^ð Ð+Ñ,ó&^÷T\
ñ \
ð~
Ø'ðà"'Ð(8¸#Ð(=Ñ">ðð �d‘ðð 
ó	ð2L¨$¨s©)ð LÀdÈ3Áió Lñ �$Ô÷<ð <ó ñ<r.   