Ë
    T^(hFI  ã                   ó„  — d Z ddlmZmZmZmZmZmZ ddlZ	ddl
mZmZ ddlmZmZmZ ddlmZ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  dd	l!m"Z"m#Z#m$Z$  e«       rddl%Z%erd
dl&m'Z'  e«       rddl(Z( e#jR                  e*«      Z+	 ddedeee,ef      fd„Z-	 ddedeee,ef      defd„Z.defd„Z/ G d„ de«      Z0dgZ1y)z%Image processor class for SuperPoint.é    )ÚTYPE_CHECKINGÚDictÚListÚOptionalÚTupleÚUnionNé   )Úis_torch_availableÚis_vision_available)ÚBaseImageProcessorÚBatchFeatureÚget_size_dict)ÚresizeÚto_channel_dimension_format)ÚChannelDimensionÚ
ImageInputÚ	ImageTypeÚPILImageResamplingÚget_image_typeÚinfer_channel_dimension_formatÚis_pil_imageÚis_scaled_imageÚis_valid_imageÚto_numpy_arrayÚvalid_imagesÚvalidate_preprocess_arguments)Ú
TensorTypeÚloggingÚrequires_backendsé   )ÚKeypointMatchingOutputÚimageÚinput_data_formatc                 ó”  — |t         j                  k(  rQ| j                  d   dk(  ryt        j                  | d   | d   k(  «      xr t        j                  | d   | d   k(  «      S |t         j
                  k(  rQ| j                  d   dk(  ryt        j                  | d   | d	   k(  «      xr t        j                  | d	   | d
   k(  «      S y )Nr   r    T©r   .©r    .©é   .éÿÿÿÿ©.r   ©.r    ©.r(   )r   ÚFIRSTÚshapeÚnpÚallÚLAST)r"   r#   s     úv/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/superglue/image_processing_superglue.pyÚis_grayscaler3   5   sÁ   € ð Ô,×2Ñ2Ò2Ø�;‰;�q‰>˜QÒØÜ�v‰v�e˜F‘m u¨V¡}Ñ4Ó5Ò`¼"¿&¹&ÀÀvÁÐRWÐX^ÑR_ÑA_Ó:`Ð`Ø	Ô.×3Ñ3Ò	3Ø�;‰;�r‰?˜aÒØÜ�v‰v�e˜F‘m u¨V¡}Ñ4Ó5Ò`¼"¿&¹&ÀÀvÁÐRWÐX^ÑR_ÑA_Ó:`Ð`ð 
4ó    Úreturnc                 ó  — t        t        dg«       t        | t        j                  «      r£t        | |¬«      r| S |t        j                  k(  r7| d   dz  | d   dz  z   | d   dz  z   }t        j                  |gd	z  d
¬«      }|S |t        j                  k(  r5| d   dz  | d   dz  z   | d   dz  z   }t        j                  |gd	z  d¬«      }S t        | t        j                  j                  «      s| S | j                  d«      } | S )ao  
    Converts an image to grayscale format using the NTSC formula. Only support numpy and PIL Image. TODO support torch
    and tensorflow grayscale conversion

    This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each
    channel, because of an issue that is discussed in :
    https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446

    Args:
        image (Image):
            The image to convert.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image.
    Úvision©r#   r%   gÅ�1w-!Ó?r&   gbX9´Èâ?r'   gÉv¾Ÿ/½?r	   r   )Úaxisr*   r+   r,   r)   ÚL)r   Úconvert_to_grayscaleÚ
isinstancer/   Úndarrayr3   r   r-   Ústackr1   ÚPILÚImageÚconvert)r"   r#   Ú
gray_images      r2   r;   r;   D   s  € ô$ Ô*¨X¨JÔ7ä�%œŸ™Ô$Ü˜Ð1BÕCØˆLØÔ 0× 6Ñ 6Ò6Ø˜v™¨Ñ/°%¸±-À&Ñ2HÑHÈ5ÐQWÉ=Ð[aÑKaÑaˆJÜŸ™ : ,°Ñ"2¸Ô;ˆJð Ðð Ô"2×"7Ñ"7Ò7Ø˜v™¨Ñ/°%¸±-À&Ñ2HÑHÈ5ÐQWÉ=Ð[aÑKaÑaˆJÜŸ™ : ,°Ñ"2¸Ô<ˆJØÐä�eœSŸY™YŸ_™_Ô-Øˆà�M‰M˜#Ó€EØ€Lr4   Úimagesc                 óò   ‡— d}d„ Št        | t        «      rQt        | «      dk(  rt        ˆfd„| D «       «      r| S t        ˆfd„| D «       «      r| D ��cg c]  }|D ]  }|‘Œ Œ c}}S t	        |«      ‚c c}}w )N)z-Input images must be a one of the following :z - A pair of PIL images.z - A pair of 3D arrays.z! - A list of pairs of PIL images.z  - A list of pairs of 3D arrays.c                 ó¢   — t        | «      xsC t        | «      xr6 t        | «      t        j                  k7  xr t        | j                  «      dk(  S )z$images is a PIL Image or a 3D array.r	   )r   r   r   r   r?   Úlenr.   )r"   s    r2   Ú_is_valid_imagez8validate_and_format_image_pairs.<locals>._is_valid_images   sG   € ä˜EÓ"ò 
Ü˜5Ó!Òf¤n°UÓ&;¼y¿}¹}Ñ&LÒfÔQTÐUZ×U`ÑU`ÓQaÐefÑQfð	
r4   r(   c              3   ó.   •K  — | ]  } ‰|«      –— Œ y ­w©N© ©Ú.0r"   rG   s     €r2   ú	<genexpr>z2validate_and_format_image_pairs.<locals>.<genexpr>z   s   øè ø€ Ò#QÀ¡_°U×%;Ñ#Qùó   ƒc              3   óŠ   •K  — | ]:  }t        |t        «      xr$ t        |«      d k(  xr t        ˆfd„|D «       «      –— Œ< y­w)r(   c              3   ó.   •K  — | ]  } ‰|«      –— Œ y ­wrI   rJ   rK   s     €r2   rM   z<validate_and_format_image_pairs.<locals>.<genexpr>.<genexpr>   s   øè ø€ ÒC¨u‘O E×*ÑCùrN   N)r<   ÚlistrF   r0   )rL   Ú
image_pairrG   s     €r2   rM   z2validate_and_format_image_pairs.<locals>.<genexpr>|   sN   øè ø€ ò 
ð ô �z¤4Ó(ò DÜ�J“ 1Ñ$òDäÓC¸
ÔCÓCóDñ
ùs   ƒA A)r<   rQ   rF   r0   Ú
ValueError)rC   Úerror_messagerR   r"   rG   s       @r2   Úvalidate_and_format_image_pairsrU   j   s€   ø€ ð€Mò
ô �&œ$ÔÜˆv‹;˜!Ò¤Ó#QÈ&Ô#QÔ QØˆMÜó 
ð %ô	
ô 
ð -3×K˜jÀ
ÒK°u’EÐK�EÓKÐKÜ
�]Ó
#Ð#ùó Ls   ÁA3c                   ó¸  ‡ — e Zd ZdZdgZddej                  dddfdedee	e
f   ded	ed
ededdfˆ fd„Z	 	 ddej                  dee	e
f   deee	ef      deee	ef      fd„Zdddddddej&                  df	dee   dee	e
f   ded	ee   d
ee   dee   deee	ef      dedeee	ef      defd„Z	 ddddeeee   f   dedeee	ej4                  f      fd„Zˆ xZS )ÚSuperGlueImageProcessoraj  
    Constructs a SuperGlue image processor.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overriden
            by `do_resize` in the `preprocess` method.
        size (`Dict[str, int]` *optional*, defaults to `{"height": 480, "width": 640}`):
            Resolution of the output image after `resize` is applied. Only has an effect if `do_resize` is set to
            `True`. Can be overriden by `size` in the `preprocess` method.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overriden by `resample` in the `preprocess` method.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image by the specified scale `rescale_factor`. Can be overriden by `do_rescale` in
            the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image. Can be overriden by `rescale_factor` in the `preprocess`
            method.
        do_grayscale (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to grayscale. Can be overriden by `do_grayscale` in the `preprocess` method.
    Úpixel_valuesTNgp?Ú	do_resizeÚsizeÚresampleÚ
do_rescaleÚrescale_factorÚdo_grayscaler5   c                 ó¤   •— t        ‰| �  di |¤Ž |�|ndddœ}t        |d¬«      }|| _        || _        || _        || _        || _        || _        y )Nià  i€  )ÚheightÚwidthF©Údefault_to_squarerJ   )	ÚsuperÚ__init__r   rY   rZ   r[   r\   r]   r^   )	ÚselfrY   rZ   r[   r\   r]   r^   ÚkwargsÚ	__class__s	           €r2   re   z SuperGlueImageProcessor.__init__Ÿ   s^   ø€ ô 	‰ÑÑ"˜6Ò"ØÐ'‰t¸ÀcÑ-JˆÜ˜T°UÔ;ˆà"ˆŒØˆŒ	Ø ˆŒØ$ˆŒØ,ˆÔØ(ˆÕr4   r"   Údata_formatr#   c                 óL   — t        |d¬«      }t        |f|d   |d   f||dœ|¤ŽS )aL  
        Resize an image.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Dictionary of the form `{"height": int, "width": int}`, specifying the size of the output image.
            data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the output image. If not provided, it will be inferred from the input
                image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        Frb   r`   ra   )rZ   ri   r#   )r   r   )rf   r"   rZ   ri   r#   rg   s         r2   r   zSuperGlueImageProcessor.resizeµ   sE   € ô: ˜T°UÔ;ˆäØð
à�x‘. $ w¡-Ð0Ø#Ø/ñ	
ð
 ñ
ð 	
r4   Úreturn_tensorsc                 ó(  — |�|n| j                   }|�|n| j                  }|�|n| j                  }|�|n| j                  }|�|n| j                  }|�|n| j
                  }t        |d¬«      }t        |«      }t        |«      st        d«      ‚t        |||||¬«       |D �cg c]  }t        |«      ‘Œ }}t        |d   «      r|rt        j                  d«       |
