o
    
sh                     @   s   U d dl mZmZmZmZ d dlmZmZ ddlm	Z	 ddl
mZmZ ddlmZ e r8d dlmZ dd	lmZ eed
ef  Zeed< edeedZedeeedZdedeee  fddZG dd deZdS )    )AnySequence	TypedDictUnion)	TypeAliasoverload   )is_pil_image)is_vision_availablerequires_backends   )Pipeline)Image
load_imagezImage.Image	ImagePairKeypointxyMatchkeypoint_image_0keypoint_image_1score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)image r    f/var/www/html/alpaca_bot/venv/lib/python3.10/site-packages/transformers/pipelines/keypoint_matching.py_is_valid_image+   s   z-validate_image_pairs.<locals>._is_valid_imager   c                 3       | ]} |V  qd S Nr    .0r   r"   r    r!   	<genexpr>0       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(   5   r)   z1validate_image_pairs.<locals>.<genexpr>.<genexpr>N)r   r   lenall)r&   
image_pairr'   r    r!   r(   2   s    


)r   r   r*   r+   
ValueError)r   error_messager    r'   r!   validate_image_pairs$   s   
"r/   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 ef dededeee eee  f 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                    s2   t  j|i | t| d | jdkrtdd S )NvisionptzBKeypoint matching pipeline only supports PyTorch (framework='pt').)super__init__r   	frameworkr-   )selfargskwargs	__class__r    r!   r4   F   s
   

z!KeypointMatchingPipeline.__init__Nc                 C   s2   i }|d ur
||d< i }|d ur||d< |i |fS )Ntimeout	thresholdr    )r6   r<   r;   preprocess_paramspostprocess_paramsr    r    r!   _sanitize_parametersL   s   
z-KeypointMatchingPipeline._sanitize_parameters        inputsr<   r8   r   c                 K      d S r$   r    r6   rA   r<   r8   r    r    r!   __call__U      z!KeypointMatchingPipeline.__call__c                 K   rB   r$   r    rC   r    r    r!   rD   X   rE   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   )r-   r/   r3   rD   r*   )r6   rA   r<   r8   formatted_inputsoutputsr9   r    r!   rD   [   s   'c                    sJ    fdd|D }| j || jd}|| j}dd |D }||d}|S )Nc                    s   g | ]}t | d qS )r;   r   r%   rH   r    r!   
<listcomp>   s    z7KeypointMatchingPipeline.preprocess.<locals>.<listcomp>)r   return_tensorsc                 S   s   g | ]}|j qS r    )sizer%   r    r    r!   rI      s    )model_inputstarget_sizes)image_processorr5   totorch_dtype)r6   r   r;   rL   rM   preprocess_outputsr    rH   r!   
preprocess   s   
z#KeypointMatchingPipeline.preprocessc                 C   s,   |d }| j di |}||d gd}|S )NrL   rM   )model_outputsrM   r    )model)r6   rQ   rL   rS   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 )NrS   rM   )rM   r<   r   
keypoints0
keypoints1matching_scoresr   r   r   c                 S   s   | d S )Nr   r    )r   r    r    r!   <lambda>   s    z6KeypointMatchingPipeline.postprocess.<locals>.<lambda>T)keyreverse)rN   post_process_keypoint_matchingzipr   itemappendr   sorted)
r6   rU   r<   rS   rM   postprocess_outputspair_resultkp_0kp_1r   r    r    r!   postprocess   s"   z$KeypointMatchingPipeline.postprocess)NN)r@   r$   )__name__
__module____qualname____doc___load_processor_load_image_processor_load_feature_extractor_load_tokenizerr4   r?   r   r   floatr   listr   rD   r   rR   rV   rf   __classcell__r    r    r9   r!   r0   <   s2    
	"*
/r0   N)typingr   r   r   r   typing_extensionsr   r   image_utilsr	   utilsr
   r   baser   PILr   r   r   r   __annotations__ro   r   r   r/   r0   r    r    r    r!   <module>   s   