o
    i                     @   s   U d dl mZ d dlmZmZmZmZ d dlmZ ddl	m
Z
 ddlmZmZ ddlmZ e r<d d	lmZ dd
l	mZ eedef  Zeed< G dd deZG dd deZdedeee  fddZG dd deZdS )    )Sequence)Any	TypeAlias	TypedDictUnion)overload   )is_pil_image)is_vision_availablerequires_backends   )Pipeline)Image
load_imagezImage.Image	ImagePairc                   @   s   e Zd ZU eed< eed< dS )KeypointxyN)__name__
__module____qualname__float__annotations__ r   r   j/sda-disk/www/egybert/egybert_env/lib/python3.10/site-packages/transformers/pipelines/keypoint_matching.pyr   "   s   
 r   c                   @   s&   e Zd ZU eed< eed< eed< dS )Matchkeypoint_image_0keypoint_image_1scoreN)r   r   r   r   r   r   r   r   r   r   r   '   s   
 r   imagesreturnc                    s`   d}dd  t | tr,t| dkrt fdd| D r| gS t fdd| D r,| S t|)N)z-Input images must be a one of the following :z - A pair of images.z - A list of pairs of images.c                 S   s   t | pt| tS )z"images is a PIL Image or a string.)r	   
isinstancestr)imager   r   r   _is_valid_image4   s   z-validate_image_pairs.<locals>._is_valid_imager   c                 3       | ]} |V  qd S Nr   .0r$   r%   r   r   	<genexpr>9       z'validate_image_pairs.<locals>.<genexpr>c                 3   s<    | ]}t |tot|d kot fdd|D V  qdS )r   c                 3   r&   r'   r   r(   r*   r   r   r+   >   r,   z1validate_image_pairs.<locals>.<genexpr>.<genexpr>N)r"   r   lenall)r)   
image_pairr*   r   r   r+   ;   s    


)r"   r   r-   r.   
ValueError)r    error_messager   r*   r   validate_image_pairs-   s   
"r2   c                       s   e Zd ZdZdZdZdZdZ fddZdddZ	e
dd
edededee fddZe
dd
ee dededeee  fddZ		dd
ee eB dededee eee  B f fddZdddZdd Zddee fddZ  ZS )KeypointMatchingPipelinez
    Keypoint matching pipeline using any `AutoModelForKeypointMatching`. This pipeline matches keypoints between two images.
    FTc                    s    t  j|i | t| d d S )Nvision)super__init__r   )selfargskwargs	__class__r   r   r6   O   s   z!KeypointMatchingPipeline.__init__Nc                 C   s2   i }|d ur
||d< i }|d ur||d< |i |fS )Ntimeout	thresholdr   )r7   r=   r<   preprocess_paramspostprocess_paramsr   r   r   _sanitize_parametersS   s   
z-KeypointMatchingPipeline._sanitize_parameters        inputsr=   r9   r!   c                 K      d S r'   r   r7   rB   r=   r9   r   r   r   __call__\      z!KeypointMatchingPipeline.__call__c                 K   rC   r'   r   rD   r   r   r   rE   _   rF   c                    sH   |du rt dt|}t j|fd|i|}t|dkr"|d S |S )a  
        Find matches between keypoints in two images.

        Args:
            inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
                The pipeline handles three types of images:

                - A string containing a http link pointing to an image
                - A string containing a local path to an image
                - An image loaded in PIL directly

                The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string.
                Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
                images.

            threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out.
                A value of 0 means that all matched keypoints will be returned.

            kwargs:
                `timeout (`float`, *optional*, defaults to None)`
                    The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
                    the call may block forever.

        Return:
            Union[list[Match], list[list[Match]]]:
                A list of matches or a list if a single image pair is provided, or of lists of matches if a batch
                of image pairs is provided. Each match is a dictionary containing the following keys:

                - **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates).
                - **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates).
                - **score** (`float`): The matching score between the two keypoints.
        NzFCannot call the keypoint-matching pipeline without an inputs argument!r=   r   r   )r0   r2   r5   rE   r-   )r7   rB   r=   r9   formatted_inputsoutputsr:   r   r   rE   b   s   'c                    sH    fdd|D }| j |dd}|| j}dd |D }||d}|S )Nc                    s   g | ]}t | d qS )r<   r   r(   rI   r   r   
<listcomp>   s    z7KeypointMatchingPipeline.preprocess.<locals>.<listcomp>pt)r    return_tensorsc                 S   s   g | ]}|j qS r   )sizer(   r   r   r   rJ      s    )model_inputstarget_sizes)image_processortodtype)r7   r    r<   rN   rO   preprocess_outputsr   rI   r   
preprocess   s   
z#KeypointMatchingPipeline.preprocessc                 C   s,   |d }| j di |}||d gd}|S )NrN   rO   )model_outputsrO   r   )model)r7   rS   rN   rU   forward_outputsr   r   r   _forward   s   z!KeypointMatchingPipeline._forwardc           
      C   s   |d }|d }| j j|||d}|d }g }t|d |d |d D ]-\}}}	t|d  |d  d	}t|d  |d  d	}|t|||	 d
 q#t|dd dd}|S )NrU   rO   )rO   r=   r   
keypoints0
keypoints1matching_scoresr   )r   r   )r   r   r   c                 S   s   | d S )Nr   r   )r   r   r   r   <lambda>   s    z6KeypointMatchingPipeline.postprocess.<locals>.<lambda>T)keyreverse)rP   post_process_keypoint_matchingzipr   itemappendr   sorted)
r7   rW   r=   rU   rO   postprocess_outputspair_resultkp_0kp_1r   r   r   r   postprocess   s"   z$KeypointMatchingPipeline.postprocess)NN)rA   r'   )r   r   r   __doc___load_processor_load_image_processor_load_feature_extractor_load_tokenizerr6   r@   r   r   r   r   listr   rE   rT   rX   rh   __classcell__r   r   r:   r   r3   E   s2    
	"*

/r3   N)collections.abcr   typingr   r   r   r   typing_extensionsr   image_utilsr	   utilsr
   r   baser   PILr   r   r#   r   r   r   r   r2   r3   r   r   r   r   <module>   s   