Ë
    ÜÓ^jäV  ã                   óV  — d Z ddlZddlZddlmZmZ ddlZddlZddl	m
Z ddlmZ ddlmZ ddlmZmZ dd	lmZmZmZ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"  e «       rddl#m$Z$ ddl%m&Z&m'Z' erddl(m)Z)  e!jT                  e+«      Z, G d„ ded¬«      Z-	 	 d/de.e/z  ej`                  z  de1de1de2de2f
d„Z3de2dej`                  dej`                  dej`                  fd„Z4d„ Z5d ej`                  d!e.ej`                  ej`                  f   fd"„Z6d0d#ej`                  d$ej`                  d%e1d!ej`                  fd&„Z7d#ej`                  d'ej`                  d(ej`                  d)ej`                  d!ej`                  f
d*„Z8d+ej`                  d!ej`                  fd,„Z9e G d-„ d.e«      «       Z:d.gZ;y)1z"Image processor class for VitPose.é    N)ÚTYPE_CHECKINGÚUnion)Ú
functionalé   )ÚTorchvisionBackend)ÚBatchFeature)Úgroup_images_by_shapeÚreorder_images)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚSizeDict)ÚImagesKwargsÚUnpack)Ú
TensorTypeÚauto_docstringÚis_scipy_availableÚloggingÚrequires_backends)Úinv)Úaffine_transformÚgaussian_filteré   )ÚVitPoseEstimatorOutputc                   ó2   — e Zd ZU dZedz  ed<   edz  ed<   y)ÚVitPoseImageProcessorKwargsaI  
    do_affine_transform (`bool`, *optional*):
        Whether to apply an affine transformation to the input images based on the bounding boxes.
    normalize_factor (`float`, *optional*, defaults to `200.0`):
        Width and height scale factor used for normalization when computing center and scale from bounding boxes.
    NÚdo_affine_transformÚnormalize_factor)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚboolÚ__annotations__Úfloat© ó    ú/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/vitpose/image_processing_vitpose.pyr   r   7   s   … ñð  ™Ó$Ø˜d‘lÔ"r)   r   F)ÚtotalÚboxÚimage_widthÚimage_heightr    Úpadding_factorc                 ó.  — | dd \  }}}}||z  }	t        j                  ||dz  z   ||dz  z   gt         j                  ¬«      }
||	|z  kD  r	|dz  |	z  }n||	|z  k  r||	z  }t        j                  ||z  ||z  gt         j                  ¬«      }||z  }|
|fS )a¥  
    Encodes a bounding box in COCO format into (center, scale).

    Args:
        box (`Tuple`, `List`, or `np.ndarray`):
            Bounding box in COCO format (top_left_x, top_left_y, width, height).
        image_width (`int`):
            Image width.
        image_height (`int`):
            Image height.
        normalize_factor (`float`):
            Width and height scale factor.
        padding_factor (`float`):
            Bounding box padding factor.

    Returns:
        tuple: A tuple containing center and scale.

        - `np.ndarray` [float32](2,): Center of the bbox (x, y).
        - `np.ndarray` [float32](2,): Scale of the bbox width & height.
    Né   ç      à?©Údtypeç      ð?)ÚnpÚarrayÚfloat32)r,   r-   r.   r    r/   Ú
top_left_xÚ
top_left_yÚwidthÚheightÚaspect_ratioÚcenterÚscales               r*   Úbox_to_center_and_scaler@   D   s¾   € ð: -0°°¨GÑ)€J�
˜E 6Ø Ñ-€LÜ�X‰X�z E¨C¡KÑ/°¸fÀs¹lÑ1JÐKÔSU×S]ÑS]Ô^€Fàˆ|˜fÑ$Ò$Ø˜‘˜|Ñ+‰Ø	� Ñ&Ò	&Ø˜Ñ%ˆä�H‰H�eÐ.Ñ.°Ð9IÑ0IÐJÔRT×R\ÑR\Ô]€EØ�NÑ"€Eà�5ˆ=Ðr)   ÚthetaÚ
size_inputÚsize_dstÚsize_targetc                 ó°  — t        j                  | «      } t        j                  dt         j                  ¬«      }|d   |d   z  }|d   |d   z  }t	        j
                  | «      |z  |d<   t	        j                  | «       |z  |d<   |d|d   z  t	        j
                  | «      z  d|d   z  t	        j                  | «      z  z   d|d   z  z   z  |d	<   t	        j                  | «      |z  |d
