
    fTh<                        S r SSKJrJrJr  SSKJr  SSKJrJ	r	J
r
  SSKJrJrJrJrJrJr  SSKJrJrJr  SSKJr  \R0                  " \5      rS	r\" S
5       V s/ s H
  n SU S S3PM     sn \" S5       V s/ s H
  n SU S S3PM     sn -   r " S S\5      r " S S\5      r " S S\SS9r S\!4S jr"S r#S r$S r% " S S\5      r&S/r'g s  sn f s  sn f )!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>i   z<locz0>4>   z<segz0>3c                   @    \ rS rSr% \\\\\\   \\   4      \	S'   Sr
g)PaliGemmaTextKwargs-   suffix N)__name__
__module____qualname____firstlineno__r   r   r   r   r   __annotations____static_attributes__r       j/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/paligemma/processing_paligemma.pyr   r   -   s&    U9&7i$O`Jaabccr"   r   c                   &    \ rS rSr% \\   \S'   Srg)PaliGemmaImagesKwargs1   do_convert_rgbr   N)r   r   r   r   r   boolr    r!   r   r"   r#   r%   r%   1   s    TN"r"   r%   c                   <    \ rS rSr% \\S'   \\S'   SS0SS0S.rS	rg
)PaliGemmaProcessorKwargs5   text_kwargsimages_kwargspaddingFdata_formatchannels_first)r,   r-   r   N)	r   r   r   r   r   r    r%   	_defaultsr!   r   r"   r#   r*   r*   5   s.    $$(( u
 +
	Ir"   r*   F)totalreturnc                 R    [        U [        5      =(       a    U R                  S5      $ )Nhttp)
isinstancestr
startswith)vals    r#   is_urlr:   C   s    c3:CNN6$::r"   c                 <    [        U 5      =(       d    [        U 5      $ N)r:   r	   elems    r#   is_image_or_image_urlr?   H   s    $</>$//r"   c                 F    [        U [        5      =(       d    [        U 5      $ r<   )r6   r7   r?   r=   s    r#   _is_str_or_imagerA   L   s    dS"A&;D&AAr"   c                     X2-  U-   U U  S3$ )a  
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_imagess        r#   build_string_from_inputrJ   P   s"    & )J67	{6("MMr"   c            
          ^  \ rS rSrSrSS/rS/rSrSr   SU 4S jjr	    SS	\
S
\\\\\   \\   4   S\\   S\4S jjrS rS r\S 5       rSrU =r$ )PaliGemmaProcessorf   a  
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)SiglipImageProcessorSiglipImageProcessorFast)GemmaTokenizerGemmaTokenizerFastc                   > Uc  [        S5      eUc  [        S5      e[        US5      (       d  [        S5      eUR                  U l        [        US5      (       dK  [        [        SSS9nS	U/0nUR                  U5        UR                  [        5      U l        [        U l        O"UR                  U l        UR                  U l        UR                  [        5        SUl        SUl        [        TU ]9  XUS
9  g )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.rH   FT)
normalizedspecialadditional_special_tokens)rP   )
ValueErrorhasattrrV   r   IMAGE_TOKENadd_special_tokensconvert_tokens_to_idsimage_token_idrH   
add_tokensEXTRA_TOKENSadd_bos_tokenadd_eos_tokensuper__init__)selfrN   rO   rP   kwargsrH   tokens_to_add	__class__s          r#   re   PaliGemmaProcessor.__init__{   s     "HIIABB(:;;Z[[ / @ @y-00$[UDQK8;-HM((7"+"A"A+"ND*D"+":":D(44D\*"'	"'	=Qr"   imagestextrg   r3   c                 <   [        X5      u  pU R                  " [        4SU R                  R                  0UD6nUS   R                  SS5      nUb  SOSnUc  [        S5      eUc  [        R                  S5        S	n[        U5      (       a  U/nO)[        U[        5      (       a  [        US
   5      (       a   UGbg  UGbc  [        S U 5       5      (       Gd  [        R                  S5        [        U[        5      (       aQ  [        U[        5      (       a<  [        U5      [        U5      :w  a$  [        S[        U5       S[        U5       S35      e[!        U5      (       a  U//nO[        U[        ["        45      (       a&  [!        US
   5      (       a  U V	s/ s H  o/PM     nn	OZ[        U[        ["        45      (       a4  [        US
   [        ["        45      (       a  [!        US
   S
   5      (       d  [        S5      e[%        X!5       V
Vs/ s HT  u  p['        U
U R                  R(                  U R*                  [,        [        U[        5      (       a  [        U5      OSS9PMV     nn
n[/        U5      nO/ nU H  nUR1                  [,        [,        U R*                  -  5      nUR3                  [,        5      nUS:w  a  U[        [,        5      -   OS
nUSU U R                  R(                  -   UUS -   nUR5                  U5        M     U Vs/ s H  o S3PM	     nnUb  [        U5      (       a  U/nUb)  U Vs/ s H  nUU R                  R6                  -   PM     nnU R8                  " U40 US   D6S   nUS   R                  SS5      nU R                  " W4UUS.US   D6nU R;                  UUS/S9  0 UESU0EnU(       a.  US   R=                  US   S
:H  S5      nUR?                  SU05        [A        UUS9$ s  sn	f s  snn
f s  snf s  snf ) a  
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              3   4   #    U  H  n[         U;   v   M     g 7fr<   )r\   ).0samples     r#   	<genexpr>.PaliGemmaProcessor.__call__.<locals>.<genexpr>   s     @4{f,4s   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.zAimages must be an image, list of images or list of list of images   rD   rC   r-   pixel_valuesreturn_tensors)	text_pairreturn_token_type_idsimage)
modalities	input_idstoken_type_idsilabels)datatensor_type)!r   _merge_kwargsr*   rO   init_kwargspoprZ   loggerwarning_oncerA   r6   listanywarningr   lenr	   tupleziprJ   rF   rV   r\   r
   replacerfindappend	eos_tokenrN   _check_special_mm_tokensmasked_fillupdater   )rf   rk   rl   audiovideosrg   output_kwargsr   rz   r{   rE   
image_listinput_stringsexpanded_samplesrr   expanded_samplebos_rfind_index	bos_indexsfxrw   rx   inputsreturn_datar   s                           r#   __call__PaliGemmaProcessor.__call__   s,   D 9F**$
"&.."<"<
 

 }-11(DA(.(:>eff<o DD!!6Dd##(8a(A(A 2@4@@@< dD))j.F.F6{c$i/('F}LT  LW  X 
 "&))%hZFu66>&QR);T;T39:6%g6F:Fve}55"6!9tUm<<&vay|44$%hii /2$.?	! /@* ,%"&..":":&*&;&;$/6@T6R6R3z?XY /@  	! 2&9#% "F&,nn[+PTPePeBe&fO&5&;&;K&HOFUY[F[#k2B BabI'
3dnn6N6NNQ`ajakQll $ %++O< # >N N=M682=M N"26":":XF@FGcDNN444FG++FUmO6TUVde&}599:JDQ
"7
 M*	
 	%%mV	%R>>> K(44V<L5MQR5RTXYF&12.IIg ;	!* !O
 Hs   P	APP#Pc                 :    U R                   R                  " U0 UD6$ )z
This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
)rO   batch_decoderf   argsrg   s      r#   r   PaliGemmaProcessor.batch_decode>  s    
 ~~**D;F;;r"   c                 :    U R                   R                  " U0 UD6$ )z
