o
    wiXB                     @   s&  d Z ddlmZmZ ddl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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.
    )OptionalUnionN   )BatchFeature)
ImageInputis_valid_imagemake_flat_list_of_images)ImagesKwargsMultiModalData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   o/home/ubuntu/sommelier/.venv/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   list__annotations__r   r   r   r   r   ,   s   
 $r   c                   @   s   e Zd ZU ee ed< dS )PaliGemmaImagesKwargsdo_convert_rgbN)r    r!   r"   r   boolr$   r   r   r   r   r%   0   s   
 r%   c                   @   s2   e Zd ZU eed< eed< dddddidZdS )	PaliGemmaProcessorKwargstext_kwargsimages_kwargsF)paddingreturn_mm_token_type_idsdata_formatchannels_first)r)   r*   N)r    r!   r"   r   r$   r%   	_defaultsr   r   r   r   r(   4   s   
 
r(   F)totalreturnc                 C   s   t | to	| dS )Nhttp)
isinstancestr
startswith)valr   r   r   is_urlC   s   r7   c                 C   s   t | pt| S N)r7   r   elemr   r   r   is_image_or_image_urlH   s   r;   c                 C   s   t | tpt| S r8   )r3   r4   r;   r9   r   r   r   _is_str_or_imageL   s   r<   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_tokenimage_seq_lenimage_token
num_imagesr   r   r   build_string_from_inputP   s   rD   c                
       s   e Zd ZdZd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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)SiglipImageProcessorSiglipImageProcessorFast)GemmaTokenizer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.rB   FT)
normalizedspecialadditional_special_tokens)chat_template)
ValueErrorhasattrrL   r   IMAGE_TOKENadd_special_tokensconvert_tokens_to_idsimage_token_idrB   
add_tokensEXTRA_TOKENSadd_bos_tokenadd_eos_tokensuper__init__)selfrF   rG   rP   kwargsrB   tokens_to_add	__class__r   r   r\   z   s&   




zPaliGemmaProcessor.__init__imagestextr^   r1   c                    sF  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}|d dd} j|	f||d|d } j|	|dgd i |d|i}|rt|d }d |t|d! d
k< |d"|i |rt|d }t|d }d#|| jk< |  |d$< 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
        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 r8   )rS   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 )   r>   )rD   rG   r@   rL   rS   r3   r#   len)r   r?   
image_listr]   r   r   r     s    c                 S   s   g | ]}| d qS )r=   r   rf   r   r   r   r   $  s    c                    s   g | ]}| j j qS r   )rG   	eos_token)r   sfxrm   r   r   r   )  s    r*   pixel_valuesreturn_tensorsr,   )	text_pairreturn_token_type_idsri   )
modalities	input_idsitoken_type_idslabelsrj   mm_token_type_ids)datatensor_type)"r   _merge_kwargsr(   rG   init_kwargspoprQ   loggerwarning_oncer<   r3   r#   anywarningrk   r   tuplezipr   replacerS   rL   rfindr@   appendrF   _check_special_mm_tokensnparrayupdate
zeros_likerV   tolistr   )r]   rb   rc   audiovideosr^   output_kwargsr   rt   input_stringsexpanded_samplesrg   expanded_samplebos_rfind_index	bos_indexrq   rr   r,   inputsreturn_datarx   	array_idsry   r   rm   r   __call__   s   B





zPaliGemmaProcessor.__call__c                 K   sH   i }|dur| j gt| }dgt| }|||d tdi |S )aB  
        Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

        Args:
            image_sizes (list[list[str]], *optional*):
                The input sizes formatted as (height, width) per each image.
        Returns:
            dict[str, list[int]]: A dictionary mapping each modality ("image", "video", "audio")
            to a list containing the number of placeholder tokens required. If the model doesn't accept
            a certain modality or no input sizes are provided, the dict value is set to an empty list.
        Nrj   )num_image_tokensnum_image_patchesr   )rL   rk   r   r
   )r]   image_sizesr^   vision_datar   r   r   r   r   _get_num_multimodal_tokensE  s   z-PaliGemmaProcessor._get_num_multimodal_tokensc                 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.
        )rG   batch_decoder]   argsr^   r   r   r   r   Y     zPaliGemmaProcessor.batch_decodec                 O   r   )z
        This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )rG   decoder   r   r   r   r   a  r   zPaliGemmaProcessor.decodec                 C   s"   | j j}| jj}tt|| S r8   )rG   model_input_namesrF   r#   dictfromkeys)r]   tokenizer_input_namesimage_processor_input_namesr   r   r   r   h  s   z$PaliGemmaProcessor.model_input_names)NNN)NNNNr8   )r    r!   r"   __doc__
attributesimage_processor_classtokenizer_classr\   r   r   r   r   r#   r   r(   r   r   r   r   r   propertyr   __classcell__r   r   r`   r   rE   f   s8    "
 
,rE   )*r   typingr   r   numpyr   feature_extraction_utilsr   image_utilsr   r   r   processing_utilsr	   r
   r   r   r   r   r   tokenization_utils_baser   r   r   utilsr   
get_loggerr    r   rS   rangerX   r   r%   r(   r'   r7   r;   r<   rD   rE   __all__r   r   r   r   <module>   s,   $	
$  