<   t	        j
                  | «      |z  |d<   |d|d   z  t	        j                  | «      z  d|d   z  t	        j
                  | «      z  z
  d|d   z  z   z  |d<   |S )aÈ  
    Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the
    Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020).

    Source: https://github.com/open-mmlab/mmpose/blob/master/mmpose/core/post_processing/post_transforms.py

    Args:
        theta (`float`):
            Rotation angle in degrees.
        size_input (`np.ndarray`):
            Size of input image [width, height].
        size_dst (`np.ndarray`):
            Size of output image [width, height].
        size_target (`np.ndarray`):
            Size of ROI in input plane [w, h].

    Returns:
        `np.ndarray`: A matrix for transformation.
    )é   r   r3   r   r   ©r   r   ©r   r   g      à¿r2   ©r   rF   ©r   r   ©r   r   ©r   rF   )r6   Údeg2radÚzerosr8   ÚmathÚcosÚsin)rA   rB   rC   rD   ÚmatrixÚscale_xÚscale_ys          r*   Úget_warp_matrixrU   p   sX  € ô( �J‰J�uÓ€EÜ�X‰X�f¤B§J¡JÔ/€FØ�q‰k˜K¨™NÑ*€GØ�q‰k˜K¨™NÑ*€GÜ—8‘8˜E“? WÑ,€Fˆ4�LÜ—H‘H˜U“OÐ# gÑ-€Fˆ4�LØØˆz˜!‰}ÑœtŸx™x¨›Ñ.°°zÀ!±}Ñ1DÄtÇxÁxÐPUÃÑ1VÑVÐY\Ð_jÐklÑ_mÑYmÑmñ€Fˆ4�Lô —8‘8˜E“? WÑ,€Fˆ4�LÜ—8‘8˜E“? WÑ,€Fˆ4�LØØˆz˜!‰}ÑœtŸx™x¨›Ñ.°°zÀ!±}Ñ1DÄtÇxÁxÐPUÃÑ1VÑVÐY\Ð_jÐklÑ_mÑYmÑmñ€Fˆ4�Lð €Mr)   c           	      ó‚  — t        | j                  d   «      D �cg c]	  }| d|f   ‘Œ }}t        j                  |g d¢g«      }t	        |«      }|d   |d   |d   |d   |d   |d	   f\  |d<   |d<   |d<   |d<   |d	<   |d<   |D �cg c]  }t        |||d
¬«      ‘Œ }}t        j                  |d¬«      }|S c c}w c c}w )a[  
    This function implements cv2.warpAffine function using affine_transform in scipy. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html and https://docs.opencv.org/4.x/d4/d61/tutorial_warp_affine.html for more details.

    Note: the original implementation of cv2.warpAffine uses cv2.INTER_LINEAR.
    éÿÿÿÿ.)r   r   r   rK   rJ   rH   rG   rL   rI   r   )Úoutput_shapeÚorder©Úaxis)ÚrangeÚshaper6   Úvstackr   r   Ústack)	ÚsrcÚMÚsizeÚiÚchannelsÚM_scipyÚM_invÚchannelÚnew_srcs	            r*   Úscipy_warp_affineri   •   sä   € ô &+¨3¯9©9°R©=Ó%9Ö: ��C˜�F“Ð:€HÐ:ô �i‰i˜šI˜Ó'€Gä�‹L€Eàˆd‰Øˆd‰Øˆd‰Øˆd‰Øˆd‰Øˆd‰ðTÑP€Eˆ$�K��t‘˜e D™k¨5°©;¸¸d¹ÀUÈ4Á[ð \dÖdÐPWÔ ¨¸TÈÖKÐd€GÐdÜ�h‰h�w RÔ(€GØ€Nùò# ;ùò es   ›B7ÂB<ÚheatmapsÚreturnc                 ó˜  — t        | t        j                  «      st        d«      ‚| j                  dk7  rt        d«      ‚| j                  \  }}}}| j                  ||df«      }t        j                  |d«      j                  ||df«      }t        j                  |d«      j                  ||df«      }t        j                  |d«      j                  t        j                  «      }|dd…dd…d	f   |z  |dd…dd…d	f<   |dd…dd…df   |z  |dd…dd…df<   t        j                  t        j                  |d«      d
kD  |d«      }||fS )aì  Get keypoint predictions from score maps.

    Args:
        heatmaps (`np.ndarray` of shape `(batch_size, num_keypoints, height, width)`):
            Model predicted heatmaps.

    Returns:
        tuple: A tuple containing aggregated results.

        - coords (`np.ndarray` of shape `(batch_size, num_keypoints, 2)`):
            Predicted keypoint location.
        - scores (`np.ndarray` of shape `(batch_size, num_keypoints, 1)`):
            Scores (confidence) of the keypoints.
    zHeatmaps should be np.ndarrayr1   z Heatmaps should be 4-dimensionalrW   rF   r   )r   r   rF   Nr   g        )Ú