This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
)rO   decoder   s      r#   r   PaliGemmaProcessor.decodeF  s    
 ~~$$d5f55r"   c                     U R                   R                  nU R                  R                  n[        [        R                  X-   5      5      $ r<   )rO   model_input_namesrN   r   dictfromkeys)rf   tokenizer_input_namesimage_processor_input_namess      r#   r   $PaliGemmaProcessor.model_input_namesM  s>     !% @ @&*&:&:&L&L#DMM"7"UVWWr"   )rV   rH   r_   )NNN)NNNN)r   r   r   r   __doc__
attributesvalid_kwargsimage_processor_classtokenizer_classre   r   r   r   r   r   r   r*   r   r   r   r   propertyr   r!   __classcell__)ri   s   @r#   rL   rL   f   s     $[1J#$LP>O 	RD "^b`J`J I0$y/4HYCZZ[`J 12`J 
`JF<6 X Xr"   rL   N)(r   typingr   r   r   feature_extraction_utilsr   image_utilsr   r	   r
   processing_utilsr   r   r   r   r   r   tokenization_utils_baser   r   r   utilsr   
get_loggerr   r   r\   rangera   r   r%   r*   r(   r:   r?   rA   rJ   rL   __all__)is   0r#   <module>r      s    ) ( 4 O O  
  
		H	%).t5A$qgQ5RWX[R\8]R\Q4#waR\8]]d* d#L #
/u 
;4 ;
0BN,lX lX^  
 W	 68]s   C8C