a
    h.                     @   s   d dl mZmZ 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mZmZ ddlmZmZ ddlmZ e r~d	d
lmZ G dd deddZG dd de
ddZG dd deddZG dd deZdgZdS )    )OptionalUnionN   )BatchFeature)
ImageInput)ImagesKwargsMultiModalDataProcessingKwargsProcessorMixin
TextKwargsUnpack)PreTokenizedInput	TextInput)is_vision_available   )smart_resizec                   @   s   e Zd ZU eed< dS )Emu3TextKwargsreturn_for_image_generationN)__name__
__module____qualname__bool__annotations__ r   r   d/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/emu3/processing_emu3.pyr       s   
r   F)totalc                   @   s   e Zd ZU eed< eed< dS )Emu3ImagesKwargsratio
image_areaN)r   r   r   strr   intr   r   r   r   r   $   s   
r   c                   @   s4   e Zd ZU eed< eed< dddddddZd	S )
Emu3ProcessorKwargstext_kwargsimages_kwargsF)r   return_mm_token_type_idsz1:1i  )r   r   )r"   r#   N)r   r   r   r   r   r   	_defaultsr   r   r   r   r!   )   s   
r!   c                	       s   e Zd ZdZddgZdZdZd fdd	Zdee	 ee
eeee ee f  ee ed	d
dZdddZdd Ze	dddZ  ZS )Emu3Processora  
    Constructs a Emu3 processor which wraps a Emu3 image processor and a GPT2 tokenizer into a single
    processor.

    [`Emu3Processor`] offers all the functionalities of [`Emu3ImageProcessor`] and [`GPT2TokenizerFast`].
    See the [`~Emu3Processor.__call__`] and [`~Emu3Processor.decode`] for more information.

    Args:
        image_processor ([`Emu3ImageProcessor`]):
            The image processor is a required input.
        tokenizer ([`Emu3TokenizerFast`]):
            The tokenizer is a required input.
        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)ZGPT2TokenizerZGPT2TokenizerFastZEmu3ImageProcessorNc                    sT   |j | _ |j| _|j| _|j| _|j| _|j| _|j	| _	d| _
t j|||d d S )N   )chat_template)image_tokenimage_token_idZ	boi_tokenimage_start_tokenZ	eoi_tokenimage_end_tokenZimage_wrapper_tokenfake_token_around_image	eof_token	bos_tokendownsample_ratiosuper__init__)selfr'   r(   r*   kwargs	__class__r   r   r4   M   s    zEmu3Processor.__init__)imagestextr6   returnc                    s  t |tr|g}n t |ts2t |d ts2tdjtfdjji|}|d dd}|d dd	}|d d
d	}	|r|d	urt	d|s|d	u r|d	u rt	di }
j
 }j j }|s|d	urj|fi |d }
t|
j}g }|D ]}j|v rt|}|\}}|j }|j }||d  }| | d| j d|  | }|j|d}j | }q|| q fdd|D }n\|r||	j\}}| | d| j   fdd|D }||ggt| |
d< |d dd	}|d dd}j|fi |d dd	i}j||dgd |rt|d }t|d }d||jk< | |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 Emu3TokenizerFast's [`~Emu3TokenizerFast.__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`.
        r   zAInvalid input text. Please provide a string, or a list of stringsZtokenizer_init_kwargsr"   r   Fr#   r   Nr   zGYou should not provide `images` when `return_for_image_generation=True`zOYou must provide either text or images when `return_for_image_generation=False`r   *<placeholder>c                    s   g | ]}| d  jqS )r=   )replacer+   .0sample)r5   r   r   
<listcomp>       z*Emu3Processor.__call__.<locals>.<listcomp>c                    s   g | ]}j  |   qS r   )r1   r?   Zimage_promptr5   r   r   rB      rC   image_sizesreturn_tensorsr$   image)Z
modalitiesZ	input_idsmm_token_type_ids)dataZtensor_type) 
isinstancer   list	TypeErrorZ_merge_kwargsr!   r(   Zinit_kwargspop
ValueErrorr-   r0   r.   r'   iterrE   r+   nextr2   r/   r>   r1   appendcalculate_generate_sizelenZ_check_special_mm_tokensnparrayZ
zeros_liker,   tolistr   )r5   r9   r:   ZaudioZvideosr6   Zoutput_kwargsr   r   r   Zimage_featuresZimage_start_tokensZimage_end_tokensrE   Zprompt_stringsrA   Z
image_sizeheightwidthimage_seq_lengthZimage_placeholderrF   r$   Ztext_inputsZ	array_idsrH   r   rD   r   __call__^   sh    *



$zEmu3Processor.__call__c           	      K   s   i }|durg }|D ]R\}}t ||| jj| jj| jj\}}|| j }|| j }||d  }|| qdgt| }|||d t	f 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.
        Nr   )num_image_tokensnum_image_patches)
r   r'   spatial_factorZ
min_pixelsZ
max_pixelsr2   rQ   rS   updater   )	r5   rE   r6   Zvision_datar[   rW   rX   rY   r\   r   r   r   _get_num_multimodal_tokens   s$    

z(Emu3Processor._get_num_multimodal_tokensc           
      C   sX   t t|d\}}|| }|| d }tt|| | }tt|| | }	||	fS )N:g      ?)mapr    splitround)
r5   r   r   r]   rX   rW   Zcurrent_areaZtarget_ratioZtoken_heightZtoken_widthr   r   r   rR      s    z%Emu3Processor.calculate_generate_size)r9   c                 K   s   | j j|fi |S )N)r'   postprocess)r5   r9   r6   r   r   r   rd      s    zEmu3Processor.postprocess)N)NNNN)N)r   r   r   __doc__
attributesZtokenizer_classZimage_processor_classr4   r   r   r   r   r   rK   r   r!   r   rZ   r_   rR   rd   __classcell__r   r   r7   r   r&   8   s&        k
"	r&   )typingr   r   numpyrT   Zimage_processing_utilsr   Zimage_utilsr   Zprocessing_utilsr   r   r	   r
   r   r   Ztokenization_utils_baser   r   utilsr   Zimage_processing_emu3r   r   r   r!   r&   __all__r   r   r   r   <module>   s     A