isinstancer6   ÚndarrayÚ	TypeErrorÚndimÚ
ValueErrorr]   ÚreshapeÚargmaxÚamaxÚtileÚastyper8   Úwhere)	rj   Ú
batch_sizeÚnum_keypointsÚ_r;   Úheatmaps_reshapedÚidxÚscoresÚpredss	            r*   Úget_keypoint_predictionsr   ¯   s-  € ô �h¤§
¡
Ô+ÜÐ7Ó8Ð8Ø‡}�}˜ÒÜÐ;Ó<Ð<à*2¯.©.Ñ'€J�˜q %Ø ×(Ñ(¨*°mÀRÐ)HÓIÐÜ
�)‰)Ð% qÓ
)×
1Ñ
1°:¸}ÈaÐ2PÓ
Q€CÜ�W‰WÐ&¨Ó*×2Ñ2°JÀÈqÐ3QÓR€Fä�G‰G�C˜Ó#×*Ñ*¬2¯:©:Ó6€EØš1ša ˜7‘^ eÑ+€EŠ!ŠQ�ˆ'�NØš1ša ˜7‘^ uÑ,€EŠ!ŠQ�ˆ'�Nä�H‰H”R—W‘W˜V YÓ/°#Ñ5°u¸bÓA€EØ�&ˆ=Ðr)   ÚcoordsÚbatch_heatmapsÚkernelc                 óˆ  — |j                   \  }}}}| j                   d   }|dk(  s||k(  st        d«      ‚t        |dz
  dz  «      }t        j                  |D �	�
cg c]!  }	|	D �
cg c]  }
t        |
d||fd¬«      ‘Œ c}
‘Œ# c}
}	«      }t        j                  |dd	«      }t        j                  |«      }t        j                  |d
d¬«      j                  «       }| d   dz   | d   dz   |dz   z  z   }||dz   |dz   z  t        j                  d||z  «      j                  d|«      z  z  }|j                  t        «      j                  dd«      }||   }||dz      }|||z   dz      }|||z   dz      }|||z
  dz
     }||dz
     }||dz
  |z
     }d||z
  z  }d||z
  z  }t        j                  ||gd¬«      }|j                  ||dd«      }|d|z  z
  |z   }|d|z  z
  |z   }d||z
  |z
  |z   |z   |z
  |z
  |z   z  }t        j                  ||||gd¬«      }|j                  ||dd«      }t        j                  j                  |t        j                   t        j"                  «      j$                  t        j&                  d«      z  z   «      }| t        j(                  d||«      j+                  «       z  } | S c c}
w c c}
}	w )a  DARK post-processing. Implemented by unbiased_data_processing.

    Paper references:
    - Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
    - Zhang et al. Distribution-Aware Coordinate Representation for Human Pose Estimation (CVPR 2020).

    Args:
        coords (`np.ndarray` of shape `(num_persons, num_keypoints, 2)`):
            Initial coordinates of human pose.
        batch_heatmaps (`np.ndarray` of shape `(batch_size, num_keypoints, height, width)`):
            Batched heatmaps as predicted by the model.
            A batch_size of 1 is used for the bottom up paradigm where all persons share the same heatmap.
            A batch_size of `num_persons` is used for the top down paradigm where each person has its own heatmaps.
        kernel (`int`, *optional*, defaults to 3):
            Gaussian kernel size (K) for modulation.

    Returns:
        `np.ndarray` of shape `(num_persons, num_keypoints, 2)` ):
            Refined coordinates.
    r   r   zQThe batch size of heatmaps should be 1 or equal to the batch size of coordinates.rF   gš™™™™™é?rH   )ÚsigmaÚradiusÚaxesgü©ñÒMbP?é2   )rG   rG   rK   rK   Úedge)Úmode).r   ).r   rW   r   r2   rZ   zijmn,ijnk->ijmk)r]   rq   Úintr6   r7   r   ÚclipÚlogÚpadÚflattenÚarangerr   rv   ÚconcatenateÚlinalgr   Úfinfor8   ÚepsÚeyeÚeinsumÚsqueeze)r€   r�   r‚   rx   ry   r<   r;   Ú
