
    %	&hQ                     b   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
mZ ddlmZmZ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 ddlmZmZmZm Z  erddlm!Z!  ejD                  e#      Z$ e       rddl%m%Z% ndZ%d Z&d Z'd Z( G d ded      Z) G d ded      Z* G d de      Z+dgZ,y)z
Processor class for SmolVLM.
    N)	timedelta)TYPE_CHECKINGDictListOptionalUnion   )BatchFeature)
ImageInput
VideoInputmake_batched_videosmake_nested_list_of_images)ImagesKwargsProcessingKwargsProcessorMixinUnpack)BatchEncoding	TextInput)is_num2words_availablelogging   )DEFAULT_MEDIA_OUTTRODEFAULT_VIDEO_INTROFRAME_TIMESTAMP_MESSAGEsmolvlm_sample_indices_fn)PreTokenizedInput)	num2wordsc           	          d}t        |      D ]4  }t        |      D ]  }|| d|dz    d|dz    dz   | | z  z   z  }! |dz  }6 |d| | z   | | z  z   | z   z  }|S )zKPrompt with expanded image tokens for when the image is split into patches. z<row_r   _col_>
)range)	image_seq_len
image_rows
image_colsfake_token_around_imageimage_tokenglobal_image_tokentext_split_imagesn_hn_ws	            /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/smolvlm/processing_smolvlm.py_prompt_split_imager.   5   s     Z  "$ 	C*+sQwiuS1WIQ/OOU`TaerRrr	 	T!" 
$%& 	"M]
*	+ %%	'     c                 &    | | z   | | z  z   | z   S )z5Prompt with expanded image tokens for a single image. )r$   r'   r(   r)   s       r-   _prompt_single_imager2   J   s6     #
# 	"M]
*	+ %%	'r/   c                 T    | dk(  r|dk(  rt        ||||      S t        || ||||      S )Nr   )r'   r(   r)   )r2   r.   )r%   r&   r$   r'   r(   r)   s         r-   get_image_prompt_stringr4   T   sH     Q:?#$;#1	
 	
 z:/FUg r/   c                   8    e Zd ZU ee   ed<   eeeef      ed<   y)SmolVLMImagesKwargsreturn_row_col_infomax_image_sizeN)	__name__
__module____qualname__r   bool__annotations__r   strintr1   r/   r-   r6   r6   c   s    !$'T#s(^,,r/   r6   F)totalc                   .    e Zd ZU eed<   ddddddidZy)SmolVLMProcessorKwargsimages_kwargsTF)add_special_tokenspaddingis_split_into_wordsr7   )text_kwargsrC   N)r9   r:   r;   r6   r=   	_defaultsr1   r/   r-   rB   rB   h   s+    && #'#(
 "4
	Ir/   rB   c                   <    e Zd ZdZddgZddgZdZdZ	 ddede	e
   f fdZ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Zdeeee
e
f         dee   dee   deeee
ef         fdZd Zd Zed        Z	 	 	 	 	 d fd	Z xZS )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`, *optional*):
            An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer 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	tokenizerr$   chat_templateSmolVLMImageProcessorAutoTokenizerc                    t        |dd      | _        t        |dd      | _        t        |dd      | _        t        |dd      | _        || _        |j                  d	   | _        |j                  | _	        |j                  | _
        |j                  j                  d
d      | _        |j                  d   | _        |j                  d   | _        t        st!        d      t#        | H  ||fd|i| y )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`.rM   )getattrrQ   r(   rR   r)   r$   video_samplingrS   size
image_sizerT   getdo_video_splittingdefault_max_framesdefault_fpsr   ImportErrorsuper__init__)selfrK   rL   r$   rM   kwargs	__class__s         r-   ra   zSmolVLMProcessor.__init__   s     !(	3EGb c"9mYG&-i9QSg&h#"))5I>"Z*)88F).."1"D"D"1"@"@"D"DEY[`"a"1"@"@"N*99%@ t  	)[=[TZ[r/   c           
      T   |(|D cg c]  }|j                  | j                         }}|D cg c]  }t        |       }	} | j                  |f||d|d   }
|d |
fS |	k7  rt	        d| d|	 d      |
j                  ddgt        |      z  g      }|
j                  ddgt        |      z  g      }g }t        |||      D ]  \  }}}g }t        ||      D ]O  \  }}t        ||| j                  | j                  | j                  | j                  	      }|j                  |       Q |j                  | j                        }t        |      dk(  rt	        d
      |d   }t        |      D ]  \  }}||||dz      z   z  } |j                  |        ||
fS c c}w c c}w )N)rT   rY   rC   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   )countr(   lenrK   
ValueErrorpopzipr4   r$   rQ   r)   appendsplit	enumerate)rb   textimagesoutput_kwargsrT   image_processor_sizesamplen_images_in_textsublistn_images_in_imagesimage_inputsr%   r&   prompt_stringssample_rowssample_colsimage_prompt_stringsn_rowsn_colsimage_prompt_stringsplit_sampleis                         r-   process_visionzSmolVLMProcessor.process_vision   s   MQR6T-=-= >RR:@Awc'lAA+t++
'9@T
XefuXv
 <%%!1134D3E\RdQeeyz  "%%fsSY.?@
!%%fsSY.?@
03D*j0Q 	*,FK#% "%k;"? 	A&=&& $ 0 0,0,A,A'+'>'>'# %++,?@	A "<<(8(89L< A% !QRR "!_F*34H*I D&&-QU0CCCD!!&)-	*0 |++U  SAs
   "F F%rq   rp   r   videosrc   returnc                 j   |||t        d      ||du |duz  rt        d       | j                  t        fd| j                  j                  i|}|t        |t              r|g}n.t        |t              st        |d   t              st        d      t        |D cg c]  }|j                  | j                         c}      }|dkD  r||t        d| d      t               }	|Jt        |      }| j                  |||| j                  | j                  	      \  }}
