o
    ZhY                     @   sR  d Z ddlZddlmZ ddlmZmZmZmZm	Z	 ddl
ZddlmZ ddl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mZmZ ddlmZmZm Z  e rcddl!m"Z"m#Z#m$Z$m%Z% erkddlm&Z& e'e(Z)e rzddl*m*Z* ndZ*dd Z+dd Z,dd Z-G dd deddZ.G dd deddZ/G dd deZ0dgZ1dS )z
Processor class for SmolVLM.
    N)	timedelta)TYPE_CHECKINGDictListOptionalUnion   )BatchFeature)
ImageInputmake_nested_list_of_images)ImagesKwargsProcessingKwargsProcessorMixinUnpack)BatchEncoding	TextInput)is_num2words_availableis_vision_availablelogging)
VideoInput
load_videomake_batched_videos   )DEFAULT_MEDIA_OUTTRODEFAULT_VIDEO_INTROFRAME_TIMESTAMP_MESSAGEsmolvlm_sample_indices_fn)PreTokenizedInput)	num2wordsc           	   	   C   s~   d}t |D ]$}t |D ]}|| d|d  d|d  d | |   7 }q|d7 }q|d| |  | |   |  7 }|S )zKPrompt with expanded image tokens for when the image is split into patches. z<row_r   Z_col_>
)range)	image_seq_len
image_rows
image_colsfake_token_around_imageimage_tokenglobal_image_tokenZtext_split_imagesZn_hZn_w r)   ]/var/www/auris/lib/python3.10/site-packages/transformers/models/smolvlm/processing_smolvlm.py_prompt_split_image5   s"   (
r+   c                 C   s   | |  | |   |  S )z5Prompt with expanded image tokens for a single image.r)   )r#   r&   r'   r(   r)   r)   r*   _prompt_single_imageJ   s   r,   c                 C   s2   | dkr|dkrt ||||dS t|| ||||S )Nr   )r&   r'   r(   )r,   r+   )r$   r%   r#   r&   r'   r(   r)   r)   r*   get_image_prompt_stringT   s   r-   c                   @   s.   e Zd ZU ee ed< eeeef  ed< dS )SmolVLMImagesKwargsreturn_row_col_infoZmax_image_sizeN)	__name__
__module____qualname__r   bool__annotations__r   strintr)   r)   r)   r*   r.   c   s   
 r.   F)totalc                   @   s,   e Zd ZU eed< ddddddidZdS )SmolVLMProcessorKwargsimages_kwargsTF)Zadd_special_tokenspaddingZis_split_into_wordsr/   )text_kwargsr9   N)r0   r1   r2   r.   r4   	_defaultsr)   r)   r)   r*   r8   h   s   
 
r8   c                       sN  e Zd ZdZg dZddgZdZdZdZ		d,de	de
e f fd	d
Z	d-ddZ				d.deeee eee  f deedee ed f dedee def
ddZdeeeeef   dee dee de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
e	 d(ed)e	dejfd*d+Z   Z!S )0SmolVLMProcessora}  
    Constructs a SmolVLM processor which wraps a LLama tokenizer and SmolVLM image processor into a single processor.

    [`SmolVLMProcessor`] offers all the functionalities of [`SmolVLMImageProcessor`] and [`SmolVLMTokenizerFast`]. See
    the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.

    Args:
        image_processor (`SmolVLMImageProcessor`):
            An instance of [`SmolVLMImageProcessor`]. The image processor is a required input.
        tokenizer (`PreTrainedTokenizerBase`):
            An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
        video_processor (`SmolVLMImageProcessor`):
            n instance of [`SmolVLMImageProcessor`]. The video processor is a required input.
        image_seq_len (`int`, *optional*, defaults to 169):
            The length of the image sequence i.e. the number of <image> tokens per image in the input.
            This parameter is used to build the string from the input prompt and image tokens and should match the
            value the model used. It is computed as: image_seq_len = int(((image_size // patch_size) ** 2) / (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_processorr#   chat_templateZSmolVLMImageProcessorZAutoTokenizer   Nc                    s   t |dd| _t |dd| _|| j| _t |dd| _t |dd| _|| _|jd	 | _	|j
| _|j| _|jd
d| _|jd | _|jd | _tsNtdt j|||fd|i| d S )Nfake_image_tokenz<fake_token_around_image>r'   z<image>end_of_utterance_tokenz<end_of_utterance>r(   z<global-img>
video_sizedo_image_splittingF
max_framesfpszbPackage `num2words` is required to run SmolVLM processor. Install it with `pip install num2words`.rA   )getattrrC   r'   Zconvert_tokens_to_idsZimage_token_idrD   r(   r#   Zvideo_samplingrE   size
image_sizerF   getZdo_video_splittingdefault_max_framesdefault_fpsr   ImportErrorsuper__init__)selfr>   r?   r@   r#   rA   kwargs	__class__r)   r*   rQ      s"   	 zSmolVLMProcessor.__init__Fc              
      sV  |d ur fdd|D }dd |D }||f||d|}	|d u r'd |	fS ||kr6t d| d| d|	dd	gt| g}
