
    fThzN                        S r SSKJr  SSKJrJrJr  SSKrSSKJr  SSK	J
r
  SSKJr  SSKJr  S	S
KJrJrJr  \R&                  " \5      rS\R,                  S\R,                  S\S\S\S\\R,                  \R,                  4   4S jrS\R,                  S\R,                  S\S\\R,                  \R,                  4   4S jrS\R,                  S\S\R,                  4S jr\ " S S\5      5       r " S S\R8                  5      r " S S\R8                  5      r " S S\R8                  5      r " S S\R8                  5      r \ " S  S!\
5      5       r!\" S"S#9 " S$ S%\!5      5       r"S%S!/r#g)&zPyTorch SuperPoint model.    )	dataclass)OptionalTupleUnionN)nn)PreTrainedModel)BaseModelOutputWithNoAttention)SuperPointConfig   )ModelOutputauto_docstringlogging	keypointsscoresborderheightwidthreturnc                     U SS2S4   U:  U SS2S4   X2-
  :  -  nU SS2S4   U:  U SS2S4   XB-
  :  -  nXV-  nX   X   4$ )zPRemoves keypoints (and their associated scores) that are too close to the borderNr       )r   r   r   r   r   mask_hmask_wmasks           j/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/superpoint/modeling_superpoint.pyremove_keypoints_from_bordersr   &   sf     1o'IadOv,OPF1o'IadOu~,NOF?D?FL((    kc                 `    U[        U 5      :  a  X4$ [        R                  " XSS9u  pX   U4$ )z(Keeps the k keypoints with highest scorer   )dim)lentorchtopk)r   r   r   indicess       r   top_k_keypointsr%   0   s7    C	N  jj2OFv%%r   
nms_radiusc                 H  ^ TS:  a  [        S5      eU4S jn[        R                  " U 5      nX" U 5      :H  n[        S5       HE  nU" UR	                  5       5      S:  n[        R
                  " XcU 5      nXr" U5      :H  nXHU) -  -  nMG     [        R
                  " X@U5      $ )z)Applies non-maximum suppression on scoresr   z'Expected positive values for nms_radiusc                 P   > [         R                  R                  U TS-  S-   STS9$ )N   r   kernel_sizestridepadding)r   
functional
max_pool2d)xr&   s    r   max_poolsimple_nms.<locals>.max_pool=   s,    }}''zA~7IRS]g'hhr   r)   )
ValueErrorr"   
zeros_likerangefloatwhere)	r   r&   r1   zerosmax_mask_	supp_masksupp_scoresnew_max_masks	    `       r   
simple_nmsr>   8   s    A~BCCi V$E&))H1XX^^-.2	kk)F;"h{&;;	z:;	 
 ;;x//r   c                      \ rS rSr% SrSr\\R                     \	S'   Sr
\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Sr\\\R                        \	S	'   S
rg)#SuperPointKeypointDescriptionOutputJ   a[  
Base class for outputs of image point description models. Due to the nature of keypoint detection, the number of
keypoints is not fixed and can vary from image to image, which makes batching non-trivial. In the batch of images,
the maximum number of keypoints is set as the dimension of the keypoints, scores and descriptors tensors. The mask
tensor is used to indicate which values in the keypoints, scores and descriptors tensors are keypoint information
and which are padding.

Args:
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
        Loss computed during training.
    keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
        Relative (x, y) coordinates of predicted keypoints in a given image.
    scores (`torch.FloatTensor` of shape `(batch_size, num_keypoints)`):
        Scores of predicted keypoints.
    descriptors (`torch.FloatTensor` of shape `(batch_size, num_keypoints, descriptor_size)`):
        Descriptors of predicted keypoints.
    mask (`torch.BoolTensor` of shape `(batch_size, num_keypoints)`):
        Mask indicating which values in keypoints, scores and descriptors are keypoint information.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or
    when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
        one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
        (also called feature maps) of the model at the output of each stage.