€t        |d   «      }
g }|D ]]  }|r| j!                  ||||
¬«      }|r| j#                  |||
¬«      }|rt%        ||
¬	«      }t'        ||	|
¬
«      }|j)                  |«       Œ_ t+        dt-        |«      d«      D �cg c]
  }|||dz    ‘Œ }}d|i}t/        ||¬«      S c c}w c c}w )a   
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image pairs to preprocess. Expects either a list of 2 images or a list of list of 2 images list with
                pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set
                `do_rescale=False`.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Size of the output image after `resize` has been applied. If `size["shortest_edge"]` >= 384, the image
                is resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the
                image will be matched to `int(size["shortest_edge"]/ crop_pct)`, after which the image is cropped to
                `(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`.
            resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
                Resampling filter to use if resizing the image. This can be one of `PILImageResampling`, filters. Only
                has an effect if `do_resize` is set to `True`.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image values between [0 - 1].
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to rescale the image by if `do_rescale` is set to `True`.
            do_grayscale (`bool`, *optional*, defaults to `self.do_grayscale`):
                Whether to convert the image to grayscale.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:
                    - Unset: Return a list of `np.ndarray`.
                    - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                    - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                    - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                    - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        Frb   zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)rY   rZ   r[   r\   r]   r   z­It looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.)r"   rZ   r[   r#   )r"   Úscaler#   r8   )Úinput_channel_dimr(   rX   )ÚdataÚtensor_type)rY   r[   r\   r]   r^   rZ   r   rU   r   rS   r   r   r   ÚloggerÚwarning_oncer   r   Úrescaler;   r   ÚappendÚrangerF   r   )rf   rC   rY   rZ   r[   r\   r]   r^   rk   ri   r#   rg   r"   Ú
