o
    wi:                     @   s   d dl mZmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZmZ ddlmZmZ ddlmZ G dd	 d	ed
dZG dd deZG dd de
d
dZG dd deZdgZdS )    )OptionalUnion   )BatchFeature)
ImageInput)ImagesKwargsMultiModalDataProcessingKwargsProcessorMixinUnpackVideosKwargs)PreTokenizedInput	TextInput)
VideoInputc                   @   s"   e Zd ZU eee ef ed< dS )Glm4vVideosProcessorKwargsfpsN)__name__
__module____qualname__r   listfloat__annotations__ r   r   g/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/glm4v/processing_glm4v.pyr      s   
 r   F)totalc                   @   s2   e Zd ZU ee ed< ee ed< ee ed< dS )Glm4vImagesKwargs
patch_sizetemporal_patch_size
merge_sizeN)r   r   r   r   intr   r   r   r   r   r   #   s   
 r   c                   @   s*   e Zd ZU eed< eed< dddiiZdS )Glm4vProcessorKwargsimages_kwargsvideos_kwargstext_kwargspaddingFN)r   r   r   r   r   r   	_defaultsr   r   r   r   r    )   s   
 r    c                       s   e Zd ZdZg dZdZdZdZd fdd	Z			dd	e	d
e
eeee ee f dedee def
ddZdddZdd Zdd Z	dddZedd Z  ZS ) Glm4vProcessora  
    Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor.
    [`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information.
    Args:
        image_processor ([`Glm4vProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`PreTrainedTokenizerFast`], *optional*):
            The tokenizer is a required input.
        video_processor ([`Glm4vVideoProcessor`], *optional*):
            The video processor 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video_processorAutoImageProcessorAutoVideoProcessor)PreTrainedTokenizerPreTrainedTokenizerFastNc                    s   t  j||||d t|dsdn|j| _t|dsdn|j| _t|dd r)|jn|| j| _t|dd r<|j| _d S || j| _d S )N)chat_templateimage_tokenz	<|image|>video_tokenz	<|video|>image_token_idvideo_token_id)	super__init__hasattrr/   r0   getattrr1   convert_tokens_to_idsr2   )selfr'   r(   r)   r.   kwargs	__class__r   r   r4   I   s   



zGlm4vProcessor.__init__imagestextvideosr9   returnc                 K   s6  | j tfd| jji|}|dur"| jdd|i|d }|d }ni }d}|dur@| jdd|i|d }|d}	|d	 }
ni }g }	d}
t|tsN|g}|	 }|dur| jj
d
 }d}tt|D ]5}| j|| v r||  | }|| | jd| d||< |d7 }| j|| v sm|| d| j||< qd|
durr| jj
d
 }d}tt|D ]}| j|| v rf|
| d }d}t|	dr|	 d }nt|	d tr|	d n|	}g }tdt|D ]	}|||  q|d| }t||k r
||r|d nd t||k st|D ]}|| }d| j d| }||7 }q|| | j|d||< |
|  | |
| d  }t|D ]}| j|| v rY|| | jd| d||< qA|d7 }| j|| v s|| d| j||< q|d dd}| j|fi |d }| j||d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__`] if `text` is not `None` to encode
        the text.

        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
                tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
            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`.
            - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
            - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
            - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
        tokenizer_init_kwargsNr<   r!   image_grid_thwr>   r"   
timestampsvideo_grid_thw   r   z<|placeholder|>    tolistz<|begin_of_image|>z<|end_of_image|>r#   return_tensorsimagevideo)
modalities)datatensor_typer   )_merge_kwargsr    r(   init_kwargsr'   r)   pop
isinstancer   copyr   rangelenr/   prodreplacer0   r5   rG   append_check_special_mm_tokensr   )r8   r<   r=   r>   r9   output_kwargsimage_inputsrA   videos_inputsrB   rC   merge_lengthindexinum_image_tokensvideo_index
num_framesvideo_structuretimestamps_listunique_timestampsidxselected_timestamps	frame_idxtimestamp_secframe_structurerI   text_inputsr   r   r   __call__X   s   *





 zGlm4vProcessor.__call__c           	         s   i }|dur7t jdi   |  ddpjj fdd|D }fdd|D }|||d |dur^t jdi | fd	d|D }fd
d|D }||d< tdi |S )aK  
        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.
            video_sizes (`list[list[int]]`, *optional*):
                The input sizes formatted as (num_frames, height, width) per each video.
        Returns:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        Nr!   r   c                    s"   g | ]}j jg | R  qS r   )r'   get_number_of_image_patches).0
image_size)r!   r8   r   r   
<listcomp>       z=Glm4vProcessor._get_num_multimodal_tokens.<locals>.<listcomp>c                       g | ]}| d   qS rD   r   rn   num_patchesr   r   r   rp          )r`   num_image_patchesr"   c                    s"   g | ]} j jg |R  qS r   )r)   get_number_of_video_patches)rn   
video_size)r8   r"   r   r   rp      rq   c                    rr   rs   r   rt   rv   r   r   rp      rw   num_video_tokensr   )r    r%   getupdater'   r   r   )	r8   image_sizesvideo_sizesr9   vision_datarx   r`   num_video_patchesr{   r   )r!   r   r8   r"   r   _get_num_multimodal_tokens   s&   

z)Glm4vProcessor._get_num_multimodal_tokensc                 O      | 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r8   argsr9   r   r   r   r         zGlm4vProcessor.batch_decodec                 O   r   )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   r      r   zGlm4vProcessor.decodeTFc                 K   s   | j j|f||d|S )a  
        Post-process the output of the model to decode the text.

        Args:
            generated_outputs (`torch.Tensor` or `np.ndarray`):
                The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
                or `(sequence_length,)`.
            skip_special_tokens (`bool`, *optional*, defaults to `True`):
                Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
            clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
                Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
            **kwargs:
                Additional arguments to be passed to the tokenizer's `batch_decode method`.

        Returns:
            `list[str]`: The decoded text.
        )skip_special_tokensclean_up_tokenization_spacesr   )r8   generated_outputsr   r   r9   r   r   r   post_process_image_text_to_text  s   z.Glm4vProcessor.post_process_image_text_to_textc                 C   s,   | j j}| jj}tt|| }|dg S )Nsecond_per_grid_ts)r(   model_input_namesr'   r   dictfromkeys)r8   tokenizer_input_namesimage_processor_input_namesnames_from_processorr   r   r   r     s   
z Glm4vProcessor.model_input_names)NNNN)NNN)NN)TF)r   r   r   __doc__
attributesimage_processor_classvideo_processor_classtokenizer_classr4   r   r   r   r   r   r   r   r    r   rl   r   r   r   r   propertyr   __classcell__r   r   r:   r   r&   3   s8    

x&
r&   N)typingr   r   feature_extraction_utilsr   image_utilsr   processing_utilsr   r   r	   r
   r   r   tokenization_utils_baser   r   video_utilsr   r   r   r    r&   __all__r   r   r   r   <module>   s    
 
u