o
    Zh'C                     @   s   d dl mZmZmZ d dlZd dlmZmZm	Z	m
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 G d	d
 d
eddZG dd deddZG dd de	ZdgZdS )    )ListOptionalUnionN)ImagesKwargsProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput   )BatchFeature)
ImageInputconcatenate_listmake_flat_list_of_images)
VideoInputVideoMetadata
load_videomake_batched_videosc                   @   s2   e Zd ZU ee ed< ee ed< ee ed< dS )InternVLImagesKwargscrop_to_patchesZmin_patchesZmax_patchesN)__name__
__module____qualname__r   bool__annotations__int r   r   _/var/www/auris/lib/python3.10/site-packages/transformers/models/internvl/processing_internvl.pyr   &   s   
 r   F)totalc                   @   s*   e Zd ZU eed< ddiddii dZdS )InternVLProcessorKwargsimages_kwargsZpadding_sideleftr   T)text_kwargsr    videos_kwargsN)r   r   r   r   r   	_defaultsr   r   r   r   r   ,   s   
 
r   c                       sD  e Zd ZdZg dZddgZdZdZdZ						d,de	f fd
dZ
dee dee	 dee	 dejdejdejfddZ				d-dee deeeeee ee f  dee dee def
ddZ	d.dedee	 deeee	f fddZd d! Zd"d# Z e!d$d% Z"	&	d/d'eed(f dee	 d)ededej#f
d*d+Z$  Z%S )0InternVLProcessoraM  
    Constructs a InternVL processor which wraps a [`AutoImageProcessor`] and
    [`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
    tokenizer functionalities. See the [`~InternVLProcessor.__call__`] and [`~InternVLProcessor.decode`] for more information.
    Args:
        image_processor ([`AutoImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`], *optional*):
            The tokenizer is a required input.
        video_processor ([`AutoVideoProcessor`], *optional*):
            The video processor is a required input.
        image_seq_length (`int`, *optional*, defaults to 256):
            The number of image token to use per image patch. it should be set so that:
            image_seq_length = (config.image_size // config.patch_size) ** 2 * (config.scale_factor**2)
        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video_processorchat_templateimage_seq_lengthZAutoImageProcessorZAutoVideoProcessorZAutoTokenizerN   c                    sN   || _ |j| _|j| _|j| _|j| _|j| _t j	|||fd|i| d S )Nr)   )
r*   start_image_tokenend_image_tokenZcontext_image_tokenimage_tokenvideo_tokenZcontext_image_token_idZimage_token_idsuper__init__)selfr&   r'   r(   r*   r)   kwargs	__class__r   r   r1   U   s   	 zInternVLProcessor.__init__textimage_num_patchesvideo_num_patchesimage_num_patches_indicesvideo_num_patches_indicesvideo_patch_indicesc	                    s  d}	d}
g }g }g }|D ]}|}j |v sj|v rȈj |v rkj|vs0|j |jk rk|	dkr:||	d  nd}||	 }||||  |j dd}|j j j ||	   j  |	d7 }	nS|
dkru||
d  nd}||
 }|
dkr|| nd}||d  }||||  t|||  d	 fddt
t D }|| |jdd}|
d7 }
j |v sj|v sd|v r|d}|d|d}d|v s|| q|||	|
fS )z
        Processes interleaved text with <image> and <video> placeholders, replacing them with appropriate
        image and video tokens while keeping track of the patches used.
        r      z<placeholder>
c                 3   s@    | ]}d |d  dj  jj  |   j V  qdS )Framer<   z: N)r,   r.   r*   r-   ).0inum_patchesr2   r   r   	<genexpr>   s
    .
z?InternVLProcessor._insert_media_placeholders.<locals>.<genexpr>)r.   r/   indexappendreplacer,   r*   r-   listjoinrangelenpop)r2   r6   image_pixel_valuesvideo_pixel_valuesr7   r8   r9   r:   r;   image_indexvideo_indexZprocessed_textimage_video_patchesZreplace_stringspromptZ
new_promptstart_indexZ	end_indexZcurrent_patch_indexZend_patch_indexZvideo_promptZreplace_strr   rA   r   _insert_media_placeholdersg   sL   

"


!
z,InternVLProcessor._insert_media_placeholdersimagesvideosr3   returnc              
   K   s  |du rt d| jtfd| jji|}t|ttfs|g}g }g }i }	d}
d}t	dg}t	dg}t	dg}|dur^t
|}| jdd|i|d }|d}|d}
t|}|durt|}d	d
 |D }t|}| jdd|i|d }dd
 |D }|ddd}t|}|dus|dur| ||
||||||\}}}}|dur|t|krt d|dur|t|krt ddt|i}	|d dd}| j|fi |d }| j||dg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 PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text if `text`
        is not `None`, otherwise encode default OCR queries which depends on the `format`, `box`, `color`, `multi_page` and
        `crop_to_patches` arguments. To prepare the vision inputs, this method forwards the `images` and `kwrags` arguments to
        GotOcr2ImageProcessor's [`~GotOcr2ImageProcessor.__call__`] if `images` is not `None`.

        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).
            videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
            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`.
        NzYou have to specify text.Ztokenizer_init_kwargsr   rT   r    rB   Zpixel_valuesc                 S   s   g | ]}t |qS r   )rJ   )r?   videor   r   r   