all_imagesÚiÚimage_pairsro   s                    r2   Ú
preprocessz"SuperGlueImageProcessor.preprocessÜ   sÊ  € ðt "+Ð!6‘I¸D¿N¹Nˆ	Ø'Ð3‘8¸¿¹ˆØ#-Ð#9‘Z¸t¿¹ˆ
Ø+9Ð+E™È4×K^ÑK^ˆØ'3Ð'?‘|ÀT×EVÑEVˆàÐ'‰t¨T¯Y©YˆÜ˜T°UÔ;ˆô 1°Ó8ˆä˜FÔ#Üð:óð ô
 	&ØØØØ!Ø)õ	
ð 6<Ö<¨E”. Õ'Ð<ˆÐ<ä˜6 !™9Ô%©*Ü×Ñðsôð
 Ð$ä >¸vÀa¹yÓ IÐàˆ
Øò 	%ˆEÙØŸ™¨%°dÀXÐar˜Ós�áØŸ™¨5¸ÐZk˜Ól�áÜ,¨UÐFWÔX�ä/°°{ÐVgÔhˆEØ×Ñ˜eÕ$ð	%ô 7<¸A¼sÀ:»ÐPQÓ6RÖS°�z ! a¨!¡eÒ,ÐSˆÐSà Ð,ˆä °>ÔBÐBùò? =ùò6 Ts   Â#F
Å(FÚoutputsr!   Útarget_sizesÚ	thresholdc                 óž  — |j                   j                  d   t        |«      k7  rt        d«      ‚t	        d„ |D «       «      st        d«      ‚t        |t        «      r,t        j                  ||j                   j                  ¬«      }n1|j                  d   dk7  s|j                  d   dk7  rt        d«      ‚|}|j                  j                  «       }||j                  d«      j                  dddd«      z  }|j                  t        j                  «      }g }t!        |j                   ||j"                  d	d	…df   |j$                  d	d	…df   «      D ]t  \  }}}	}
|d   dkD  }|d   dkD  }|d   |   }|d   |   }|	|   }|
|   }t        j&                  ||kD  |dkD  «      }||   }|||      }||   }|j)                  |||d
œ«       Œv |S )aÙ  
        Converts the raw output of [`KeypointMatchingOutput`] into lists of keypoints, scores and descriptors
        with coordinates absolute to the original image sizes.
        Args:
            outputs ([`KeypointMatchingOutput`]):
                Raw outputs of the model.
            target_sizes (`torch.Tensor` or `List[Tuple[Tuple[int, int]]]`, *optional*):
                Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`Tuple[int, int]`) containing the
                target size `(height, width)` of each image in the batch. This must be the original image size (before
                any processing).
            threshold (`float`, *optional*, defaults to 0.0):
                Threshold to filter out the matches with low scores.
        Returns:
            `List[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image
            of the pair, the matching scores and the matching indices.
        r   zRMake sure that you pass in as many target sizes as the batch dimension of the maskc              3   ó8   K  — | ]  }t        |«      d k(  –— Œ y­w)r(   N)rF   )rL   Útarget_sizes     r2   rM   zISuperGlueImageProcessor.post_process_keypoint_matching.<locals>.<genexpr>j  s   è ø€ ÒI¨[”3�{Ó# qÕ(ÑIùs   ‚zTEach element of target_sizes must contain the size (h, w) of each image of the batch)Údevicer    r(   r)   N)Ú
keypoints0Ú
keypoints1Úmatching_scores)Úmaskr.   rF   rS   r0   r<   r   ÚtorchÚtensorr€   Ú	keypointsÚcloneÚflipÚreshapeÚtoÚint32ÚzipÚmatchesrƒ   Úlogical_andrt   )rf   rz   r{   r|   Úimage_pair_sizesr‡   ÚresultsÚ	mask_pairÚkeypoints_pairrŽ   ÚscoresÚmask0Úmask1r�   r‚   Úmatches0Úscores0Úvalid_matchesÚmatched_keypoints0Úmatched_keypoints1rƒ   s                        r2   Úpost_process_keypoint_matchingz6SuperGlueImageProcessor.post_process_keypoint_matchingR  sô  € ð, �<‰<×Ñ˜aÑ ¤C¨Ó$5Ò5ÜÐqÓrÐrÜÑI¸LÔIÔIÜÐsÓtÐtä�l¤DÔ)Ü$Ÿ|™|¨LÀÇÁ×ATÑATÔUÑà×!Ñ! !Ñ$¨Ò)¨\×-?Ñ-?ÀÑ-BÀaÒ-GÜ Øjóð ð  ,Ðà×%Ñ%×+Ñ+Ó-ˆ	ØÐ 0× 5Ñ 5°bÓ 9× AÑ AÀ"ÀaÈÈAÓ NÑNˆ	Ø—L‘L¤§¡Ó-ˆ	àˆÜ:=Ø�L‰L˜) W§_¡_²Q¸°TÑ%:¸G×<SÑ<SÒTUÐWXÐTXÑ<Yó;
ò 	Ñ6ˆI�~ w°ð ˜a‘L 1Ñ$ˆEØ˜a‘L 1Ñ$ˆEØ'¨Ñ*¨5Ñ1ˆJØ'¨Ñ*¨5Ñ1ˆJØ˜u‘~ˆHØ˜U‘mˆGô "×-Ñ-¨g¸	Ñ.AÀ8ÈbÁ=ÓQˆMà!+¨MÑ!:ÐØ!+¨H°]Ñ,CÑ!DÐØ% mÑ4ˆOà�N‰Nà"4Ø"4Ø'6ñõð#	ð2 ˆr4   )NN)g        )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úmodel_input_namesr   ÚBILINEARÚboolr   ÚstrÚintÚfloatre   r/   r=   r   r   r   r   r-   r   r   ry   r   r   r…   ÚTensorrœ   Ú__classcell__)rh   s   @r2   rW   rW   †   s  ø„ ñð, (Ð(Ðð Ø#Ø'9×'BÑ'BØØ 'Ø!ñ)àð)ð �3˜�8‰nð)ð %ð	)ð
 ð)ð ð)ð ð)ð 
õ)ð4 ?CØDHñ%
à�z‰zð%
ð �3˜�8‰nð%
ð ˜e CÐ)9Ð$9Ñ:Ñ;ð	%
ð
 $ E¨#Ð/?Ð*?Ñ$@ÑAó%
ðT %)Ø#Ø'+Ø%)Ø*.Ø'+Ø;?Ø(8×(>Ñ(>ØDHñtCð ˜D‘>ðtCð �3˜�8‰nð	tCð
 %ðtCð ˜T‘NðtCð ! ™ðtCð ˜t‘nðtCð !  s¨J Ñ!7Ñ8ðtCð &ðtCð $ E¨#Ð/?Ð*?Ñ$@ÑAðtCð 
ótCðt ñ	Bà)ðBð ˜J¨¨U©Ð3Ñ4ðBð ð	Bð
 
ˆd�3˜Ÿ™Ð$Ñ%Ñ	&÷Br4   rW   rI   )2r    Útypingr   r   r   r   r   r   Únumpyr/   Ú r
   r   Úimage_processing_utilsr   r   r   Úimage_transformsr   r   Úimage_utilsr   r   r   r   r   r   r   r   r   r   r   r   Úutilsr   r   r   r…   Úmodeling_supergluer!   r?   Ú
get_loggerr�   rq   r¤   r3   r;   rU   rW   Ú__all__rJ   r4   r2   ú<module>r³      só   ðñ ,ç D× Dã ç 7ß UÑ Uß C÷÷ ÷ ó ÷ <Ñ ;ñ ÔÛáÝ:áÔÛà	ˆ×	Ñ	˜HÓ	%€ð AEñaØðaà  cÐ+;Ð&;Ñ <Ñ=óað" AEñ#Øð#à  cÐ+;Ð&;Ñ <Ñ=ð#ð ó#ðL$¨Jó $ô8NÐ0ô Nðb %Ð
%�r4   