num_coordsr…   rj   ÚheatmapÚbatch_heatmaps_padÚindexÚi_Úix1Úiy1Úix1y1Úix1_y1_Úix1_Úiy1_ÚdxÚdyÚ
derivativeÚdxxÚdyyÚdxyÚhessians                              r*   Ú"post_dark_unbiased_data_processingr©   Ð   sî  € ð* 0>×/CÑ/CÑ,€J�˜v uØ—‘˜a‘€JØ˜!ŠO˜z¨ZÒ7ÜÐlÓmÐmÜ�&˜1‘* Ñ"Ó#€FÜ—X‘Xð +÷	
àð goÖoÐ[bŒ_˜W¨C¸ÀÐ8HÈvÖVÔoó	
ó€Nô —W‘W˜^¨U°BÓ7€NÜ—V‘V˜NÓ+€NäŸ™ Ð0PÐW]Ô^×fÑfÓhÐØ�6‰N˜QÑ &¨¡.°1Ñ"4¸À¹Ñ!CÑC€EØ	ˆe�a‰i˜F Q™JÑ'¬"¯)©)°A°zÀMÑ7QÓ*R×*ZÑ*ZÐ[]Ð_lÓ*mÑmÑm€EØ�L‰LœÓ×%Ñ% b¨!Ó,€EØ	˜EÑ	"€BØ
˜U Q™YÑ
'€CØ
˜U U™]¨QÑ.Ñ
/€CØ˜u u™}¨qÑ0Ñ1€EØ  ¨¡°Ñ!2Ñ3€GØ˜e a™iÑ(€DØ˜e a™i¨%Ñ/Ñ0€DØ	��d‘
Ñ	€BØ	��d‘
Ñ	€BÜ—‘  R ¨qÔ1€JØ×#Ñ# J°¸qÀ!ÓD€JØ
��B‘‰,˜Ñ
€CØ
��B‘‰,˜Ñ
€CØ
�˜‘˜sÑ" RÑ'¨"Ñ,¨tÑ3°dÑ:¸WÑDÑ
E€CÜ�n‰n˜c 3¨¨SÐ1¸Ô:€GØ�o‰o˜j¨-¸¸AÓ>€GÜ�i‰i�m‰m˜G¤b§h¡h¬r¯z©zÓ&:×&>Ñ&>ÄÇÁÈÃÑ&JÑJÓK€GØ
Œb�i‰iÐ)¨7°JÓ?×GÑGÓIÑI€FØ€Mùò; pùó	
s   Á	J>
Á$J9Á<J>
Ê9J>
r>   r?   Úoutput_sizec                 óÈ  — | j                   d   dvrt        d«      ‚t        |«      dk7  rt        d«      ‚t        |«      dk7  rt        d«      ‚t        |«      dk7  rt        d«      ‚|dz  }|d   |d	   d
z
  z  }|d	   |d   d
z
  z  }t        j                  | «      }| dd…d	f   |z  |d	   z   |d	   dz  z
  |dd…d	f<   | dd…df   |z  |d   z   |d   dz  z
  |dd…df<   |S )ao  Get final keypoint predictions from heatmaps and apply scaling and
    translation to map them back to the image.

    Note:
        num_keypoints: K

    Args:
        coords (`np.ndarray` of shape `(num_keypoints, ndims)`):

            * If ndims=2, corrds are predicted keypoint location.
            * If ndims=4, corrds are composed of (x, y, scores, tags)
            * If ndims=5, corrds are composed of (x, y, scores, tags,
              flipped_tags)

        center (`np.ndarray` of shape `(2,)`):
            Center of the bounding box (x, y).
        scale (`np.ndarray` of shape `(2,)`):
            Scale of the bounding box wrt original image of width and height.
        output_size (`np.ndarray` of shape `(2,)`):
            Size of the destination heatmaps in (height, width) format.

    Returns:
        np.ndarray: Predicted coordinates in the images.
    r   )rF   r1   é   z5Coordinates need to have either 2, 4 or 5 dimensions.rF   z9Center needs to have 2 elements, one for x and one for y.z,Scale needs to consist of a width and heightz2Output size needs to consist of a height and widthç      i@r   r5   Nr2   )r]   rq   Úlenr6   Ú	ones_like)r€   r>   r?   rª   rT   rS   Útarget_coordss          r*   Útransform_predsr±     s  € ð2 ‡|�|�A�˜iÑ'ÜÐPÓQÐQÜ
