
    i(                         d Z ddlmZ ddlZddlmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZmZ dd	lmZmZmZ erd
dlmZmZ  G d de
d      Z G d ded      Ze G d de             ZdgZy)z(
Image/Text processor class for OWL-ViT
    )TYPE_CHECKINGN   )BatchFeature)
ImageInput)ImagesKwargsProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)
TensorTypeauto_docstringis_torch_available   )&OwlViTImageGuidedObjectDetectionOutputOwlViTObjectDetectionOutputc                   "    e Zd ZU dZedz  ed<   y)OwlViTImagesKwargsaa  
    query_images (`ImageInput`, *optional*):
        Query images to use for image-guided object detection. When provided, these images serve as visual queries
        to find similar objects in the main `images`. The query images override any text prompts, and the model
        performs image-to-image matching instead of text-to-image matching.
    Nquery_images)__name__
__module____qualname____doc__r   __annotations__     h/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/models/owlvit/processing_owlvit.pyr   r   &   s     t##r   r   F)totalc                   *    e Zd ZU eed<   ddiddidZy)OwlViTProcessorKwargsimages_kwargspadding
max_lengthreturn_tensorspt)text_kwargscommon_kwargsN)r   r   r   r   r   	_defaultsr   r   r   r    r    1   s'    %% |
 d
	Ir   r    c                        e Zd Zd fd	Ze	 	 ddedz  deez  ee   z  ee   z  de	e
   defd       Zd Z	 	 	 dd	d
dedeee   z  dz  deee      dz  fdZ	 	 	 dd	ddededeee   z  dz  fdZ xZS )OwlViTProcessorNc                 &    t         |   ||       y N)super__init__)selfimage_processor	tokenizerkwargs	__class__s       r   r.   zOwlViTProcessor.__init__?   s    )4r   imagestextr2   returnc                     | j                   t        fd| j                  j                  i|}|d   j	                  dd      }|d   d   }|||t        d      i }|t        |t              s#t        |t              r+t        |d   t              s | j                  |fi |d   g}nt        |t              ryt        |d   t              rfg }t        d	 |D              }	|D ]L  }
t        |
      |	k7  r|
d
g|	t        |
      z
  z  z   }
 | j                  |
fi |d   }|j                  |       N nt        d      |dk(  rQt        j                  |D cg c]  }|d   	 c}d      }t        j                  |D cg c]  }|d   	 c}d      }ng|dk(  rWt               rMddl}|j#                  |D cg c]  }|d   	 c}d      }|j#                  |D cg c]  }|d   	 c}d      }nt        d      ||d<   ||d<   |$ | j$                  |fi |d   j&                  }d|i}|% | j$                  |fi |d   }|j&                  |d<   t)        ||      S c c}w c c}w c c}w c c}w )a  
        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:
            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
                `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
                `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
            - **query_pixel_values** -- Pixel values of the query images to be fed to a model. Returned when `query_images` is not `None`.
        tokenizer_init_kwargsr!   r   Nr&   r$   zXYou have to specify at least one text or query image or image. All three cannot be none.r   c              3   2   K   | ]  }t        |        y wr,   )len).0text_singles     r   	<genexpr>z+OwlViTProcessor.__call__.<locals>.<genexpr>i   s     %O;c+&6%Os    zLInput text should be a string, a list of strings or a nested list of stringsnp	input_ids)axisattention_maskr%   )dimz/Target return tensor type could not be returnedquery_pixel_valuespixel_values)datatensor_type)_merge_kwargsr    r1   init_kwargspop
ValueError
isinstancestrlistmaxr:   append	TypeErrorr?   concatenater   torchcatr0   rE   r   )r/   r4   r5   r2   output_kwargsr   r$   rF   	encodingsmax_num_queriesr<   encodingr@   rB   rS   rD   image_featuress                    r   __call__zOwlViTProcessor.__call__B   s   " +**!
"&.."<"<
 

 %_599.$O&}56FG<L0V^j  $$D$)?
