a
    h                     @   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 rpd 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eeee  d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Zkeypoint_image_0Zkeypoint_image_1score)imagesreturnc                    sd   d}dd  t | trXt| dkr>t fdd| D r>| gS t fdd| D rX| S t|d S )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   d/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/pipelines/keypoint_matching.py_is_valid_image+   s    z-validate_image_pairs.<locals>._is_valid_imager   c                 3   s   | ]} |V  qd S Nr   .0r   r    r   r   	<genexpr>0       z'validate_image_pairs.<locals>.<genexpr>c                 3   s:   | ]2}t |to0t|d ko0t fdd|D V  qdS )r   c                 3   s   | ]} |V  qd S r!   r   r"   r$   r   r   r%   5   r&   z1validate_image_pairs.<locals>.<genexpr>.<genexpr>N)r   r   lenall)r#   Z
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eeeee d
ddZe
dee eeeee  d
ddZdeee ef eeeee eee  f d
 fddZdddZdd Zdee d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 )NZvisionptzBKeypoint matching pipeline only supports PyTorch (framework='pt').)super__init__r   	frameworkr)   )selfargskwargs	__class__r   r   r/   F   s    

z!KeypointMatchingPipeline.__init__Nc                 C   s2   i }|d ur||d< i }|d ur(||d< |i |fS )Ntimeout	thresholdr   )r1   r7   r6   Zpreprocess_paramsZpostprocess_paramsr   r   r   _sanitize_parametersL   s    z-KeypointMatchingPipeline._sanitize_parameters        )inputsr7   r3   r   c                 K   s   d S r!   r   r1   r:   r7   r3   r   r   r   __call__U   s    z!KeypointMatchingPipeline.__call__c                 K   s   d S r!   r   r;   r   r   r   r<   X   s    c                    sH   |du rt dt|}t j|fd|i|}t|dkrD|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!r7   r   r   )r)   r+   r.   r<   r'   )r1   r:   r7   r3   Zformatted_inputsoutputsr4   r   r   r<   [   s    'c                    sJ    fdd|D }| j || jd}|| j}dd |D }||d}|S )Nc                    s   g | ]}t | d qS )r6   r   r"   r>   r   r   
<listcomp>   r&   z7KeypointMatchingPipeline.preprocess.<locals>.<listcomp>)r   Zreturn_tensorsc                 S   s   g | ]
}|j qS r   )sizer"   r   r   r   r?      r&   )model_inputstarget_sizes)image_processorr0   toZtorch_dtype)r1   r   r6   rA   rB   preprocess_outputsr   r>   r   
preprocess   s    
z#KeypointMatchingPipeline.preprocessc                 C   s,   |d }| j f i |}||d gd}|S )NrA   rB   )model_outputsrB   )model)r1   rE   rA   rG   forward_outputsr   r   r   _forward   s    z!KeypointMatchingPipeline._forward)r   c           
      C   s   |d }|d }| j j|||d}|d }g }t|d |d |d D ]Z\}}}	t|d  |d  d	}t|d  |d  d	}|t|||	 d
 qFt|dd dd}|S )NrG   rB   )rB   r7   r   Z
keypoints0Z
keypoints1Zmatching_scoresr   r   r   c                 S   s   | d S )Nr   r   )r   r   r   r   <lambda>   r&   z6KeypointMatchingPipeline.postprocess.<locals>.<lambda>T)keyreverse)rC   Zpost_process_keypoint_matchingzipr   itemappendr   sorted)
r1   rI   r7   rG   rB   Zpostprocess_outputsZpair_resultZkp_0Zkp_1r   r   r   r   postprocess   s"    z$KeypointMatchingPipeline.postprocess)NN)r9   )r9   )r9   )N)r9   )__name__
__module____qualname____doc__Z_load_processorZ_load_image_processorZ_load_feature_extractorZ_load_tokenizerr/   r8   r   r   floatr   listr   r<   r   rF   rJ   rR   __classcell__r   r   r4   r   r,   <   s*   
	$ /
r,   N)typingr   r   r   r   Ztyping_extensionsr   r   Zimage_utilsr	   utilsr
   r   baser   ZPILr   r   r   r   __annotations__rW   r   r   r+   r,   r   r   r   r   <module>   s   