<listcomp>   s    z.InternVLProcessor.__call__.<locals>.<listcomp>rU   r#   c                 S   s   g | ]}t |D ]}d qqS )r<   )rI   )r?   frames_r   r   r   rX      s    Zpixel_values_videosr<   zONumber of image placeholders in the prompt does not match the number of images.zONumber of video placeholders in the prompt does not match the number of videos.r"   return_tensorsimage)Z
modalities)dataZtensor_typer   )
ValueErrorZ_merge_kwargsr   r'   Zinit_kwargs
isinstancerG   tuplenparrayr   r&   rK   Zcumsumr   r(   flattenrS   rJ   r   Z_check_special_mm_tokensr   )r2   rT   r6   ZaudiorU   r3   Zoutput_kwargsr7   r8   Zimage_videos_inputsrL   rM   r9   r;   r:   Zimage_inputsZnum_frames_per_videoZvideo_inputsrP   rN   rO   r[   Ztext_inputsr   r   r   __call__   sj   )





zInternVLProcessor.__call__Tmetadata
num_framesinitial_shiftc                 C   sH   |dur|n|j }|du r|j | d }t||j |j | t}|S )a  
        The function to generate indices of frames to sample from a video.

        Args:
            metadata (`VideoMetadata`):
                `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps".
            num_frames (`int`, *optional*):
                Number of frames to sample uniformly. If None, all frames are sampled.
            initial_shift (`bool`, `float` or `int`, defaults to `0`):
                The initial shift to apply when sampling frames. If `True`, the shift is set so that frames are sampled from the middle of the video.

        Returns:
            `np.ndarray`: Array of frame indices to sample.
        NT   )Ztotal_num_framesra   ZarangeZastyper   )r2   re   rf   rg   indicesr   r   r   sample_indices_fn  s   z#InternVLProcessor.sample_indices_fnc                 O      | j j|i |S )z
        This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r'   batch_decoder2   argsr3   r   r   r   rl   '     zInternVLProcessor.batch_decodec                 O   rk   )z
        This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r'   decoderm   r   r   r   rp   .  ro   zInternVLProcessor.decodec                 C   s    | j j}| jj}t|t| S )N)r'   model_input_namesr&   rG   )r2   Ztokenizer_input_namesZimage_processor_input_namesr   r   r   rq   5  s   z#InternVLProcessor.model_input_namespyavrW   r   backendc                    s*    fdd}t |||d\}}||fS )a  
        Loads `video` to a numpy array.

        Args:
            video (`str` or `VideoInput`):
                The video to convert to the numpy array format. Can be a link to video or local path.
            num_frames (`int`, *optional*):
                Number of frames to sample uniformly. If not passed, the whole video is loaded.
            backend (`str`, *optional*, defaults to `"pyav"`):
                The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision"]. Defaults to "pyav".
            initial_shift (`bool`, *optional*, defaults to `True`):
                The initial shift to apply when sampling frames. If `True`, the shift is set so that frames are sampled from the middle of the video.

        Returns:
            Tuple[`np.array`, Dict]: A tuple containing:
                - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
                - Metadata dictionary.
        c                    s   j | f d|S )N)rf   rg   )rj   )re   Z	fn_kwargsrg   rf   r2   r   r   sample_indices_fn_funcW  s   zGInternVLProcessor._load_video_for_model.<locals>.sample_indices_fn_func)rs   rj   )r   )r2   rW   rf   rs   rg   r3   ru   re   r   rt   r   _load_video_for_model<  s   z'InternVLProcessor._load_video_for_model)NNNr+   N)NNNN)NT)rr   T)&r   r   r   __doc__
attributesZvalid_kwargsZimage_processor_classZvideo_processor_classZtokenizer_classr   r1   rG   strra   ZndarrayrS   r   r   r   r
   r	   r   r   r   r   r   rd   r   r   floatrj   rl   rp   propertyrq   rb   rv   __classcell__r   r   r4   r   r%   9   s    	
B
g



r%   )typingr   r   r   numpyra   Ztransformers.processing_utilsr   r   r   r   Z$transformers.tokenization_utils_baser	   r
   Zimage_processing_utilsr   Zimage_utilsr   r   r   Zvideo_utilsr   r   r   r   r   r   r%   __all__r   r   r   r   <module>   s     
'