o
    Zh<                     @   s  d Z ddlmZmZmZ ddlmZ ddlmZm	Z	m
Z
 ddlmZmZmZmZmZmZ ddlmZmZmZ ddlmZ eeZd	Zd
d edD dd edD  ZG dd deZG dd deZG dd deddZ de!fddZ"dd Z#dd Z$dd Z%G d d! d!eZ&d!gZ'd"S )#z 
Processor class for PaliGemma.
    )ListOptionalUnion   )BatchFeature)
ImageInputis_valid_imagemake_flat_list_of_images)ImagesKwargsProcessingKwargsProcessorMixin
TextKwargsUnpack!_validate_images_text_input_order)
AddedTokenPreTokenizedInput	TextInput)loggingz<image>c                 C      g | ]	}d |ddqS )z<locz0>4> .0ir   r   a/var/www/auris/lib/python3.10/site-packages/transformers/models/paligemma/processing_paligemma.py
<listcomp>*       r   i   c                 C   r   )z<segz0>3r   r   r   r   r   r   r   *   r      c                   @   s.   e Zd ZU eeeeee ee f  ed< dS )PaliGemmaTextKwargssuffixN)	__name__
__module____qualname__r   r   r   r   r   __annotations__r   r   r   r   r   -   s   
 $r   c                   @   s   e Zd ZU ee ed< dS )PaliGemmaImagesKwargsZdo_convert_rgbN)r    r!   r"   r   boolr#   r   r   r   r   r$   1   s   
 r$   c                   @   s0   e Zd ZU eed< eed< ddiddidZdS )	PaliGemmaProcessorKwargstext_kwargsimages_kwargspaddingFZdata_formatZchannels_first)r'   r(   N)r    r!   r"   r   r#   r$   	_defaultsr   r   r   r   r&   5   s   
 
r&   F)totalreturnc                 C   s   t | to	| dS )Nhttp)
isinstancestr
startswith)valr   r   r   is_urlC   s   r2   c                 C   s   t | pt| S N)r2   r   elemr   r   r   is_image_or_image_urlH   s   r6   c                 C   s   t | tpt| S r3   )r.   r/   r6   r4   r   r   r   _is_str_or_imageL   s   r7   c                 C   s   || |  | |  dS )aZ  
    Builds a string from the input prompt and image tokens.
    For example, for the call:
    build_string_from_input(
        prompt="Prefix str"
        bos_token="<s>",
        image_seq_len=3,
        image_token="<im>",
    )
    The output will be:
    "<im><im><im><s>Initial str"
    Args:
        prompt (`List[Union[str, ImageInput]]`): The input prompt.
        bos_token (`str`): The beginning of sentence token.
        image_seq_len (`int`): The length of the image sequence.
        image_token (`str`): The image token.
        num_images (`int`): Number of images in the prompt.
    
r   prompt	bos_tokenZimage_seq_lenimage_tokenZ
num_imagesr   r   r   build_string_from_inputP   s   r=   c                
       s   e Zd ZdZddgZdgZdZdZ			d fdd		Z				dd
