U
    9%es+                     @   s`   d Z ddl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 G dd	 d	eZdS )
z(
Image/Text processor class for OWL-ViT
    N)List   )ProcessorMixin)BatchEncoding)is_flax_availableis_tf_availableis_torch_availablec                       s|   e Zd ZdZddgZdZdZd fdd	ZdddZdd Z	dd Z
dd Zdd Zdd Zedd Zedd Z  ZS )OwlViTProcessora  
    Constructs an OWL-ViT processor which wraps [`OwlViTImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`]
    into a single processor that interits both the image processor and tokenizer functionalities. See the
    [`~OwlViTProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more information.

    Args:
        image_processor ([`OwlViTImageProcessor`]):
            The image processor is a required input.
        tokenizer ([`CLIPTokenizer`, `CLIPTokenizerFast`]):
            The tokenizer is a required input.
    image_processor	tokenizerZOwlViTImageProcessor)ZCLIPTokenizerZCLIPTokenizerFastNc                    sd   d }d|kr"t dt |d}|d k	r.|n|}|d krBtd|d krRtdt || d S )Nfeature_extractorzhThe `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor` instead.z)You need to specify an `image_processor`.z"You need to specify a `tokenizer`.)warningswarnFutureWarningpop
ValueErrorsuper__init__)selfr
   r   kwargsr   	__class__ k/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/owlvit/processing_owlvit.pyr   -   s    
zOwlViTProcessor.__init__
max_lengthnpc                 K   s  |dkr |dkr |dkr t d|dk	r0t|tsLt|trht|d tsh| j|f||d|g}nt|trt|d trg }tdd |D }|D ]H}	t|	|kr|	dg|t|	   }	| j|	f||d|}
||
 qntd|d	kr*t	j
d
d |D dd}t	j
dd |D dd}n|dkrzt rzddlm} |j
dd |D dd}|j
dd |D dd}n|dkrt rddl}|jdd |D dd}|jdd |D dd}nT|dkrt rddl}|jdd |D dd}|jdd |D dd}nt dt }
||
d< ||
d< |dk	r`t }
| j|fd|i|j}||
d< |dk	r| j|fd|i|}|dk	r|dk	r|j|
d< |
S |dk	r|dk	r|j|
d< |
S |dk	s|dk	r|
S ttf ||dS dS )a/  
        Main method to prepare for the model one or several text(s) and image(s). This method forwards the `text` and
        `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode:
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
        of the above two methods for more information.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`,
            `List[torch.Tensor]`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
                number of channels, H and W are image height and width.
            query_images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The query image to be prepared, one query image is expected per target image to be queried. Each image
                can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image
                should be of shape (C, H, W), where C is a number of channels, H and W are image height and width.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:
                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.
                - `'jax'`: Return JAX `jnp.ndarray` objects.
        Returns:
            [`BatchEncoding`]: A [`BatchEncoding`] 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`.
        NzXYou have to specify at least one text or query image or image. All three cannot be none.r   )paddingreturn_tensorsc                 S   s   g | ]}t |qS r   )len).0tr   r   r   
<listcomp>q   s     z,OwlViTProcessor.__call__.<locals>.<listcomp> zLInput text should be a string, a list of strings or a nested list of stringsr   c                 S   s   g | ]}|d  qS 	input_idsr   r   encodingr   r   r   r!   ~   s     )Zaxisc                 S   s   g | ]}|d  qS attention_maskr   r%   r   r   r   r!      s     Zjaxc                 S   s   g | ]}|d  qS r#   r   r%   r   r   r   r!      s     c                 S   s   g | ]}|d  qS r'   r   r%   r   r   r   r!      s     ptc                 S   s   g | ]}|d  qS r#   r   r%   r   r   r   r!      s     )dimc                 S   s   g | ]}|d  qS r'   r   r%   r   r   r   r!      s     tfc                 S   s   g | ]}|d  qS r#   r   r%   r   r   r   r!      s     c                 S   s   g | ]}|d  qS r'   r   r%   r   r   r   r!      s     z/Target return tensor type could not be returnedr$   r(   r   query_pixel_valuespixel_values)dataZtensor_type)r   
isinstancestrr   r   maxr   append	TypeErrorr   Zconcatenater   Z	jax.numpynumpyr   torchcatr   Z
tensorflowstackr   r
   r-   dict)r   textZimagesZquery_imagesr   r   r   	encodingsZmax_num_queriesr    r&   r$   r(   Zjnpr5   r+   r,   Zimage_featuresr   r   r   __call__?   sp    %
"




zOwlViTProcessor.__call__c                 O   s   | j j||S )z
        This method forwards all its arguments to [`OwlViTImageProcessor.post_process`]. Please refer to the docstring
        of this method for more information.
        )r
   post_processr   argsr   r   r   r   r<      s    zOwlViTProcessor.post_processc                 O   s   | j j||S )z
        This method forwards all its arguments to [`OwlViTImageProcessor.post_process_object_detection`]. Please refer
        to the docstring of this method for more information.
        )r
   post_process_object_detectionr=   r   r   r   r?      s    z-OwlViTProcessor.post_process_object_detectionc                 O   s   | j j||S )z
        This method forwards all its arguments to [`OwlViTImageProcessor.post_process_one_shot_object_detection`].
        Please refer to the docstring of this method for more information.
        )r
   #post_process_image_guided_detectionr=   r   r   r   r@      s    z3OwlViTProcessor.post_process_image_guided_detectionc                 O   s   | j j||S )z
        This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r   batch_decoder=   r   r   r   rA      s    zOwlViTProcessor.batch_decodec                 O   s   | j j||S )z
        This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r   decoder=   r   r   r   rB      s    zOwlViTProcessor.decodec                 C   s   t dt | jS )Nzg`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.)r   r   r   image_processor_classr   r   r   r   feature_extractor_class   s
    z'OwlViTProcessor.feature_extractor_classc                 C   s   t dt | jS )Nz[`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.)r   r   r   r
   rD   r   r   r   r      s
    z!OwlViTProcessor.feature_extractor)NN)NNNr   r   )__name__
__module____qualname____doc__
attributesrC   Ztokenizer_classr   r;   r<   r?   r@   rA   rB   propertyrE   r   __classcell__r   r   r   r   r	      s   
p
r	   )rI   r   typingr   r4   r   Zprocessing_utilsr   Ztokenization_utils_baser   utilsr   r   r   r	   r   r   r   r   <module>   s   