o
    eiW0                     @   s   d dl ZddlmZ ddl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mZ ddlmZ eeZG d	d
 d
eddZeG dd de	ZdgZdS )    N   )BatchFeature)
ImageInput)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)auto_docstringlogging)
VideoInputc                   @   s"   e Zd ZddddddidZdS )Glm4vProcessorKwargsF)paddingreturn_token_type_idsreturn_mm_token_type_idsreturn_metadataT)text_kwargsvideos_kwargsN)__name__
__module____qualname__	_defaults r   r   h/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/glm4v/processing_glm4v.pyr   "   s    
r   F)totalc                       s   e Zd Zd fdd	Ze			ddedB deeB ee B ee B de	dB de
e def
d	d
ZdddZ	dddZdd Z  ZS )Glm4vProcessorNc                    s   t |dsdn|j| _t |dsdn|j| _t|dd r|jn|| j| _t|dd r/|jn|| j| _t j||||d d S )Nimage_tokenz	<|image|>video_tokenz	<|video|>image_token_idvideo_token_id)chat_template)	hasattrr   r   getattrr   convert_tokens_to_idsr    super__init__)selfimage_processor	tokenizervideo_processorr!   kwargs	__class__r   r   r&   /   s   



zGlm4vProcessor.__init__imagestextvideosr+   returnc                 K   s  | j tfd| jji|}|dur"| jdd|i|d }|d }ni }d}|durJ| jdd|i|d }|dsA|d	}	n|d	 }	|d
 }
ni }d}
t|t	sV|g}|
 }|dur| jjd }d}tt|D ]5}| j|| v r||  | }|| | jd| d||< |d7 }| j|| v su|| d| j||< ql|
dur| jjd }d}tt|D ]}| j|| v rs|
| d }d}|	| }|jdu rtd |jdu rdn|j|_|jddd }g }tdt|D ]	}|||  q|d| }t||k r||r|d nd t||k st|D ]}|| }| |}||7 }q|| | j|d||< |
|  | |
| d  }t|D ]}| j|| v rf|| | jd| d||< qN|d7 }| j|| v s|| d| j||< q|d dd}|d dd}| j|fi |d }| j||ddgd |rt|d }t|d }d||| jk< | |d< ti ||||dS )a  
        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.   images_kwargsimage_grid_thwr0   r   r   video_metadatavideo_grid_thw   r   z<|placeholder|>    a  SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results.   r   return_tensorsr   Fimagevideo)
modalities	input_idsmm_token_type_ids)datatensor_typer   )_merge_kwargsr   r)   init_kwargsr(   r*   getpop
isinstancelistcopy
merge_sizerangelenr   prodreplacer   fpsloggerwarning_once
timestampsappendreplace_frame_token_id_check_special_mm_tokensnparray
zeros_liker   tolistr   )r'   r.   r/   r0   r+   output_kwargsimage_inputsr4   videos_inputsr5   r6   merge_lengthindexinum_image_tokensvideo_index
num_framesvideo_structuremetadatarS   unique_timestampsidxselected_timestamps	frame_idxtimestamp_secframe_structurer<   r   text_inputs	array_idsrA   r   r   r   __call__>   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.
        Nr3   rK   c                    s"   g | ]}j jg | R  qS r   )r(   get_number_of_image_patches).0
image_size)r3   r'   r   r   
<listcomp>       z=Glm4vProcessor._get_num_multimodal_tokens.<locals>.<listcomp>c                       g | ]}| d   qS r7   r   rp   num_patchesrK   r   r   rr          )ra   num_image_patchesr   c                    s"   g | ]} j jg |R  qS r   )r*   get_number_of_video_patches)rp   
video_size)r'   r   r   r   rr      rs   c                    rt   ru   r   rv   rx   r   r   rr      ry   num_video_tokensr   )r   r   rF   updater(   rK   r   )	r'   image_sizesvideo_sizesr+   vision_datarz   ra   num_video_patchesr}   r   )r3   rK   r'   r   r   _get_num_multimodal_tokens   s&   

z)Glm4vProcessor._get_num_multimodal_tokensTFc                 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_spaces)r)   batch_decode)r'   generated_outputsr   r   r+   r   r   r   post_process_image_text_to_text   s   z.Glm4vProcessor.post_process_image_text_to_textc                 C   s   d| j  dt| S )Nz<|begin_of_image|>z<|end_of_image|>)r   int)r'   rj   r   r   r   rU      s   z%Glm4vProcessor.replace_frame_token_id)NNNN)NNN)NN)TF)r   r   r   r&   r   r   r
   r	   rI   r   r   r   r   rn   r   r   rU   __classcell__r   r   r,   r   r   -   s*    
p'
r   )numpyrW   feature_extraction_utilsr   image_utilsr   processing_utilsr   r   r   r   tokenization_utils_baser	   r
   utilsr   r   video_utilsr   
get_loggerr   rQ   r   r   __all__r   r   r   r   <module>   s   
 
G