o
    iD;                     @   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
 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.
    )OptionalUnionN   )BatchFeature)
ImageInputis_valid_image)ImagesKwargsMultiModalDataProcessingKwargsProcessorMixin
TextKwargsUnpack)
AddedTokenPreTokenizedInput	TextInput)loggingz<image>c                 C      g | ]	}d |ddqS )z<locz0>4> .0ir   r   o/home/ubuntu/veenaModal/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#   /   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&   3   s   
 
r&   F)totalreturnc                 C   s   t | to	| dS )Nhttp)
isinstancestr
startswith)valr   r   r   is_urlB   s   r5   c                 C   s   t | pt| S N)r5   r   elemr   r   r   is_image_or_image_urlG   s   r9   c                 C   s   t | tpt| S r6   )r1   r2   r9   r7   r   r   r   _is_str_or_imageK   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_inputO   s   rB   c                
       s   e Zd ZdZddgZdZdZ			d fdd	Z				dd	ee	 d
e
eeee ee f dee defddZd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   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 )	Nimage_seq_lengthz;Image processor is missing an `image_seq_length` attribute.r@   FT)
normalizedspecialadditional_special_tokens)chat_template)hasattr
ValueErrorrJ   r   IMAGE_TOKENadd_special_tokensconvert_tokens_to_idsimage_token_idr@   
add_tokensEXTRA_TOKENSadd_bos_tokenadd_eos_tokensuper__init__)selfrD   rE   rN   kwargsr@   tokens_to_add	__class__r   r   rZ   y   s   




zPaliGemmaProcessor.__init__imagestextr\   r/   c                    s$   j tfd jji|}|d dd}|du}|du r!td|du r,td d}t|r4|g}nt	|t
r@t|d r@	 |dur|durtd	d
 |D std t	|t
rwt	|t
rwt|t|krwt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 }	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}|rnt|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 `kwargs` 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   NzF`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 r6   )rQ   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<   )rB   rE   r>   rJ   rQ   r1   r!   len)r   r=   
image_listr[   r   r   r     s    c                 S   s   g | ]}| d qS )r;   r   rd   r   r   r   r     s    c                    s   g | ]}| j j qS r   )rE   	eos_token)r   sfxrk   r   r   r   !  s    r(   pixel_valuesreturn_tensorsr*   )	text_pairreturn_token_type_idsrg   )
modalities	input_idsitoken_type_idslabelsrh   mm_token_type_ids)datatensor_type) _merge_kwargsr&   rE   init_kwargspoprP   loggerwarning_oncer:   r1   r!   anywarningri   r   tuplezipreplacerQ   rJ   rfindr>   appendrD   _check_special_mm_tokensnparrayupdate
zeros_likerT   tolistr   )r[   r`   ra   audiovideosr\   output_kwargsr   rr   input_stringsexpanded_samplesre   expanded_samplebos_rfind_index	bos_indexro   rp   r*   inputsreturn_datarv   	array_idsrw   r   rk   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 )a  
        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:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        Nrh   )num_image_tokensnum_image_patchesr   )rJ   ri   r   r	   )r[   image_sizesr\   vision_datar   r   r   r   r   _get_num_multimodal_tokens=  s   z-PaliGemmaProcessor._get_num_multimodal_tokens)NNN)NNNNr6   )r   r   r    __doc__
attributesimage_processor_classtokenizer_classrZ   r   r   r   r   r   r!   r   r&   r   r   r   __classcell__r   r   r^   r   rC   e   s0    
 )rC   )(r   typingr   r   numpyr   feature_extraction_utilsr   image_utilsr   r   processing_utilsr   r	   r
   r   r   r   tokenization_utils_baser   r   r   utilsr   
get_loggerr   r}   rQ   rangerV   r   r#   r&   r%   r5   r9   r:   rB   rC   __all__r   r   r   r   <module>   s*    
$ 
l