e	de
eeee ee f dee defddZdd Zdd Zedd Z  ZS )PaliGemmaProcessora  
    Constructs a PaliGemma processor which wraps a PaliGemma image processor and a PaliGemma tokenizer into a single processor.

    [`PaliGemmaProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GemmaTokenizerFast`]. See the
    [`~PaliGemmaProcessor.__call__`] and [`~PaliGemmaProcessor.decode`] for more information.

    Args:
        image_processor ([`SiglipImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`GemmaTokenizerFast`], *optional*):
            The tokenizer is a required input.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
    image_processor	tokenizerchat_template)ZSiglipImageProcessorZSiglipImageProcessorFast)ZGemmaTokenizerZGemmaTokenizerFastNc                    s   |d u rt d|d u rt dt|dst d|j| _t|ds=ttddd}d	|gi}|| |t| _t| _n|j| _|j| _|	t
 d|_d|_t j|||d
 d S )Nz)You need to specify an `image_processor`.z"You need to specify a `tokenizer`.image_seq_lengthz;Image processor is missing an `image_seq_length` attribute.r<   FT)
normalizedZspecialZadditional_special_tokens)rA   )
ValueErrorhasattrrB   r   IMAGE_TOKENZadd_special_tokensZconvert_tokens_to_idsZimage_token_idr<   Z
add_tokensEXTRA_TOKENSZadd_bos_tokenZadd_eos_tokensuper__init__)selfr?   r@   rA   kwargsr<   Ztokens_to_add	__class__r   r   rI   {   s&   




zPaliGemmaProcessor.__init__imagestextrK   r,   c                    s  t ||\}} jtfd jji|}|d dd}|dur"dnd}|du r,td|du r7td d	}t	|r?|g}nt
|trKt	|d
 rK	 |dur|durtdd |D std t
|trt
|trt|t|krtdt| dt| dt|r|gg}n1t
|ttfrt|d
 rdd |D }nt
|ttfrt
|d
 ttfrt|d
 d
 std fddt||D }	t|}n=g }
|D ]1}|tt j }|t}|dkr|tt nd
}|d|  jj ||d  }|
| qdd |
D }	|durt	|r|g}|dur' fdd|D } j|fi |d d }|d dd} j|	f||d|d } j|	|dgd i |d|i}|rq|d |d d
kd }|d!|i t||d"S )#ah  
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
        of the above two methods for more information.

        The usage for PaliGemma fine-tuning preparation is slightly different than usual. suffix passed are suffixes to
        the prompt in `text`, and will be placed after the prompt. This is because attention is handled differently for
        the prefix and the suffix. For instance,
        ```python
        image = PIL_cow_image
        prompt = "answer en Where is the cow standing?"
        suffix = "on the beach"
        inputs = processor(text=prompt, images=image, suffix=suffix)
        ```
        Here `inputs` will contain the `input_ids` and `token_type_ids` that follow
        ```python
        inputs["input_ids"][:, 256:]
        # tensor([[     2,   6006,    603,    573,  13910,   9980, 235336,    108,    477,   573,   8318]])
        inputs["token_type_ids"][:, 256:]
        tensor([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
        ```
        Meaning the last three tokens are of "label" ("suffix") type while the other ones are of "prefix" type.


        Args:
            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.
            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).
            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.
            suffix (`str`, `List[str]`, `List[List[str]]`):
                The suffixes or batch of suffixes to be encoded. Only necessary for finetuning. See https://github.com/google-research/big_vision/blob/main/big_vision/configs/proj/paligemma/README.md
                for more information. If your prompt is "<image> What is on the image", the suffix corresponds to the expected prediction "a cow sitting on a bench".

        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`. If `suffix`
              is provided, the `input_ids` will also contain the suffix input ids.
            - **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`.
            - **labels** -- Labels compatible with training if `suffix` is not None
        Ztokenizer_init_kwargsr'   r   NTFzF`images` are expected as arguments to a `PaliGemmaProcessor` instance.z]You are using PaliGemma without a text prefix. It will perform as a picture-captioning model. r   c                 s   s    | ]}t |v V  qd S r3   )rF   r   sampler   r   r   	<genexpr>   s    z.PaliGemmaProcessor.__call__.<locals>.<genexpr>aL  You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens.z	Received z images for zK prompts. Each prompt should be associated with an image or list of images.c                 S   s   g | ]}|gqS r   r   )r   imager   r   r   r     s    z/PaliGemmaProcessor.__call__.<locals>.<listcomp>zAimages must be an image, list of images or list of list of imagesc              
      s:   g | ]\}}t | jj jtt|trt|nd dqS )   r9   )r=   r@   r;   rB   rF   r.   listlen)r   r:   Z
image_listrJ   r   r   r     s    c                 S   s   g | ]}| d qS )r8   r   rQ   r   r   r   r   %  s    c                    s   g | ]}| j j qS r   )r@   Z	eos_token)r   ZsfxrX   r   r   r   *  s    r(   pixel_valuesreturn_tensors)Z	text_pairreturn_token_type_idsrT   )Z
modalitiesZ	input_idsZtoken_type_idsilabels)dataZtensor_type)r   Z_merge_kwargsr&   r@   Zinit_kwargspoprD   loggerZwarning_oncer7   r.   rV   anywarningr   rW   r   tuplezipr	   replacerF   rB   rfindr;   appendr?   Z_check_special_mm_tokensZmasked_fillupdater   )rJ   rN   rO   ZaudioZvideosrK   Zoutput_kwargsr   r\   Zinput_stringsZexpanded_samplesrR   Zexpanded_sampleZbos_rfind_indexZ	bos_indexrZ   r[   ZinputsZreturn_datar]   r   rX   r   __call__   s   B





zPaliGemmaProcessor.__call__c                 O      | j j|i |S )z
        This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r@   batch_decoderJ   argsrK   r   r   r   rk   >     zPaliGemmaProcessor.batch_decodec                 O   rj   )z
        This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r@   decoderl   r   r   r   ro   F  rn   zPaliGemmaProcessor.decodec                 C   s"   | j j}| jj}tt|| S r3   )r@   model_input_namesr?   rV   dictfromkeys)rJ   Ztokenizer_input_namesZimage_processor_input_namesr   r   r   rp   M  s   z$PaliGemmaProcessor.model_input_names)NNN)NNNN)r    r!   r"   __doc__
attributesZvalid_kwargsZimage_processor_classZtokenizer_classrI   r   r   r   r   r   r   r&   r   ri   rk   ro   propertyrp   __classcell__r   r   rL   r   r>   f   s8    "
 $r>   N)(rs   typingr   r   r   Zfeature_extraction_utilsr   Zimage_utilsr   r   r	   Zprocessing_utilsr
   r   r   r   r   r   Ztokenization_utils_baser   r   r   utilsr   Z
get_loggerr    r`   rF   rangerG   r   r$   r&   r%   r2   r6   r7   r=   r>   __all__r   r   r   r   <module>   s(    
$ 
p