a
    h                     @   s   d dl mZ ddlmZ ddlmZ ddlmZmZm	Z	 ddl
mZmZ ddlmZ eeZG dd	 d	ed
dZG dd deZdgZdS )    )Union   )BatchFeature)
ImageInput)ProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)loggingc                   @   s   e Zd Zddii dZdS )Ovis2ProcessorKwargspaddingF)text_kwargsZimage_kwargsN)__name__
__module____qualname__	_defaults r   r   f/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/ovis2/processing_ovis2.pyr      s   r   F)totalc                       s   e Zd ZdZddgZdZdZd fd	d
	Zdee	e
eee
 ee f ee edddZee
 eee  dddZdd Zdd Zedd Z  ZS )Ovis2Processora  
    Constructs a Ovis2 processor which wraps Ovis2 image processor and a Qwen2 tokenizer into a single processor.

    [`Ovis2Processor`] offers all the functionalities of [`Ovis2VideoProcessor`], [`Ovis2ImageProcessor`] and [`Qwen2TokenizerFast`]. See the
    [`~Ovis2Processor.__call__`] and [`~Ovis2Processor.decode`] for more information.

    Args:
        image_processor ([`Ovis2ImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`Qwen2TokenizerFast`], *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_token (`str`, *optional*, defaults to `"<image>"`):
            Special token used to denote image location.
        image_seq_length (`int`, *optional*, defaults to 256):
            The number of image tokens to be used for each image in the input.
    image_processor	tokenizerZAutoImageProcessorZAutoTokenizerN<image>   c                    sZ   || _ t|dr|jn|| _t|dd r.|jn
|| j| _t j||fd|i| d S )Nimage_tokenimage_token_idchat_template)image_seq_lengthhasattrr   getattrr   Zconvert_tokens_to_idssuper__init__)selfr   r   r   r   r   kwargs	__class__r   r   r"   =   s    	

zOvis2Processor.__init__)imagestextr$   returnc                 K   s   | j tfd| jji|}t|tr,|g}n t|tsLt|d tsLtdi }|dur| j|fi |d }|	d
 }| ||}| j|fi |d }ti ||d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 Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        Ovis2ImageProcessor's [`~Ovis2ImageProcessor.__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).

        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`.
            - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
        Ztokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringsNZimages_kwargsgridsr   )data)Z_merge_kwargsr   r   Zinit_kwargs
isinstancestrlist
ValueErrorr   poptolist_expand_image_tokensr   )r#   r'   r(   r$   Zoutput_kwargsZimage_inputsZimage_gridsZtext_inputsr   r   r   __call__O   s$    !
zOvis2Processor.__call__)r(   r*   c                 C   s   g }d}|D ]}d|v r|| }|d |d  }}dd| j   d}	|| dkrt|D ]J}
t|D ](}|	d| j   7 }	||d k rd|	d7 }	qd|
|d k rX|	d7 }	qX|	d	7 }	|d|	d}|d7 }q|| q|S )
Nr   r      z<IMG_START>z
<IMG_ATOM>z
<IMG_GRID>z	<IMG_COL>z	<IMG_ROW>z	<IMG_END>)r   rangereplaceappend)r#   r(   r*   Zprocessed_textZ
grid_indexsamplegridrowcolplaceholderrcr   r   r   r2      s(    


z#Ovis2Processor._expand_image_tokensc                 O   s   | j j|i |S )z
        This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r   batch_decoder#   argsr$   r   r   r   r?      s    zOvis2Processor.batch_decodec                 O   s   | j j|i |S )z
        This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r   decoder@   r   r   r   rB      s    zOvis2Processor.decodec                 C   s    | j j}| jj}t|t| S )N)r   model_input_namesr   r.   )r#   Ztokenizer_input_namesZimage_processor_input_namesr   r   r   rC      s    z Ovis2Processor.model_input_names)NNNr   r   )NN)r   r   r   __doc__
attributesZimage_processor_classZtokenizer_classr"   r   r   r
   r	   r.   r   r   r   r3   intr2   r?   rB   propertyrC   __classcell__r   r   r%   r   r   %   s2          8
r   N)typingr   Zfeature_extraction_utilsr   Zimage_utilsr   Zprocessing_utilsr   r   r   Ztokenization_utils_baser	   r
   utilsr   Z
get_loggerr   loggerr   r   __all__r   r   r   r   <module>   s   
	 