o
    Zh+                     @   s   d Z ddlmZmZ ddlmZ ddl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 eeZG d	d
 d
eddZdefddZdd ZG dd deZdgZdS )z
Processor class for Pixtral.
    )ListUnion   )BatchFeature)
ImageInputis_valid_image
load_image)ProcessingKwargsProcessorMixinUnpack!_validate_images_text_input_order)PreTokenizedInput	TextInput)loggingc                   @   s    e Zd Zddii ddidZdS )PixtralProcessorKwargspaddingFreturn_tensorspt)text_kwargsimages_kwargsZcommon_kwargsN)__name__
__module____qualname__	_defaults r   r   ]/var/www/auris/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_url,   s   r#   c                 C   s   t | pt| S N)r#   r   )elemr   r   r   is_image_or_image_url1   s   r&   c                
       s   e Zd ZdZddgZg dZdZdZ							
		ddedef fddZ					dde
deeeee ee f dee defddZdd Zdd Zedd Z  ZS )PixtralProcessorab  
    Constructs a Pixtral processor which wraps a Pixtral image processor and a Pixtral tokenizer into a single processor.

    [`PixtralProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the
    [`~PixtralProcessor.__call__`] and [`~PixtralProcessor.decode`] for more information.

    Args:
        image_processor ([`PixtralImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`LlamaTokenizerFast`], *optional*):
            The tokenizer is a required input.
        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.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
        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.
    image_processor	tokenizer)chat_template
patch_sizespatial_merge_sizeimage_tokenimage_break_tokenimage_end_tokenZAutoImageProcessorZAutoTokenizerN      [IMG][IMG_BREAK]	[IMG_END]r+   r,   c	           
         sB   || _ || _|| _|| j| _|| _|| _t j|||d d S )N)r*   )	r+   r,   r-   Zconvert_tokens_to_idsZimage_token_idr.   r/   super__init__)
selfr(   r)   r+   r,   r*   r-   r.   r/   kwargs	__class__r   r   r6   [   s   zPixtralProcessor.__init__imagestextr8   r   c                 K   sD  t ||\}}| jtfd| jji|}| j| j }|durmt|r&|g}n2t|t	t
fr4t|d r4n$t|t	t
frTt|d t	t
frTt|d d rTdd |D }ntddd |D }| j|fd|i|d	 }ni }t|trx|g}nt|t	st|d tst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 sd|v r|d}|d|d}d|v s|	| q|d dd}| j|	fi |d }| j|	|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 LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
        of the above two methods for more information.

        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).
            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`.
        Ztokenizer_init_kwargsNr   c                 S      g | ]	}|D ]}|qqS r   r   ).0sublistimager   r   r   
<listcomp>       z-PixtralProcessor.__call__.<locals>.<listcomp>zdInvalid input images. Please provide a single image, a list of images, or a list of lists of images.c                 S   s"   g | ]}t |trt|n|qS r   )r   r    r   )r>   Zimr   r   r   rA      s   " r+   r   zAInvalid input text. Please provide a string, or a list of stringsZpixel_valuesimage_sizesc                 S   r=   r   r   )r>   r?   itemr   r   r   rA      rB    z<placeholder>r1   r   r   r@   )Z
modalities)dataZtensor_type)r   Z_merge_kwargsr   r)   Zinit_kwargsr+   r,   r&   r   listtuple
ValueErrorr(   r    getiterr-   nextr.   r/   joinappendreplacepopZ_check_special_mm_tokensr   )r7   r;   r<   ZaudioZvideosr8   Zoutput_kwargsr+   Zimage_inputsZprompt_stringsrC   Zreplace_stringssampleheightwidthZnum_height_tokensZnum_width_tokensZreplace_tokensZreplace_strr   Ztext_inputsr   r   r   __call__o   sx   )






zPixtralProcessor.__call__c                 O      | j j|i |S )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r)   batch_decoder7   argsr8   r   r   r   rW         zPixtralProcessor.batch_decodec                 O   rV   )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r)   decoderX   r   r   r   r[      rZ   zPixtralProcessor.decodec                 C   s"   | j j}| jj}tt|| S r$   )r)   model_input_namesr(   rH   dictfromkeys)r7   Ztokenizer_input_namesZimage_processor_input_namesr   r   r   r\      s   z"PixtralProcessor.model_input_names)NNr0   r1   Nr2   r3   r4   )NNNN)r   r   r   __doc__
attributesZvalid_kwargsZimage_processor_classZtokenizer_classintr6   r   r   r   r   r   r   r   r   rU   rW   r[   propertyr\   __classcell__r   r   r9   r   r'   5   sH    
nr'   N)r_   typingr   r   Zfeature_extraction_utilsr   Zimage_utilsr   r   r   Zprocessing_utilsr	   r
   r   r   Ztokenization_utils_baser   r   utilsr   Z
get_loggerr   loggerr   boolr#   r&   r'   __all__r   r   r   r   <module>   s   
 
@