ˆ6ƒ{�aÒÜÐTÓUÐUÜ
ˆ5ƒz�Q‚ÜÐGÓHÐHÜ
ˆ;Ó˜1ÒÜÐMÓNÐNð �E‰M€Eð �A‰h˜+ a™.¨3Ñ.Ñ/€GØ�A‰h˜+ a™.¨3Ñ.Ñ/€Gä—L‘L Ó(€MØ ¢ A ™,¨Ñ0°6¸!±9Ñ<¸uÀQ¹xÈ#¹~ÑM€M’!�Q�$ÑØ ¢ A ™,¨Ñ0°6¸!±9Ñ<¸uÀQ¹xÈ#¹~ÑM€M’!�Q�$ÑàÐr)   Úbboxesc                 óz   — | dd…df   | dd…df   z   dz
  | dd…df<   | dd…df   | dd…df   z   dz
  | dd…df<   | S )a¥  
    Converts bounding boxes from the COCO format to the Pascal VOC format.

    In other words, converts from (top_left_x, top_left_y, width, height) format
    to (top_left_x, top_left_y, bottom_right_x, bottom_right_y).

    Args:
        bboxes (`np.ndarray` of shape `(batch_size, 4)):
            Bounding boxes in COCO format.

    Returns:
        `np.ndarray` of shape `(batch_size, 4) in Pascal VOC format.
    NrF   r   r   r   r(   )r²   s    r*   Úcoco_to_pascal_vocr´   <  sW   € ð š!˜Q˜$‘< &ª¨A¨¡,Ñ.°Ñ2€FŠ1ˆaˆ4�LØš!˜Q˜$‘< &ª¨A¨¡,Ñ.°Ñ2€FŠ1ˆaˆ4�Là€Mr)   c            '       óú  ‡ — e Zd ZdZeZdgZeZe	Z
dddœZdZdZdZdZdee   fˆ fd	„Zed
edeeee         ej.                  z  dee   defˆ fd„«       Z	 d5d
edeeee         ej.                  z  dz  dededeedf   dz  defd„Zej@                  jB                  ddde"e   de"e   dede#ddfd„«       Z$	 	 	 d6d
ed   dede#dddede#d ed!ed"ed#eee   z  dz  d$eee   z  dz  d%edz  d&e#dz  d'edz  d(ee%z  dz  d)ed*edeej.                  z  dz  def&d+„Z&	 d7d,ej.                  dej.                  dej.                  d-e'fd.„Z(	 	 	 d8d/d0deeee         ej.                  z  d1e'd2edz  d3e%ee"   z  dz  f
d4„Z)ˆ xZ*S )9ÚVitPoseImageProcessorz6Torchvision backend for VitPose with affine transform.Úpixel_valuesé   éÀ   )r<   r;   Tr­   Úkwargsc                 ó$   •— t        ‰| �  di |¤Ž y )Nr(   )ÚsuperÚ__init__)Úselfrº   Ú	__class__s     €r*   r½   zVitPoseImageProcessor.__init___  s   ø€ Ü‰ÑÑ"˜6Ó"r)   ÚimagesÚboxesrk   c                 ó&   •— t        ‰| �  ||fi |¤ŽS )a  
        boxes (`list[list[list[float]]]` or `np.ndarray`):
            List or array of bounding boxes for each image. Each box should be a list of 4 floats representing the
            bounding box coordinates in COCO format (top_left_x, top_left_y, width, height).
        )r¼   Ú
