o
    ei$%                     @   s   d 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 e r;d	d
lmZ eeZG dd de
ddZdefddZdd ZeG dd deZdgZdS )z
Processor class for Pixtral.
    N   )BatchFeature)
ImageInputis_valid_image)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)auto_docstringis_vision_availablelogging   )get_resize_output_image_sizec                   @   s    e Zd ZdddddidZdS )PixtralProcessorKwargsF)paddingreturn_mm_token_type_idsreturn_tensorspt)text_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults r   r   l/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/pixtral/processing_pixtral.pyr   '   s    
r   F)totalreturnc                 C   s   t | to	| dS )Nhttp)
isinstancestr
startswith)valr   r   r   is_url4   s   r%   c                 C   s   t | pt| S N)r%   r   )elemr   r   r   is_image_or_image_url9   s   r(   c                
       s   e Zd Z								ddedef fd	d
Ze		ddedB deeB e	e B e	e B de
e defddZdddZedd Z  ZS )PixtralProcessorN   r   [IMG][IMG_BREAK]	[IMG_END]
patch_sizespatial_merge_sizec	           
         s~   || _ || _|| _|| j| _|| _|| _|| j| _|| j| _|| j| _| j| j| jg| _	t
 j|||d dS )a  
        patch_size (`int`, *optional*, defaults to 16):
            Patch size from the vision tower.
        spatial_merge_size (`int`, *optional*, defaults to 1):
            The downsampling factor for the spatial merge operation.
        image_token (`str`, *optional*, defaults to `"[IMG]"`):
            Special token used to denote image location.
        image_break_token (`str`, *optional*, defaults to `"[IMG_BREAK]"`):
            Special token used to denote the end of a line of pixels in an image.
        image_end_token (`str`, *optional*, defaults to `"[IMG_END]"`):
            Special token used to denote the end of an image input.
        )chat_templateN)r.   r/   image_tokenconvert_tokens_to_idsimage_token_idimage_break_tokenimage_end_tokenimage_break_token_idimage_end_token_id	image_idssuper__init__)
selfimage_processor	tokenizerr.   r/   r0   r1   r4   r5   kwargs	__class__r   r   r:   ?   s   zPixtralProcessor.__init__imagestextr>   r   c                 K   s*  | j tfdt| jdi i|}| j| j }|dur,||d d< | j|fi |d }ni }t|tr7|g}nt|t	sGt|d tsGt
d|}|ddurt|d	 }g }g }	|D ]^}
| j|
v rt|\}}|| }|| }| jg| | jg g| }d
d |D }| j|d< d|}|	| |
| jdd}
| j|
v scd|
v r|	d}|
d|d}
d|
v s||
 q\|d dd}|d dd}|d dd | j|fi |d ddi}| j||dgd |rt|d }t|d }d|t|| j< | |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`.
        tokenizer_init_kwargsinit_kwargsNimages_kwargsr.   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesimage_sizesc                 S   s   g | ]	}|D ]}|qqS r   r   ).0sublistitemr   r   r   
<listcomp>   s    z-PixtralProcessor.__call__.<locals>.<listcomp> z<placeholder>r   r   r   r   Freturn_token_type_idsimage)
modalities	input_idsmm_token_type_ids)datatensor_type)_merge_kwargsr   getattrr=   r.   r/   r<   r!   r"   list	TypeErrorgetiterr1   nextr4   r5   joinappendreplacepop_check_special_mm_tokensnparray
zeros_likeisinr8   tolistr   )r;   rA   rB   r>   output_kwargsr.   image_inputsprompt_stringsrG   replace_stringssampleheightwidthnum_height_tokensnum_width_tokensreplace_tokensreplace_strr   r   text_inputs	array_idsrR   r   r   r   __call__c   sh   






zPixtralProcessor.__call__c                 K   s   i }|durbt jdi }|| |ddp| jj}| j| j }g }|D ],\}}	tt	
||	df|d |d f||fd\}
}|
| }|| }||d |  q&dgt| }|||d td	i |S )
a  
        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.

        Returns:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        NrE   sizer   longest_edge)rt   r.   r   )num_image_tokensnum_image_patchesr   )r   r   rY   updater<   rt   r.   r/   r   ra   zerosr]   lenr   )r;   rG   r>   vision_datarE   rt   r.   rv   rk   rl   resized_heightresized_widthrm   rn   rw   r   r   r   _get_num_multimodal_tokens   s&   

z+PixtralProcessor._get_num_multimodal_tokensc                 C   s   | j j}| jj}|| dg S )NrG   )r=   model_input_namesr<   )r;   tokenizer_input_namesimage_processor_input_namesr   r   r   r      s   z"PixtralProcessor.model_input_names)NNr*   r   Nr+   r,   r-   )NNr&   )r   r   r   intr:   r   r   r   r
   rW   r	   r   r   rs   r~   propertyr   __classcell__r   r   r?   r   r)   =   s:    $
O$r)   )__doc__numpyra   feature_extraction_utilsr   image_utilsr   r   processing_utilsr   r   r   r	   tokenization_utils_baser
   r   utilsr   r   r   image_processing_pixtralr   
get_loggerr   loggerr   boolr%   r(   r)   __all__r   r   r   r   <module>   s"   
 
!