
    <h+                         S r SSKJr  SSK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  SSKJrJr  SS	KJr  \R*                  " \5      r " S
 S\SS9r " S S\5      rS/rg)z
Processor class for Llava.
    )UnionN   )BatchFeature)
ImageInputget_image_sizeto_numpy_array)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)loggingc                   $    \ rS rSrSSS.0 S.rSrg)LlavaProcessorKwargs&   F)paddingreturn_mm_token_type_ids)text_kwargsimages_kwargs N)__name__
__module____qualname____firstlineno__	_defaults__static_attributes__r       b/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/llava/processing_llava.pyr   r   &   s    #(eLIr   r   F)totalc            
          ^  \ rS rSrSrS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S jrS rS r\S 5       rSrU =r$ )LlavaProcessor-   a  
Constructs a LLaVa processor which wraps a LLaVa image processor and a LLaMa tokenizer into a single processor.

[`LlavaProcessor`] offers all the functionalities of [`LlavaImageProcessor`] and [`LlamaTokenizerFast`]. See the
[`~LlavaProcessor.__call__`] and [`~LlavaProcessor.decode`] for more information.

Args:
    image_processor ([`LlavaImageProcessor`], *optional*):
        The image processor is a required input.
    tokenizer ([`LlamaTokenizerFast`], *optional*):
        The tokenizer is a required input.
    patch_size (`int`, *optional*):
        Patch size from the vision tower.
    vision_feature_select_strategy (`str`, *optional*):
        The feature selection strategy used to select the vision feature from the vision backbone.
        Should be same as in model's config
    chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
        in a chat into a tokenizable string.
    image_token (`str`, *optional*, defaults to `"<image>"`):
        Special token used to denote image location.
    num_additional_image_tokens (`int`, *optional*, defaults to 0):
        Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
        extra tokens appended, no need to set this arg.
image_processor	tokenizerAutoImageProcessorAutoTokenizerc                    > X0l         Xpl        X@l        [        US5      (       a  UR                  OUU l        UR                  U R                  SS9S   U l        [        T	U ]!  XUS9  g )Nimage_tokenF)add_special_tokensr   )chat_template)	
patch_sizenum_additional_image_tokensvision_feature_select_strategyhasattrr)   encodeimage_token_idsuper__init__)
selfr$   r%   r,   r.   r+   r)   r-   kwargs	__class__s
            r   r3   LlavaProcessor.__init__K   sj     %+F(.L+4;I}4U4U900[f'..t/?/?TY.Z[\]=Qr   imagestextr5   returnc                 H   Uc  Uc  [        S5      eU R                  " [        4SU R                  R                  0UD6nUb  U R
                  " U40 US   D6nO0 n[        U[        5      (       a  U/nO8[        U[        5      (       d#  [        US   [        5      (       d  [        S5      eUnUR                  S5      b  US   n	[        [        U	S   5      5      u  pXR                  -  XR                  -  -  U R                  -   nU R                  S:X  a  US	-  n/ nU H=  nUR!                  U R"                  U R"                  U-  5      nUR%                  U5        M?     US
   R'                  SS5      nUS
   R'                  SS5      nU R                  " U40 US
   DSS0D6nU R)                  UUS/S9  U(       aW  [*        R,                  " US   5      n[*        R.                  " US   5      nS	UUU R0                  :H  '   UR3                  5       US'   [5        0 UEUEUS9$ )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 LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
of the above two methods for more information.

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. Both channels-first and channels-last formats are supported.
    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.

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`.
    - **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`.
Nz7You have to specify at least one of `images` or `text`.tokenizer_init_kwargsr   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesdefault   r   return_tensorsr   Fimage)
modalities	input_idsmm_token_type_ids)datatensor_type)
ValueError_merge_kwargsr   r%   init_kwargsr$   
isinstancestrlist	TypeErrorgetr   r   r,   r-   r.   replacer)   appendpop_check_special_mm_tokensnparray
zeros_liker1   tolistr   )r4   r8   r9   audiovideosr5   output_kwargsimage_inputsprompt_stringsr=   heightwidthnum_image_tokenssampler@   r   text_inputs	array_idsrD   s                      r   __call__LlavaProcessor.__call__]   s=   N >dlVWW** 
"&.."<"<
 

 //Y-:XYLLdC  6DD$''
47C0H0H_`` N+7'7L*>,q/+JKMF &// 9( 00 1 22i? A% N(8(8$:J:JM]:]^%%f-  '}599:JDQ#0#?#C#CD^`e#f nn^i}]7Sidhi%%nkwi%X#[!9:I "k+.F GBCi4+>+>>?/@/G/G/IK+,!@K!@<!@n]]r   c                    0 nUb  [         R                  R                  S0 5      nUR                  U5        UR                  SS5      =(       d    U R                  R
                  nUS   US   pvX`R                  -  XpR                  -  -  nXR                  -  nU R                  S:X  a  US-  nU/[        U5      -  nS/[        U5      -  n	UR                  XS.5        [        S	0 UD6$ )
a{  
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

Args:
    image_sizes (`list[list[int]]`, *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   	crop_sizer\   r]   r>   r?   )r^   num_image_patchesr   )r   r   rN   updater$   re   r,   r-   r.   lenr	   )
r4   image_sizesr5   vision_datar   re   resized_heightresized_widthr^   rf   s
             r   _get_num_multimodal_tokens)LlavaProcessor._get_num_multimodal_tokens   s     "0::>>PRSM  (%))+t<^@T@T@^@^I,5h,?7ASM .// AmWfWfFfg @ @@22i? A%  01C4DD!"c+&6 64Dmn,,,r   c                 :    U R                   R                  " U0 UD6$ )z
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
)r%   batch_decoder4   argsr5   s      r   rp   LlavaProcessor.batch_decode   s    
 ~~**D;F;;r   c                 :    U R                   R                  " U0 UD6$ )z
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
)r%   decoderq   s      r   ru   LlavaProcessor.decode   s    
 ~~$$d5f55r   c                     U R                   R                  nU R                  R                  n[        [        R                  X-   5      5      $ N)r%   model_input_namesr$   rL   dictfromkeys)r4   tokenizer_input_namesimage_processor_input_namess      r   ry    LlavaProcessor.model_input_names   s>     !% @ @&*&:&:&L&L#DMM"7"UVWWr   )r)   r1   r-   r,   r.   )NNNNNz<image>r   )NNNNrx   )r   r   r   r   __doc__
attributesimage_processor_classtokenizer_classr3   r   r   r   r   rL   r   r   r   rb   rm   rp   ru   propertyry   r   __classcell__)r6   s   @r   r"   r"   -   s    2 $[1J0%O '+$%R( "^bU^U^ I0$y/4HYCZZ[U^ -.U^ 
U^n-@<6 X Xr   r"   )r   typingr   numpyrS   feature_extraction_utilsr   image_utilsr   r   r   processing_utilsr	   r
   r   r   tokenization_utils_baser   r   utilsr   
get_loggerr   loggerr   r"   __all__r   r   r   <module>r      sj      4 E E  D  
		H	%+5 {X^ {X| 
r   