|	d
d	gt| g}g }t||
|D ]P\}}}g }t||D ]\}}t|| j j j jd}|	| qb|
 j}t|d	krt d|d	 }t|D ]\}}||||d   7 }q|	| qV||	fS )Nc                       g | ]}|  jqS r)   countr'   .0samplerR   r)   r*   
<listcomp>       z3SmolVLMProcessor.process_vision.<locals>.<listcomp>c                 S   s   g | ]}t |qS r)   )len)rZ   Zsublistr)   r)   r*   r]      s    )rF   rJ   z!The number of images in the text z and images z should be the same.rowsr   cols)r'   r&   r(   z.The image token should be present in the text.r   )
ValueErrorpopr_   zipr-   r#   r'   rC   r(   appendsplit	enumerate)rR   textimagesoutput_kwargsrF   image_processor_size	processorn_images_in_textZn_images_in_imagesZimage_inputsr$   r%   Zprompt_stringsr[   Zsample_rowsZsample_colsZimage_prompt_stringsZn_rowsZn_colsZimage_prompt_stringZsplit_sampleir)   r\   r*   process_vision   sN   zSmolVLMProcessor.process_visionri   rh   r   videosrS   returnc                    s  |du r|du r|du rt d|du r |du |duA r t d jtfd jji|}|durit|tr:|g}nt|tsJt|d tsJt dt fdd|D }|dkri|du ri|du rit d	| d
i }|durt	|} j
|||d  j j jd\}}	||	 n|durt|} j
|||d  j j jd\}}	||	 |d dd}
|durψ j|fi |d } j||dgd || t||
dS )a,  
        Processes the input prompts and returns a BatchEncoding.

        Example:

        ```python
        >>> import requests
        >>> from transformers import SmolVLMProcessor
        >>> from transformers.image_utils import load_image

        >>> processor = SmolVLMProcessor.from_pretrained("HuggingFaceM4/SmolVLM2-256M-Video-Instruct")
        >>> processor.image_processor.do_image_splitting = False  # Force as False to simplify the example

        >>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
        >>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"

        >>> image1, image2 = load_image(url1), load_image(url2)
        >>> images = [[image1], [image2]]

        >>> text = [
        ...     "<image>In this image, we see",
        ...     "bla bla bla<image>",
        ... ]
        >>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
        >>> input_ids = outputs.input_ids
        >>> input_tokens = processor.tokenizer.batch_decode(input_ids)
        >>> print(input_tokens)
        ['<|begin_of_text|><fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image> In this image, we see', '<|reserved_special_token_0|><|reserved_special_token_0|><|reserved_special_token_0|><|begin_of_text|>bla bla bla<fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image>']
        ```

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. If is of type `List[ImageInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
            text (`Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]`, *optional*):
                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).
                Wherever an image token, `<image>` is encountered it is expanded to
                `<fake_token_around_image>` + `<row_x_col_y>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
            videos (`List[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
                The video or batch of videos to be prepared. Each video can be a list of PIL frames, NumPy array or PyTorch
                tensor. If is of type `List[VideoInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
            return_tensors (`Union[str, TensorType]`, *optional*):
                If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
                information.
        Nz5You must provide one of `text`, `images` or `videos'.z4You must specify exactly one of `images` or `videos`Ztokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringsc                    rV   r)   rW   rY   r\   r)   r*   r]   /  r^   z-SmolVLMProcessor.__call__.<locals>.<listcomp>zWe detected z4 tokens in the text but no images/videos were passedr9   )rF   rk   rl   Zvideos_kwargsr;   return_tensorsimage)Z
modalities)Ztensor_type)rb   Z_merge_kwargsr8   r?   Zinit_kwargs
isinstancer5   listsumr   ro   rF   rK   r>   updater   rE   r@   rc   Z_check_special_mm_tokensr	   )rR   ri   rh   Zaudiorp   rS   rj   rm   ZinputsZvision_inputsrr   Ztext_inputsr)   r\   r*   __call__   s`   7




zSmolVLMProcessor.__call__conversationsbatch_imagesbatch_videosbatch_video_metadatac              
   K   s  t |}g g }}t||D ]Q\}}	t||	D ]G\}
}t|
d}t|
d}t|
d}g }t||D ] \}}|| }t|d }t|d }||dd|d q2|| |t| qq|D ]l}|D ]g}d|vrnqgg }|d D ]U}|dd	kr|d
}|d
}t	t|d}|dt
jt|t|dd t|D ]\}}|dtj|dd |ddi q|dtd qt|| qt||d< qgqc|S )a   
        Used within `apply_chat_template` when a model has special way to process conversation history. For example,
        video models might want to specify in the prompt the duration of video or which frame indices at which timestamps
        were sampled. This information cannot be accessed before the video is loaded.
        For most models it is a no-op, must be overridden by model processors which require special processing.
        Args:
            conversation (`List[Dict, str, str]`):
                The conversation to process. Always comes in batched format.
            batch_images (`List[List[ImageInput]]`):
                Batch of images that were loaded from url/path defined in the conversation. The images
                are ordered in the same way as in the conversation. Comes in nested list format, one list of `PIL` images
                per batch.
            batch_videos (`List[List[ImageInput]]`):
                Batch of videos that were loaded from url/path defined in the conversation. The videos
                are ordered in the same way as in the conversation. Comes in nested list format, one list of 4D video arrays
                per batch.
            batch_video_metadata (`List[List[Dict[[str, any]]]]`):
                Batch of metadata returned from loading videos. That includes video fps, duration and total number of framer in original video.
                Metadata are ordered in the same way as `batch_videos`. Comes in nested list format, one list of 4D video arrays
                per batch.
        durationZframes_indicesrH   <   02d:contenttypevideor   )secondsrh   )Zframe_countZvideo_duration)r   rh   )	timestamprs   )copydeepcopyrd   rI   r6   re   r_   rL   rc   r   r   formatr   r5   rg   r   r   )rR   ry   rz   r{   r|   Zchat_template_kwargsZbatch_num_framesZbatch_timestampsZmetadata_listZ
video_listmetadatar   Zduration_secZ
frames_idxrH   Z
timestampsidxZframe_npsecmmssZconversationmsgZnew_contentblockZcurr_timestampsZcurr_num_framestdrn   tsr)   r)   r*   #_process_messages_for_chat_templateU  sR   