preprocess)r¾   rÀ   rÁ   rº   r¿   s       €r*   rÃ   z VitPoseImageProcessor.preprocessb  s   ø€ ô ‰wÑ! &¨%Ñ:°6Ñ:Ð:r)   NÚdo_convert_rgbÚinput_data_formatÚdeviceztorch.devicec                 ó\   — | j                  ||||¬«      }||d<    | j                  |fi |¤ŽS )z"Handle extra inputs beyond images.)rÀ   rÄ   rÅ   rÆ   rÁ   )Ú_prepare_image_like_inputsÚ_preprocess)r¾   rÀ   rÁ   rÄ   rÅ   rÆ   rº   s          r*   Ú_preprocess_image_like_inputsz3VitPoseImageProcessor._preprocess_image_like_inputsp  sG   € ð ×0Ñ0Ø¨.ÐL]Ðflð 1ó 
ˆð  ˆˆw‰Øˆt×Ñ Ñ1¨&Ñ1Ð1r)   Úimageztorch.Tensorr>   r?   Úrotationrb   c                 óª  — t        ||dz  t        j                  |j                  |j                  f«      dz
  |dz  «      }|j                  ddd«      j                  «       j                  «       }t        |||j                  |j                  f¬«      }t        j                  |«      j                  ddd«      j                  |j                  «      }	|	S )z7Apply an affine transformation to a torch tensor image.g       @r5   r­   r   rF   r   )r`   ra   rb   )rU   r6   r7   r;   r<   ÚpermuteÚcpuÚnumpyri   ÚtorchÚ
from_numpyÚtorÆ   )
r¾   rË   r>   r?   rÌ   rb   ÚtransformationÚimage_npÚtransformed_npÚtransformeds
             r*   r   z&VitPoseImageProcessor.affine_transform�  s¶   € ô )Ø�f˜s‘l¤B§H¡H¨d¯j©j¸$¿+¹+Ð-FÓ$GÈ#Ñ$MÈuÐW\É}ó
ˆð —=‘=  A qÓ)×-Ñ-Ó/×5Ñ5Ó7ˆÜ*¨x¸>ÐQU×Q\ÑQ\Ð^b×^hÑ^hÐPiÔjˆÜ×&Ñ& ~Ó6×>Ñ>¸qÀ!ÀQÓG×JÑJÈ5Ï<É<ÓXˆØÐr)   Ú	do_resizeÚresamplez7PILImageResampling | tvF.InterpolationMode | int | NoneÚdo_center_cropÚ	crop_sizeÚ
do_rescaleÚrescale_factorÚdo_normalizeÚ
image_meanÚ	image_stdÚdo_padÚpad_sizeÚdisable_groupingÚreturn_tensorsr   r    c           	      ó¢  — |�n|rlg }t        ||«      D ]Y  \  }}|D ]O  }t        ||j                  |j                  |¬«      \  }}| j	                  |||d|¬«      }|j                  |«       ŒQ Œ[ |}t        ||¬«      \  }}i }|j                  «       D ]   \  }}| j                  ||||	|
|«      }|||<   Œ" t        ||«      } t        d| i|¬«      S )z!Custom preprocessing for VitPose.)r-   r.   r    r   )rÌ   rb   )rã   r·   )ÚdataÚtensor_type)Úzipr@   r;   r<   r   Úappendr	   ÚitemsÚrescale_and_normalizer
   r   )!r¾   rÀ   rØ   rb   rÙ   rÚ   rÛ   rÜ   rÝ   rÞ   rß   rà   rá   râ   rã   rä   r   r    rÁ   rº   Útransformed_imagesrË   Úimage_boxesr,   r>   r?   Útransformed_imageÚgrouped_imagesÚgrouped_images_indexÚprocessed_images_groupedr]   Ústacked_imagesÚprocessed_imagess!                                    r*   rÉ   z!VitPoseImageProcessor._preprocess“  s  € ð. ÐÑ!4Ø!#ÐÜ&)¨&°%Ó&8ò 	AÑ"��{Ø&ò A�CÜ$;ØØ$(§J¡JØ%)§[¡[Ø)9ô	%‘M�F˜Eð )-×(=Ñ(=¸eÀVÈUÐ]^ÐeiÐ(=Ó(jÐ%Ø&×-Ñ-Ð.?Õ@ñAð	Að (ˆFä/DÀVÐ^nÔ/oÑ,ˆÐ,Ø#%Ð Ø%3×%9Ñ%9Ó%;ò 	=Ñ!ˆE�>Ø!×7Ñ7Ø 
¨N¸LÈ*ÐV_óˆNð /=Ð$ UÒ+ð		=ô
 *Ð*BÐDXÓYÐÜ .Ð2BÐ!CÐQ_Ô`Ð`r)   rj   r‚   c                 ó¾   — |j                   \  }}}}t        |«      \  }	}
t        |	||¬«      }t        |«      D ]  }t	        ||   ||   ||   ||g¬«      ||<   Œ! ||
fS )zRGet final keypoint predictions from heatmaps and transform them back to the image.©r‚   )r>   r?   rª   )r]   r   r©   r\   r±   )r¾   rj   r>   r?   r‚   rx   rz   r<   r;   r€   r}   r~   rc   s                r*   Úkeypoints_from_heatmapsz-VitPoseImageProcessor.keypoints_from_heatmapsÂ  sy   € ð (0§~¡~Ñ$ˆ
�A�v˜uÜ1°(Ó;‰ˆ�Ü2°6¸8ÈFÔSˆÜ�zÓ"ò 	pˆAÜ& u¨Q¡x¸¸q¹	ÈÈqÉÐ`fÐhmÐ_nÔoˆE�!ŠHð	pà�fˆ}Ðr)   Úoutputsr   Úkernel_sizeÚ	thresholdÚtarget_sizesc                 óD  — t        | d«       |j                  j                  \  }}}}|�|t        |«      k7  rt	        d«      ‚t        j                  |dft
        j                  ¬«      }	t        j                  |dft
        j                  ¬«      }