SWXYSZ\`Ha+T^^DQM-4PQR	D$'JtAw,E	 #&%O$%O"O $( /K;'?:&1SE_sS^O_=_4`&`-t~~kZ]==YZH$$X./   noo%NNR[+\hH[,A+\cde	!#\e0fPX:J1K0fmn!o4',>,@!IIY&Wx'<&W]^I_	!&W`+a8H5E,F+agh!i !RSS )D%3D!"#!5!5!5l!emTcFd!e!r!r(*<=D1T11&[M/<Z[N#1#>#>D >BB- ,]0f 'X+as   I! I&8I+I0c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to [`OwlViTImageProcessor.post_process`]. Please refer to the docstring
        of this method for more information.
        )r0   post_process)r/   argsr2   s      r   r\   zOwlViTProcessor.post_process   s"    
 1t##00$A&AAr   outputsr   	thresholdtarget_sizestext_labelsc                    | j                   j                  |||      }|"t        |      t        |      k7  rt        d      |0t	        ||      D ]  \  }}|d   D cg c]  }||   	 }	}|	|d<   ! |S |D ]  }d|d<   	 |S c c}w )a  
        Converts the raw output of [`OwlViTForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
        bottom_right_x, bottom_right_y) format.

        Args:
            outputs ([`OwlViTObjectDetectionOutput`]):
                Raw outputs of the model.
            threshold (`float`, *optional*, defaults to 0.1):
                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 not be resized.
            text_labels (`list[list[str]]`, *optional*):
                List of lists of text labels for each image in the batch. If unset, "text_labels" in output will be
                set to `None`.

        Returns:
            `list[Dict]`: A list of dictionaries, each dictionary containing the following keys:
            - "scores": The confidence scores for each predicted box on the image.
            - "labels": Indexes of the classes predicted by the model on the image.
            - "boxes": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.
            - "text_labels": The text labels for each predicted bounding box on the image.
        )r^   r_   r`   NzAMake sure that you pass in as many lists of text labels as imageslabelsra   )r0   post_process_object_detectionr:   rK   zip)
r/   r^   r_   r`   ra   outputimage_outputimage_text_labelsiobject_text_labelss
             r   &post_process_grounded_object_detectionz6OwlViTProcessor.post_process_grounded_object_detection   s    < %%CCy| D 
 "s;'73v;'F`aa "36v{3K A//DPQYDZ%[q&7&:%["%[.@]+A  !' 3.2]+3  &\s   Br   nms_thresholdc                 @    | j                   j                  ||||      S )a  
        Converts the output of [`OwlViTForObjectDetection.image_guided_detection`] into the format expected by the COCO
        api.

        Args:
            outputs ([`OwlViTImageGuidedObjectDetectionOutput`]):
                Raw outputs of the model.
            threshold (`float`, *optional*, defaults to 0.0):
                Minimum confidence threshold to use to filter out predicted boxes.
            nms_threshold (`float`, *optional*, defaults to 0.3):
                IoU threshold for non-maximum suppression of overlapping boxes.
            target_sizes (`torch.Tensor`, *optional*):
                Tensor of shape (batch_size, 2) where each entry is the (height, width) of the corresponding image in
                the batch. If set, predicted normalized bounding boxes are rescaled to the target sizes. If left to
                None, predictions will not be unnormalized.

        Returns:
            `list[Dict]`: A list of dictionaries, each dictionary containing the following keys:
            - "scores": The confidence scores for each predicted box on the image.
            - "boxes": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.
            - "labels": Set to `None`.
        )r^   r_   rl   r`   )r0   #post_process_image_guided_detection)r/   r^   r_   rl   r`   s        r   rn   z3OwlViTProcessor.post_process_image_guided_detection   s-    : ##GGy\h H 
 	
r   )NN)g?NN)g        g333333?N)r   r   r   r.   r   r   r   r   rN   r
   r    r   rZ   r\   floatr   tuplerM   rk   rn   __classcell__)r3   s   @r   r*   r*   =   s   5  %)Z^ICT!IC ++d9o=EV@WWIC ./	IC
 
IC ICVB 8<.2... . !4;.5	.
 $s)_t+.f "8<
9
 
 	

 !4;.5
r   r*   )r   typingr   numpyr?   image_processing_utilsr   image_utilsr   processing_utilsr   r   r	   r
   tokenization_utils_baser   r   utilsr   r   r   modeling_owlvitr   r   r   r    r*   __all__r   r   r   <module>r{      s|    !  2 %  D C C d$U $	,E 	 f
n f
 f
R 
r   