Nlossr   r   descriptorsr   hidden_statesr   )__name__
__module____qualname____firstlineno____doc__rB   r   r"   FloatTensor__annotations__r   	IntTensorr   rC   r   
BoolTensorrD   r   __static_attributes__r   r   r   r@   r@   J   s    2 )-D(5$$
%,+/Ix(/*.FHU&&'./3K%++,3'+D(5##
$+8<M8E%"3"345<r   r@   c                      ^  \ rS rSr SS\S\S\S\SS4
U 4S jjjrS	\R                  S\R                  4S
 jr
SrU =r$ )SuperPointConvBlockm   configin_channelsout_channelsadd_poolingr   Nc                   > [         TU ]  5         [        R                  " UUSSSS9U l        [        R                  " UUSSSS9U l        [        R                  " SS9U l        U(       a  [        R                  " SSS9U l	        g S U l	        g )Nr   r   r*   Tinplacer)   r+   r,   )
super__init__r   Conv2dconv_aconv_bReLUrelu	MaxPool2dpool)selfrR   rS   rT   rU   	__class__s        r   r[   SuperPointConvBlock.__init__n   s|     	ii
 ii
 GGD)	=HBLLQq9	d	r   rD   c                     U R                  U R                  U5      5      nU R                  U R                  U5      5      nU R                  b  U R                  U5      nU$ N)r`   r]   r^   rb   )rc   rD   s     r   forwardSuperPointConvBlock.forward   sN    		$++m"<=		$++m"<=99  IIm4Mr   )r]   r^   rb   r`   )F)rE   rF   rG   rH   r
   intboolr[   r"   Tensorrh   rN   __classcell__rd   s   @r   rP   rP   m   s_    afS&S58SHKSZ^S	S S*U\\ ell  r   rP   c            	       l   ^  \ rS rSrSrS\SS4U 4S jjr  SS\\   S\\   S\	\
\4   4S	 jjrS
rU =r$ )SuperPointEncoder   z
SuperPoint encoder module. It is made of 4 convolutional layers with ReLU activation and max pooling, reducing the
 dimensionality of the image.
rR   r   Nc           
        > [         TU ]  5         SU l        / nUR                  [	        XR                  UR
                  S   SS95        [        S[        UR
                  5      S-
  5       H:  nUR                  [	        XR
                  US-
     UR
                  U   SS95        M<     UR                  [	        XR
                  S   UR
                  S   SS95        [        R                  " U5      U l
        g )Nr   r   T)rU   F)rZ   r[   	input_dimappendrP   encoder_hidden_sizesr5   r!   r   
ModuleListconv_blocks)rc   rR   ry   ird   s       r   r[   SuperPointEncoder.__init__   s    8S8STU8Vdhi	
 q#f99:Q>?A#77A>@[@[\]@^lp @ 	33B79T9TUW9Xfk	

 ==5r   output_hidden_statesreturn_dictc                     U(       a  SOS nU R                    H  nU" U5      nU(       d  M  XA4-   nM     UnU(       d  [        S Xd4 5       5      $ [        UUS9$ )Nr   c              3   .   #    U  H  oc  M  Uv   M     g 7frg   r   .0vs     r   	<genexpr>,SuperPointEncoder.forward.<locals>.<genexpr>   s     Q$?q$?   	)last_hidden_staterD   )ry   tupler	   )rc   inputr|   r}   all_hidden_states
conv_blockoutputs          r   rh   SuperPointEncoder.forward   sj     #7BD**Ju%E##$5$@! + QV$?QQQ-$+
 	
r   )ry   ru   )FT)rE   rF   rG   rH   rI   r
   r[   r   rk   r   r   r	   rh   rN   rm   rn   s   @r   rp   rp      s_    
6/ 6D 62 05&*	
 'tn
 d^	

 
u44	5
 
r   rp   c                   "  ^  \ rS rSrSrS\SS4U 4S jjrS\R                  S\	\R                  \R                  4   4S jr
S\R                  S\R                  4S	 jrS
\R                  S\	\R                  \R                  4   4S jrSrU =r$ )SuperPointInterestPointDecoder   a  
The SuperPointInterestPointDecoder uses the output of the SuperPointEncoder to compute the keypoint with scores.
The scores are first computed by a convolutional layer, then a softmax is applied to get a probability distribution
over the 65 possible keypoint classes. The keypoints are then extracted from the scores by thresholding and
non-maximum suppression. Post-processing is then applied to remove keypoints too close to the image borders as well
as to keep only the k keypoints with highest score.
rR   r   Nc                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        UR
                  U l        [        R                  " SS9U l        [        R                  " SSS9U l
        [        R                  " UR                  S   UR                  SSSS9U l        [        R                  " UR                  UR                  SSS	S9U l        g 
NTrW   r)   rY   rt   r   r   r*   r   )rZ   r[   keypoint_thresholdmax_keypointsr&   border_removal_distancer   r_   r`   ra   rb   r\   rw   decoder_hidden_sizeconv_score_akeypoint_decoder_dimconv_score_brc   rR   rd   s     r   r[   'SuperPointInterestPointDecoder.__init__   s    "(";";#11 ++'-'E'E$GGD)	LLQq9	II''+&&
 II&&(C(CQR[\fg
r   encodedc                 P    U R                  U5      nU R                  U5      u  p2X24$ rg   )_get_pixel_scores_extract_keypoints)rc   r   r   r   s       r   rh   &SuperPointInterestPointDecoder.forward   s.    ''0 33F;	  r   c                    U R                  U R                  U5      5      nU R                  U5      n[        R                  R                  US5      SS2SS24   nUR                  u  p4pVUR                  SSSS5      R                  X5USS5      nUR                  SSSSS5      R                  X5S-  US-  5      n[        X R                  5      nU$ )	zKBased on the encoder output, compute the scores for each pixel of the imager   Nrt   r   r)   r         )r`   r   r   r   r.   softmaxshapepermutereshaper>   r&   )rc   r   r   
batch_sizer:   r   r   s          r   r   0SuperPointInterestPointDecoder._get_pixel_scores   s    4,,W56""6*&&vq1!SbS&9'-||$
v1a+33JqRST1aA.66zA:uWXyYFOO4r   r   c                    UR                   u  p#n[        R                  " US   U R                  :  5      nUS   [	        UR                  5       5         n[        XQU R                  US-  US-  5      u  pQU R                  S:  a  [        XQU R                  5      u  pQ[        R                  " US/5      R                  5       nXQ4$ )z
Based on their scores, extract the pixels that represent the keypoints that will be used for descriptors computation.
The keypoints are in the form of relative (x, y) coordinates.
r   r   r   )r   r"   nonzeror   r   tr   r   r   r%   flipr6   )rc   r   r:   r   r   r   s         r   r   1SuperPointInterestPointDecoder._extract_keypoints   s    
 "<<5 MM&)d.E.E"EF	5/0 :t;;VaZQR
	
 " /	4CUCU VI JJy1#.446	  r   )r   r   r   r   r   r&   rb   r`   )rE   rF   rG   rH   rI   r
   r[   r"   rl   r   rh   r   r   rN   rm   rn   s   @r   r   r      s    
/ 
D 
(!u|| !ellELL6P0Q !	 	%,, 	! !%ell@Z:[ ! !r   r   c                      ^  \ rS rSrSrS\SS4U 4S jjrS\R                  S\R                  S\R                  4S	 jr	\
SS
\S\R                  4S jj5       rSrU =r$ )SuperPointDescriptorDecoderi  aS  
The SuperPointDescriptorDecoder uses the outputs of both the SuperPointEncoder and the
SuperPointInterestPointDecoder to compute the descriptors at the keypoints locations.

The descriptors are first computed by a convolutional layer, then normalized to have a norm of 1. The descriptors
are then interpolated at the keypoints locations.
rR   r   Nc                 R  > [         TU ]  5         [        R                  " SS9U l        [        R
                  " SSS9U l        [        R                  " UR                  S   UR                  SSSS9U l
        [        R                  " UR                  UR                  SSS	S9U l        g r   )rZ   r[   r   r_   r`   ra   rb   r\   rw   r   conv_descriptor_adescriptor_decoder_dimconv_descriptor_br   s     r   r[   $SuperPointDescriptorDecoder.__init__  s    GGD)	LLQq9	!#''+&&"
 "$&&))"
r   r   r   c                    U R                  U R                  U R                  U5      5      5      n[        R                  R                  USSS9nU R                  US   US   S   S5      S   n[        R                  " USS5      nU$ )zXBased on the encoder output and the keypoints, compute the descriptors for each keypointr)   r   pr    Nr   r   )	r   r`   r   r   r.   	normalize_sample_descriptorsr"   	transpose)rc   r   r   rC   s       r   rh   #SuperPointDescriptorDecoder.forward"  s    ,,TYYt7M7Mg7V-WXmm--kQA-F..yAt@TVWXYZ[ ook1a8r   scalec                    UR                   u  p4pVXS-  -
  S-   n [        R                  " Xb-  US-  -
  S-
  XR-  US-  -
  S-
  //5      nUR                  U 5      nX-  n U S-  S-
  n SS0nU R	                  USSS5      n [
        R                  R                  " X4SS0UD6nUR                  X4S5      n[
        R                  R                  USSS	9nU$ )
z-Interpolate descriptors at keypoint locationsr)   g      ?r   align_cornersTrt   modebilinearr   )
r   r"   tensortoviewr   r.   grid_sampler   r   )	r   rC   r   r   num_channelsr   r   divisorkwargss	            r   r   /SuperPointDescriptorDecoder._sample_descriptors.  s     3>2C2C/
&	)C/	,,%-%!)";c"AV^V[^_V_E_beEe ghi**Y'	MA%	!4(NN:q"a8	mm//bZb[ab!))*BGmm--kQA-Fr   )r   r   rb   r`   )r   )rE   rF   rG   rH   rI   r
   r[   r"   rl   rh   staticmethodrj   r   rN   rm   rn   s   @r   r   r     sh    
/ 
D 
(
u|| 
 
 
 3 u||  r   r   c                       \ rS rSr\rSrSrSrS\	\
R                  \
R                  \
R                  4   SS4S jrS\R                   S\R                   4S	 jrS
rg)SuperPointPreTrainedModeliA  
superpointpixel_valuesFmoduler   Nc                 
   [        U[        R                  [        R                  45      (       ak  UR                  R
                  R                  SU R                  R                  S9  UR                  b%  UR                  R
                  R                  5         gg[        U[        R                  5      (       aJ  UR                  R
                  R                  5         UR                  R
                  R                  S5        gg)zInitialize the weightsg        )meanstdNg      ?)
isinstancer   Linearr\   weightdatanormal_rR   initializer_rangebiaszero_	LayerNormfill_)rc   r   s     r   _init_weights'SuperPointPreTrainedModel._init_weightsH  s    fryy"))455 MM&&CT[[5R5R&S{{&  &&( '--KK""$MM$$S) .r   c                 :    USS2SSS2SS24   SS2SSS2SS24   $ )a  
Assuming pixel_values has shape (batch_size, 3, height, width), and that all channels values are the same,
extract the first channel value to get a tensor of shape (batch_size, 1, height, width) for SuperPoint. This is
a workaround for the issue discussed in :
https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446

Args:
    pixel_values: torch.FloatTensor of shape (batch_size, 3, height, width)

Returns:
    pixel_values: torch.FloatTensor of shape (batch_size, 1, height, width)

Nr   r   )rc   r   s     r    extract_one_channel_pixel_values:SuperPointPreTrainedModel.extract_one_channel_pixel_valuesT  s$     Aq!QJ'4A66r   r   )rE   rF   rG   rH   r
   config_classbase_model_prefixmain_input_namesupports_gradient_checkpointingr   r   r   r\   r   r   r"   rJ   r   rN   r   r   r   r   r   A  sd    #L$$O&+#
*E"))RYY*L$M 
*RV 
*7U=N=N 7SXSdSd 7r   r   z@
    SuperPoint model outputting keypoints and descriptors.
    )custom_introc                      ^  \ rS rSrSrS\SS4U 4S jjr\   SS\R                  S\
\R                     S	\
\   S
\
\   S\\\4   4
S jj5       rSrU =r$ )SuperPointForKeypointDetectionie  a  
SuperPoint model. It consists of a SuperPointEncoder, a SuperPointInterestPointDecoder and a
SuperPointDescriptorDecoder. SuperPoint was proposed in `SuperPoint: Self-Supervised Interest Point Detection and
Description <https://arxiv.org/abs/1712.07629>`__ by Daniel DeTone, Tomasz Malisiewicz, and Andrew Rabinovich. It
is a fully convolutional neural network that extracts keypoints and descriptors from an image. It is trained in a
self-supervised manner, using a combination of a photometric loss and a loss based on the homographic adaptation of
keypoints. It is made of a convolutional encoder and two decoders: one for keypoints and one for descriptors.
rR   r   Nc                    > [         TU ]  U5        Xl        [        U5      U l        [        U5      U l        [        U5      U l        U R                  5         g rg   )
rZ   r[   rR   rp   encoderr   keypoint_decoderr   descriptor_decoder	post_initr   s     r   r[   'SuperPointForKeypointDetection.__init__t  sE     (0 >v F"=f"Er   r   labelsr|   r}   c           	      P   SnUb  [        S5      eUb  UOU R                  R                  nUb  UOU R                  R                  nU R	                  U5      nUR
                  u  pgpU R                  UUUS9n
U
S   nU Vs/ s H  oR                  US   5      PM     nnU Vs/ s H  oS   PM	     nnU Vs/ s H  oS   PM	     nn[        WU5       VVs/ s H  u  nnU R                  US   US   5      PM      nnn[        S U 5       5      n[        R                  " UUS4UR                  S	9n[        R                  " UU4UR                  S	9n[        R                  " UUU R                  R                  4UR                  S	9n[        R                  " UU4UR                  [        R                  S
9n[!        [        XU5      5       Hb  u  nu  nnnUUUSUR
                  S   24'   UUUSUR
                  S   24'   UUUSUR
                  S   24'   SUUSUR
                  S   24'   Md     U[        R"                  " X/UR                  S	9-  nU(       a  U
S   OSnU(       d  [%        S UUUUUU4 5       5      $ ['        UUUUUUS9$ s  snf s  snf s  snf s  snnf )a.  
Examples:

```python
>>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
>>> import torch
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
>>> model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")

>>> inputs = processor(image, return_tensors="pt")
>>> outputs = model(**inputs)
```Nz-SuperPoint does not support training for now.)r|   r}   r   )N.r   c              3   >   #    U  H  oR                   S    v   M     g7f)r   N)r   )r   r   s     r   r   9SuperPointForKeypointDetection.forward.<locals>.<genexpr>  s     #W9OOA$6s   r)   )device)r   dtypec              3   .   #    U  H  oc  M  Uv   M     g 7frg   r   r   s     r   r   r     s     q$_q$_r   )rB   r   r   rC   r   rD   )r3   rR   r|   use_return_dictr   r   r   r   zipr   maxr"   r8   r   r   rj   	enumerater   r   r@   )rc   r   r   r|   r}   rB   r   r:   r   r   encoder_outputsr   list_keypoints_scoreskeypoints_scoreslist_keypointslist_scoresr   list_descriptorsmaximum_num_keypointsr   rC   r   rz   
_keypoints_scores_descriptorsrD   s                              r   rh   &SuperPointForKeypointDetection.forward  s   4 LMM %9$D $++JjJj 	 &1%<k$++B]B]<<\J'3'9'9$
v,,!5# ' 
 ,A. Zk!
YjDU!!"3I">?Yj 	 !
 G\\F[2B1-F[\CXYCX/?*CXY 144E~0V
0V,!9 ##$5i$@)IBVW0V 	 

 !$#W#W WKK-BA F|ObObc	j*?@I\I\]kk.0R0RS&&
 {{J(=>|GZGZbgbkbkl6?Naq@r6s2A2
G\2<Ia.:++A.../,3F1(a((()6BK2\//2223*+D&gmmA&&&'	 7t e_YEUEU VV	.B*qT9fk4Q^$_qqq2#'
 	
G!
 ]Y
s   J$J8J%J")rR   r   r   r   )NNN)rE   rF   rG   rH   rI   r
   r[   r   r"   rJ   r   
LongTensorrk   r   r   r@   rh   rN   rm   rn   s   @r   r   r   e  s    	/ 	D 	  .2/3&*X
''X
 ))*X
 'tn	X

 d^X
 
u99	:X
 X
r   r   )$rI   dataclassesr   typingr   r   r   r"   r   transformersr   transformers.modeling_outputsr	   7transformers.models.superpoint.configuration_superpointr
   utilsr   r   r   
get_loggerrE   loggerrl   rj   r   r%   r>   r@   ModulerP   rp   r   r   r   r   __all__r   r   r   <module>r     s     ! ) )   ( U  
		H	%)||)%*\\);>)HK)TW)
5<<%&)&u|| &U\\ &c &eTYT`T`bgbnbnTnNo &0u|| 0 0 0$ =+ = =D")) </
		 /
dE!RYY E!P9")) 9x  7  7  7F 
n
%> n

n
b ,-H
Ir   