t        t        j                  |Ž «      }t        |«      D ]|  }|�4||   d   ||   d   }}t        j                  ||||g«      }||   |z  ||<   | j                  d   | j                  d	   }}t        ||   ||¬
«      \  }}||	|dd…f<   ||
|dd…f<   Œ~ | j                  |j                  j!                  «       j#                  «       |	|
|¬«      \  }}t        j                  |dft
        j                  ¬«      }|	dd…dd…f   |dd…dd…f<   |
dd…dd…f   |dd…dd…f<   t%        j&                  |«      }t%        j&                  |«      }t%        j(                  d|«      }t%        j&                  t+        |«      «      }g }t-        |||«      }|D ]k  }g }|D ]Q  }t/        |«      \  }}} |j1                  «       }|}!|�||kD  }"||"   }||"   }|!|"   }!|||!| dœ}#|j3                  |#«       ŒS |j3                  |«       Œm |S )aî  
        Transform the heatmaps into keypoint predictions and transform them back to the image.

        Args:
            outputs (`VitPoseEstimatorOutput`):
                VitPoseForPoseEstimation model outputs.
            boxes (`list[list[list[float]]]` or `np.ndarray`):
                List or array of bounding boxes for each image. Each box should be a list of 4 floats representing the bounding
                box coordinates in COCO format (top_left_x, top_left_y, width, height).
            kernel_size (`int`, *optional*, defaults to 11):
                Gaussian kernel size (K) for modulation.
            threshold (`float`, *optional*, defaults to None):
                Score threshold to keep object detection predictions.
            target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
                Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
                `(height, width)` of each image in the batch. If unset, predictions will be resize with the default value.
        Returns:
            `list[list[Dict]]`: A list of dictionaries, each dictionary containing the keypoints and boxes for an image
            in the batch as predicted by the model.
        rÑ   NzTMake sure that you pass in as many target sizes as the batch dimension of the logitsrF   r3   r   r   r;   r<   )r-   r.   rõ   r1   )Ú	keypointsr}   ÚlabelsÚbbox)r   rj   r]   r®   rq   r6   rN   r8   ÚlistÚ	itertoolsÚchainr\   r7   rb   r@   rö   rÏ   rÐ   rÑ   Útensorr�   r´   rè   Únextr–   ré   )$r¾   r÷   rÁ   rø   rù   rú   rx   ry   rz   ÚcentersÚscalesÚflattened_boxesrc   r-   r.   Úscale_factorr;   r<   r>   r?   r~   r}   Ú	all_boxesÚposesrý   Úbboxes_xyxyÚresultsÚpose_bbox_pairsÚimage_bboxesÚimage_resultsÚposeÚscoreÚ	bbox_xyxyÚkeypoints_labelsÚkeepÚpose_results$                                       r*   Úpost_process_pose_estimationz2VitPoseImageProcessor.post_process_pose_estimationÑ  sÃ  € ô8 	˜$ Ô(Ø*1×*:Ñ*:×*@Ñ*@Ñ'ˆ
�M 1 aØÐ#¨
´c¸,Ó6GÒ(GÜÐsÓtÐtÜ—(‘(˜J¨˜?´"·*±*Ô=ˆÜ—‘˜: q˜/´·±Ô<ˆÜœyŸ™°Ð6Ó7ˆÜ�zÓ"ò 	!ˆAØÐ'Ø,8¸©O¸AÑ,>ÀÈQÁÐPQÑ@R˜\�Ü!Ÿx™x¨°lÀKÐQ]Ð(^Ó_�Ø%4°QÑ%7¸,Ñ%F� Ñ"Ø ŸI™I gÑ.°·	±	¸(Ñ0C�6ˆEÜ3°OÀAÑ4FÐTYÐhnÔo‰MˆF�EØ"ˆG�A’q�D‰MØ ˆF�1’a�4ŠLð	!ð ×4Ñ4Ø×Ñ× Ñ Ó"×(Ñ(Ó*¨G°VÀKð 5ó 
‰ˆˆvô —H‘H˜j¨!˜_´B·J±JÔ?ˆ	Ø#¢A q¨ s F™Oˆ	’!�Q�q�S�&ÑØ"¢1 a¨ c 6™Nˆ	’!�Q�q�S�&ÑÜ—‘˜UÓ#ˆÜ—‘˜fÓ%ˆÜ—‘˜a Ó/ˆÜ—l‘lÔ#5°iÓ#@ÓAˆØ79ˆÜ˜e V¨[Ó9ˆØ!ò 	*ˆLØ;=ˆMØ!ò 
2�Ü)-¨oÓ)>Ñ&��e˜YØŸ™›�Ø#)Ð ØÐ(Ø  9Ñ,�DØ ™:�DØ! $™K�EØ'7¸Ñ'=Ð$Ø,0¸EÐM]ÐgpÑq�Ø×$Ñ$ [Õ1ð
2ð �N‰N˜=Õ)ð	*ð ˆr)   )N)Tr­   N)é   )r  NN)+r!   r"   r#   r$   r   Úvalid_kwargsÚmodel_input_namesr   rß   r   rà   rb   rÜ   rÞ   r   r    r   r½   r   r   rÿ   r'   r6   rn   r   rÃ   r%   r   r   ÚstrrÊ   rÑ   ÚcompilerÚdisableÚtupler   r   r   rÉ   rŠ   rö   r  Ú__classcell__)r¿   s   @r*   r¶   r¶   P  sI  ø„ á@à.€LØ'Ð(Ðà&€JØ$€IØ CÑ(€DØ€JØ€LØÐØÐð# Ð(CÑ!Dõ #ð ð;àð;ð �D˜˜e™Ñ%Ñ&¨¯©Ñ3ð;ð Ð4Ñ5ð	;ð
 