|	j!                  |
       nK|It#        |      }| j                  |||| j                  | j$                  	      \  }}
|	j!                  |
       |( | j                  dd
|i|d   }|	j!                  |       |	S c c}w )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>`.
            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`tokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringszWe detected z4 tokens in the text but no images/videos were passed)rT   rs   rp   rG   r1   )rj   _merge_kwargsrB   rL   init_kwargs
isinstancer>   listsumrh   r(   r
   r   r   rT   rZ   updater   rS   )rb   rq   rp   audior   rc   rr   rt   ru   inputsvision_inputstext_inputss               r-   __call__zSmolVLMProcessor.__call__   s   h <FNv~TUU<fnt1CDSTT***"
"&.."<"<
 
 $$vd+JtAw4L !dee"QU#VvFLL1A1A$B#VW!#FN <0@/AAu!vww/7F"&"5"5#'#:#:%)__ #6 #D- MM-((0F"&"5"5#'#:#:%)__ #6 #D- MM-(($..SdSmM6RSKMM+&? $Ws   ""F0conversationsbatch_imagesbatch_videosbatch_video_metadatac                    t        j                  |      }g g }}t        ||      D ]  \  }}	t        ||	      D ]  \  }
}t        |
d      }t        |
d      }t        |
d      }g }t        ||      D ]>  \  }}||z  }t	        |dz        }t	        |dz        }|j                  |dd|d       @ |j                  |       |j                  t        |               |D ]"  }|D ]  }d|vr	g }|d   D ]  }|j                  d      d	k(  r|j                  d
      }|j                  d
      }t        t	                    }|j                  dt        j                  t        |      t        |            d       t        |      D ]@  \  }}|j                  dt        j                  |      d       |j                  ddi       B |j                  dt         d       |j                  |        ||d<    % |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 overriden 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.
        durationframes_indicesrV   <   02d:contenttypevideor   )secondsrp   )frame_countvideo_duration)r   rp   )	timestampimage)copydeepcopyrl   rW   r?   rm   ri   r[   rk   r   r   formatr   r>   ro   r   r   )rb   r   r   r   r   chat_template_kwargsbatch_num_framesbatch_timestampsmetadata_list
video_listmetadatar   duration_sec
frames_idxrV   
timestampsidxframe_npsecmmssconversationmsgnew_contentblockcurr_timestampscurr_num_framestdr   tss                                 r-   #_process_messages_for_chat_templatez4SmolVLMProcessor._process_messages_for_chat_template?  s=   > m4-/*),-A<)P 	4%M:#&}j#A 4%&x<$X/?@
h.
%(U%; <MC)CSBYBS2XB%%C"S&:;	<
 !''
3 ''E
34	4 * $	-L# "-C'  ^ 2Eyy(G3*:*>*>q*A*:*>*>q*A 's</@A#**(.(;(B(B09/0J[^_a[b)" &/%? BEAr'..H_HfHfqsHt/uv'../@AB
 $**FDX+YZ $**5152: "-IE"-$	-J r/   c                 >     | 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.
        )rL   batch_decode)rb   argsrc   batched_decode_outputs       r-   r   zSmolVLMProcessor.batch_decode  s&    
 !< ; ;T LV L$$r/   c                 >     | j                   j                  |i |}|S )z
        This method forwards all its arguments to SmolVLMTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )rL   decode)rb   r   rc   decode_outputs       r-   r   zSmolVLMProcessor.decode  s%    
 .--t>v>r/   c                     | j                   j                  }| j                  j                  }t        t        j                  ||z               S )N)rL   model_input_namesrK   r   dictfromkeys)rb   tokenizer_input_namesimage_processor_input_namess      r-   r   z"SmolVLMProcessor.model_input_names  s?     $ @ @&*&:&:&L&L#DMM"=@U"UVWWr/   c                     | j                   n| j                  nfd}|s|}t        	|   |f||d|S )Nc                 $    t        | fd|S )N)rU   
target_fps	skip_secs)r   )r   	fn_kwargsrU   r   r   s     r-   sample_indices_fn_funczDSmolVLMProcessor.apply_chat_template.<locals>.sample_indices_fn_func  s(    ,%/JR[_h r/   )video_load_backendsample_indices_fn)r]   r^   r`   apply_chat_template)
rb   r   rU   r   r   r   r   rc   r   rd   s
     ```    r-   r   z$SmolVLMProcessor.apply_chat_template  sa     1;0BT,,

)3);T%%
	 ! 6w*
-?Sd
hn
 	
r/   )N   N)FN)NNNN)NNr   pyavN)r9   r:   r;   __doc__
attributesvalid_kwargsimage_processor_classtokenizer_classr?   r   r>   ra   r   r   r   r   r   r   r   rB   r   r   r   anyr   r   r   propertyr   r   __classcell__)rd   s   @r-   rJ   rJ   w   st   & $[1J#_5L3%O im\>A\X`adXe\6,,` OSbf!dj$z"2Dj9I4JJKd I2DOTJ]E^^_d
 d /0d 
dLUDc3h01U :&U :&	U
 #4S#X#78Un% X X !
 
r/   rJ   )-r   r   datetimer   typingr   r   r   r   r   feature_extraction_utilsr
   image_utilsr   r   r   r   processing_utilsr   r   r   r   tokenization_utils_baser   r   utilsr   r   video_processing_smolvlmr   r   r   r   r   
get_loggerr9   loggerr   r.   r2   r4   r6   rB   rJ   __all__r1   r/   r-   <module>r      s      = = 4  W V ? 4  <			H	% #I*-,e -
-U N
~ N
b
 
r/   