o
    Zh)                     @   s   d dl mZmZmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZ ddlmZ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 )    )ListOptionalUnion   )BatchFeature)
ImageInput)ImagesKwargsProcessingKwargsProcessorMixin
TextKwargsUnpack)PreTokenizedInput	TextInputc                   @   s   e Zd ZU eed< dS )Emu3TextKwargsreturn_for_image_generationN)__name__
__module____qualname__bool__annotations__ r   r   W/var/www/auris/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                   @   s2   e Zd ZU eed< eed< ddiddddZd	S )
Emu3ProcessorKwargstext_kwargsimages_kwargsr   Fz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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 Zd
e
fddZdd Zdd Ze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chat_template)ZGPT2TokenizerZGPT2TokenizerFastZEmu3ImageProcessorNc                    sT   |j | _ |j| _|j| _|j| _|j| _|j| _|j	| _	d| _
t j|||d d S )N   )r%   )image_tokenZ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   r/   F   s   zEmu3Processor.__init__imagestextr1   returnc                    sV  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	}j|fi |d }j||dgd |jdi |
 t||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`   *<placeholder>c                    s   g | ]	}| d  jqS )r9   )replacer'   .0sample)r0   r   r   
<listcomp>   s    z*Emu3Processor.__call__.<locals>.<listcomp>c                    s   g | ]}j  |   qS r   )r,   r;   Zimage_promptr0   r   r   r>      s    image_sizesreturn_tensorsimage)Z
modalities)dataZtensor_typer   )
isinstancer   list	TypeErrorZ_merge_kwargsr   r$   Zinit_kwargspop
ValueErrorr(   r+   r)   r#   iterr@   r'   nextr-   r*   r:   r,   appendcalculate_generate_sizelenZ_check_special_mm_tokensupdater   )r0   r4   r5   ZaudioZvideosr1   Zoutput_kwargsr   r   r   Zimage_featuresZimage_start_tokensZimage_end_tokensr@   Zprompt_stringsr=   Z
image_sizeheightwidthZimage_seq_lengthZimage_placeholderrA   rC   r   r?   r   __call__W   s`   
*



$

zEmu3Processor.__call__c           
      C   sX   t t|d\}}|| }|| d }tt|| | }tt|| | }	||	fS )N:g      ?)mapr   splitround)
r0   r   r   Zspatial_factorrP   rO   Zcurrent_areaZtarget_ratioZtoken_heightZtoken_widthr   r   r   rL      s   z%Emu3Processor.calculate_generate_sizec                 K   s   | j j|fi |S N)r#   postprocess)r0   r4   r1   r   r   r   rW      s   zEmu3Processor.postprocessc                 O      | j j|i |S )z
        This method forwards all its arguments to Emu3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r$   batch_decoder0   argsr1   r   r   r   rY         zEmu3Processor.batch_decodec                 O   rX   )z
        This method forwards all its arguments to Emu3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r$   decoderZ   r   r   r   r]      r\   zEmu3Processor.decodec                 C   s"   | j j}| jj}tt|| S rV   )r$   model_input_namesr#   rE   dictfromkeys)r0   Ztokenizer_input_namesZimage_processor_input_namesr   r   r   r^      s   zEmu3Processor.model_input_namesrV   )NNNN)r   r   r   __doc__
attributesZvalid_kwargsZtokenizer_classZimage_processor_classr/   r   r   r   r   r   r   r   r   r   rQ   rL   rW   rY   r]   propertyr^   __classcell__r   r   r2   r   r"   0   s6    
f	r"   N)typingr   r   r   Zimage_processing_utilsr   Zimage_utilsr   Zprocessing_utilsr   r	   r
   r   r   Ztokenization_utils_baser   r   r   r   r   r"   __all__r   r   r   r   <module>   s    
/