ô;ó ð;ð& 59ñ2àð2ð �D˜˜e™Ñ%Ñ&¨¯©Ñ3°dÑ:ð2ð ð	2ð
 ,ð2ð �c˜>Ð)Ñ*¨TÑ1ð2ð 
ó2ð" ‡^�^×Ñðàðð �e‘ðð �U‰|ð	ð
 ðð ðð 
òó ððD %)Ø"'Ø*.ñ'-aà�^Ñ$ð-að ð-að ð	-að
 Lð-að ð-að ð-að ð-að ð-að ð-að ˜D ™KÑ'¨$Ñ.ð-að ˜4 ™;Ñ&¨Ñ-ð-að �t‘ð-að ˜T‘/ð-að  ™+ð-að  ˜jÑ(¨4Ñ/ð!-að" "ð#-að$  ð%-að& �b—j‘jÑ  4Ñ'ð'-að* 
ó+-aðh ñà—*‘*ðð —
‘
ðð �z‰zð	ð
 óð& Ø"&Ø8<ñFà)ðFð �D˜˜e™Ñ%Ñ&¨¯©Ñ3ðFð ð	Fð
 ˜4‘<ðFð ! 4¨¡;Ñ.°Ñ5÷Fr)   r¶   )r­   g      ô?)r   )<r$   r   rO   Útypingr   r   rÐ   r6   rÑ   Útorchvision.transforms.v2r   ÚtvFÚimage_processing_backendsr   Úimage_processing_utilsr   Úimage_transformsr	   r
   Úimage_utilsr   r   r   r   r   r   Úprocessing_utilsr   r   Úutilsr   r   r   r   r   Úscipy.linalgr   Úscipy.ndimager   r   Úmodeling_vitposer   Ú
get_loggerr!   Úloggerr   r  rÿ   rn   rŠ   r'   r@   rU   ri   r   r©   r±   r´   r¶   Ú__all__r(   r)   r*   ú<module>r-     sÕ  ðñ )ã Û ß 'ã Û Ý 7å ;Ý 2ß E÷÷ ÷ 5÷õ ñ ÔÝ ß?áÝ8à	ˆ×	Ñ	˜HÓ	%€ô	# ,°eõ 	#ð" $Ø ñ)Ø	�‰˜Ÿ
™
Ñ	"ð)àð)ð ð)ð ð	)ð
 ó)ðX"˜5ð "¨b¯j©jð "ÀBÇJÁJð "Ð]_×]gÑ]gó "òJð4 r§z¡zð °e¸B¿J¹JÈÏ
É
Ð<RÑ6Só ñB9¨r¯z©zð 9È2Ï:É:ð 9Ð_bð 9Ðkm×kuÑkuó 9ðx-˜BŸJ™Jð -°·
±
ð -À2Ç:Á:ð -Ð\^×\fÑ\fð -Ðkm×kuÑkuó -ð`˜rŸz™zð ¨b¯j©jó ð( ôFÐ.ó Fó ðFðR #Ð
#�r)   