o
    i.                     @   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   e/home/ubuntu/veenaModal/venv/lib/python3.10/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d	ee	 d
ee
eeee ee f  dee defddZdddZdd Zd	e	f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)GPT2TokenizerGPT2TokenizerFastEmu3ImageProcessorNc                    sT   |j | _ |j| _|j| _|j| _|j| _|j| _|j	| _	d| _
t j|||d d S )N   )chat_template)image_tokenimage_token_id	boi_tokenimage_start_token	eoi_tokenimage_end_tokenimage_wrapper_tokenfake_token_around_image	eof_token	bos_tokendownsample_ratiosuper__init__)selfr'   r(   r-   kwargs	__class__r   r   r:   M   s   zEmu3Processor.__init__imagestextr<   returnc                    s  t |tr	|g}nt |tst |d tstdjtfdjji|}|d dd}|d dd	}|d d
d	}	|rH|d	urHt	d|sV|d	u rV|d	u rVt	di }
j
 }j j }|s|d	urӈj|fi |d }
t|
j}g }|D ]J}j|v rt|}|\}}|j }|j }||d  }| | d| j d|  | }|j|d}j | }j|v s|| 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 |rGt|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 `kwargs` 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 strings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 )rD   )replacer.   .0sample)r;   r   r   
<listcomp>   s    z*Emu3Processor.__call__.<locals>.<listcomp>c                    s   g | ]}j  |   qS r   )r7   rF   image_promptr;   r   r   rI      s    image_sizesreturn_tensorsr$   image)
modalities	input_idsmm_token_type_ids)datatensor_type) 
isinstancer   list	TypeError_merge_kwargsr!   r(   init_kwargspop
ValueErrorr1   r6   r3   r'   iterrL   r.   nextr8   r5   rE   r7   appendcalculate_generate_sizelen_check_special_mm_tokensnparray
zeros_liker/   tolistr   )r;   r?   r@   audiovideosr<   output_kwargsr   r   r   image_featuresimage_start_tokensimage_end_tokensrL   prompt_stringsrH   
image_sizeheightwidthimage_seq_lengthimage_placeholderrM   r$   text_inputs	array_idsrQ   r   rJ   r   __call__^   sj   
*



$

zEmu3Processor.__call__c           	      K   s   i }|durCg }|D ])\}}t ||| jj| jj| jj\}}|| j }|| j }||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.
        Nr   )num_image_tokensnum_image_patchesr   )
r   r'   spatial_factor
min_pixels
max_pixelsr8   r]   r_   updater   )	r;   rL   r<   vision_datart   rm   rn   ro   ru   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)
r;   r   r   rv   rn   rm   current_areatarget_ratiotoken_heighttoken_widthr   r   r   r^      s   z%Emu3Processor.calculate_generate_sizec                 K   s   | j j|fi |S N)r'   postprocess)r;   r?   r<   r   r   r   r      s   zEmu3Processor.postprocessr   )NNNN)r   r   r   __doc__
attributestokenizer_classimage_processor_classr:   r   r   r   r   r   rU   r   r!   r   rs   r{   r^   r   __classcell__r   r   r=   r   r&   8   s.    

k"	r&   )typingr   r   numpyra   image_processing_utilsr   image_utilsr   processing_utilsr   r   r	   r
   r   r   tokenization_utils_baser   r   utilsr   image_processing_emu3r   r   r   r!   r&   __all__r   r   r   r   <module>   s     
A