o
    ei-                     @   s  d 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 ddlmZmZmZ ddlmZ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
ddZdefddZdd Zdd Z dd Z!eG dd deZ"dgZ#dS ) z 
Processor class for PaliGemma.
    N   )BatchFeature)
ImageInputis_valid_image)MultiModalDataProcessingKwargsProcessorMixin
TextKwargsUnpack)
AddedTokenPreTokenizedInput	TextInput)auto_docstringloggingz<image>c                 C      g | ]	}d |ddqS )z<locz0>4> .0ir   r   p/home/ubuntu/transcripts/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                   @   s2   e Zd ZU dZeeB ee B ee B dB ed< dS )PaliGemmaTextKwargsa  
    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".
    Nsuffix)__name__
__module____qualname____doc__r   r   list__annotations__r   r   r   r   r   '   s   
 $r   c                   @   s*   e Zd ZU eed< dddddidZdS )PaliGemmaProcessorKwargstext_kwargsF)paddingreturn_mm_token_type_idsdata_formatchannels_first)r#   images_kwargsN)r   r   r   r   r!   	_defaultsr   r   r   r   r"   1   s   
 
r"   F)totalreturnc                 C   s   t | to	| dS )Nhttp)
isinstancestr
startswith)valr   r   r   is_url?   s   r1   c                 C   s   t | pt| S N)r1   r   elemr   r   r   is_image_or_image_urlD   s   r5   c                 C   s   t | tpt| S r2   )r-   r.   r5   r3   r   r   r   _is_str_or_imageH   s   r6   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_inputL   s   r>   c                
       sz   e Zd Z			d fdd	Ze		ddedB deeB ee B ee B de	e
 defdd	Zdd
dZedd Z  ZS )PaliGemmaProcessorNc                    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
ValueErrorr@   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__)selfimage_processor	tokenizerrD   kwargsr<   tokens_to_add	__class__r   r   rP   d   s   




zPaliGemmaProcessor.__init__imagestextrT   r+   c                    s    j tfd jji|}|d dd}d}|du rtd|du r*td d}t|r2|g}nt	|t
r>t|d	 r>	 |dur|durtd
d |D std t	|t
rut	|t
rut|t|krut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}|rlt|d }d|t|d  d	k< |d!|i |rt|d }t|d }d"|| jk< | |d#< t||d$S )%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`. 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   NTzF`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 r2   )rG   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 )   r8   )r>   rS   r:   r@   rG   r-   r    len)r   r9   
image_listrQ   r   r   r      s    c                 S   s   g | ]}| d qS )r7   r   r\   r   r   r   r      s    c                    s   g | ]}| j j qS r   )rS   	eos_token)r   sfxrc   r   r   r      s    r(   pixel_valuesreturn_tensorsr%   )	text_pairreturn_token_type_idsr_   )
modalities	input_idsitoken_type_idslabelsr`   mm_token_type_ids)datatensor_type) _merge_kwargsr"   rS   init_kwargspoprF   loggerwarning_oncer6   r-   r    anywarningra   r   tuplezipreplacerG   r@   rfindr:   appendrR   _check_special_mm_tokensnparrayupdate
zeros_likerJ   tolistr   )rQ   rX   rY   rT   output_kwargsr   rj   input_stringsexpanded_samplesr]   expanded_samplebos_rfind_index	bos_indexrg   rh   r%   inputsreturn_datarn   	array_idsro   r   rc   r   __call__   s   



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.
        Nr`   )num_image_tokensnum_image_patchesr   )r@   ra   r   r   )rQ   image_sizesrT   vision_datar   r   r   r   r   _get_num_multimodal_tokens   s   z-PaliGemmaProcessor._get_num_multimodal_tokensc                 C   s$   | j jddg }| jj}t|| S )Nrm   rn   )rS   model_input_namesrR   r    )rQ   tokenizer_input_namesimage_processor_input_namesr   r   r   r     s   z$PaliGemmaProcessor.model_input_names)NNN)NNr2   )r   r   r   rP   r   r   r   r   r    r
   r"   r   r   r   propertyr   __classcell__r   r   rV   r   r?   b   s(    
zr?   )$r   numpyr   feature_extraction_utilsr   image_utilsr   r   processing_utilsr   r   r   r	   r
   tokenization_utils_baser   r   r   utilsr   r   
get_loggerr   ru   rG   rangerL   r   r"   boolr1   r5   r6   r>   r?   __all__r   r   r   r   <module>   s(   
$
 
2