
    g$                         d Z ddlmZm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 ddlmZmZ ddlmZ  ej        e          Z G d	 d
ed          Z G d de          ZdS )z
Processor class for Llava.
    )ListUnion   )BatchFeature)
ImageInputget_image_sizeto_numpy_array)ProcessingKwargsProcessorMixinUnpack!_validate_images_text_input_order)PreTokenizedInput	TextInput)loggingc                       e Zd Zddii dZdS )LlavaProcessorKwargspaddingF)text_kwargsimages_kwargsN)__name__
__module____qualname__	_defaults     f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/llava/processing_llava.pyr   r      s+         u
 	 IIIr   r   F)totalc            
            e Zd ZdZddgZg dZdZdZ	 	 	 	 	 	 d fd		Z	 	 	 	 dd
e	de
eeee         ee         f         dee         defdZd Zd Zed             Z xZS )LlavaProcessoraj  
    Constructs a Llava processor which wraps a Llava image processor and a Llava tokenizer into a single processor.

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

    Args:
        image_processor ([`CLIPImageProcessor`], *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.
            Shoudl 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.
    image_processor	tokenizer)chat_template
patch_sizevision_feature_select_strategyimage_tokenAutoImageProcessorAutoTokenizerN<image>c                 z    || _         || _        || _        t                                          |||           d S )N)r"   )r#   r$   r%   super__init__)	selfr    r!   r#   r$   r"   r%   kwargs	__class__s	           r   r+   zLlavaProcessor.__init__D   sA     %.L+&)=QQQQQr   imagestextr-   returnc                 f   ||t          d          t          ||          \  }} | j        t          fd| j        j        i|}| | j        |fi |d         }ni }t          |t                    r|g}n?t          |t                    s*t          |d         t                    st          d          |}|
                    d          | j        | j        |d         }	t          t          |	d                             \  }
}|
| j        z  || j        z  z  dz   }| j        d	k    r|dz  }g }|D ]:}|                    | j        | j        |z            }|                    |           ;nt$                              d
            | j        |fi |d         }t)          i ||          S )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 doctsring
        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   defaulta  Expanding inputs for image tokens in LLaVa should be done in processing. Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. Using processors without these attributes in the config is deprecated and will throw an error in v4.47.r   )data)
ValueErrorr   _merge_kwargsr   r!   init_kwargsr    
isinstancestrlistgetr#   r$   r   r	   replacer%   appendloggerwarning_oncer   )r,   r/   r0   audiovideosr-   output_kwargsimage_inputsprompt_stringsr4   heightwidthnum_image_tokenssampletext_inputss                  r   __call__zLlavaProcessor.__call__S   s   N >dlVWWW 9FF** 
 
"&."<
 
 

 /4/YY-:XYYLLLdC   	b6DDD$'' 	b
47C0H0H 	b`aaa N++7*t/R/^+N; .~l1o/N/N O O$*do$=%4?BZ#[^_#_ 6)CC$)$!#" 2 2F#^^D,<d>NQa>abbF"))&11112 ##~   %dn^TT}]7STT!@K!@<!@AAAAr   c                 &     | j         j        |i |S )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r,   argsr-   s      r   rO   zLlavaProcessor.batch_decode   s    
 +t~*D;F;;;r   c                 &     | j         j        |i |S )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r!   decoderP   s      r   rS   zLlavaProcessor.decode   s    
 %t~$d5f555r   c                     | j         j        }| j        j        }t          t                              ||z                       S )N)r!   model_input_namesr    r=   dictfromkeys)r,   tokenizer_input_namesimage_processor_input_namess      r   rU   z LlavaProcessor.model_input_names   s<     !% @&*&:&L#DMM"7:U"UVVWWWr   )NNNNNr(   )NNNN)r   r   r   __doc__
attributesvalid_kwargsimage_processor_classtokenizer_classr+   r   r   r   r   r   r   r   r   rM   rO   rS   propertyrU   __classcell__)r.   s   @r   r   r   (   sB        , $[1JcccL0%O '+R R R R R R" "^bTB TBTB I0$y/4HYCZZ[TB -.TB 
TB TB TB TBn< < <6 6 6 X X XX X X X Xr   r   N)rZ   typingr   r   feature_extraction_utilsr   image_utilsr   r   r	   processing_utilsr
   r   r   r   tokenization_utils_baser   r   utilsr   
get_loggerr   rA   r   r   r   r   r   <module>rh      s5            4 4 4 4 4 4 E E E E E E E E E E k k k k k k k k k k k k C C C C C C C C       
	H	%	%    +5    VX VX VX VX VX^ VX VX VX VX VXr   