#z4SmolVLMProcessor._process_messages_for_chat_templatec                 O      | j j|i |}|S )z
        This method forwards all its arguments to SmolVLMTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r?   batch_decode)rR   argsrS   Zbatched_decode_outputr)   r)   r*   r        zSmolVLMProcessor.batch_decodec                 O   r   )z
        This method forwards all its arguments to SmolVLMTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r?   decode)rR   r   rS   Zdecode_outputr)   r)   r*   r     r   zSmolVLMProcessor.decodec                 C   s"   | j j}| jj}tt|| S )N)r?   model_input_namesr>   ru   dictfromkeys)rR   Ztokenizer_input_namesZimage_processor_input_namesr)   r)   r*   r     s   z"SmolVLMProcessor.model_input_namesopencv        r   r   
num_framesrH   backend	skip_secsc           	         sN   |du r| j n| |du r| jn| 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.
            fps (`int`, *optional*):
                Number of frames to sample per second. Should be passed only when `num_frames=None`.
                If not specified and `num_frames==None`, all frames are sampled.
            backend (`str`, *optional*, defaults to `"opencv"`):
                The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision"]. Defaults to "opencv".

        Returns:
            Tuple[`np.array`, Dict]: A tuple containing:
                - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
                - Metadata dictionary.
        Nc                    s   t | f d|S )N)rG   
target_fpsr   )r   )r   Z	fn_kwargsrG   r   r   r)   r*   sample_indices_fn_func  s   zFSmolVLMProcessor._load_video_for_model.<locals>.sample_indices_fn_func)r   Zsample_indices_fn)rM   rN   r   )	rR   r   r   rH   r   r   rS   r   r   r)   r   r*   _load_video_for_model  s
   z&SmolVLMProcessor._load_video_for_model)rB   N)FNN)NNNN)NNr   r   )"r0   r1   r2   __doc__
attributesZvalid_kwargsZimage_processor_classZvideo_processor_classZtokenizer_classr6   r   r5   rQ   ro   r   r
   r   r   r   r   r8   r   rx   r   anyr   r   r   propertyr   nparrayr   __classcell__r)   r)   rT   r*   r=   w   s|    #
2
n
W
	
r=   )2r   r   datetimer   typingr   r   r   r   r   numpyr   Zfeature_extraction_utilsr	   Zimage_utilsr
   r   Zprocessing_utilsr   r   r   r   Ztokenization_utils_baser   r   utilsr   r   r   Zvideo_utilsr   r   r   Zvideo_processing_smolvlmr   r   r   r   r   Z
get_loggerr0   loggerr   r+   r,   r-   r.   r8   r=   __all__r)   r)   r)   r*   <module>   s8   

  
v