o
    wi)                     @   s   d Z 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 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 )z 
Processor class for Chameleon.
    )OptionalUnionN   )BatchFeature)
ImageInput)MultiModalDataProcessingKwargsProcessorMixin
TextKwargsUnpack!_validate_images_text_input_order)PreTokenizedInput	TextInputc                   @   s   e Zd ZU eed< dS )ChameleonTextKwargsreturn_for_text_completionN)__name__
__module____qualname__bool__annotations__ r   r   o/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/chameleon/processing_chameleon.pyr   $   s   
 r   F)totalc                   @   s,   e Zd ZU eed< ddddddidZdS )ChameleonProcessorKwargstext_kwargsF)paddingr   return_mm_token_type_idsreturn_tensorspt)r   common_kwargsN)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ded	ef 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d Zedd Z  ZS )ChameleonProcessora/  
    Constructs a Chameleon processor which wraps a Chameleon image processor and a Chameleon tokenizer into a single
    processor.

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

    Args:
        image_processor ([`ChameleonImageProcessor`]):
            The image processor is a required input.
        tokenizer ([`LlamaTokenizerFast`]):
            The tokenizer is a required input.
        image_seq_length (`int`, *optional*, defaults to 1024):
            Sequence length of one image embedding.
        image_token (`str`, *optional*, defaults to `"<image>"`):
            The special token used to indicate image in the text.
    image_processor	tokenizer)LlamaTokenizerLlamaTokenizerFastChameleonImageProcessor   <image>image_seq_lengthimage_tokenc                    s   || _ t|dr|jn|| _|| j| _t|dr|jnd| _t|dr(|jnd| _|| j| _|| j| _	|| j| _
| j| j	| j
g| _t || d S )Nr*   	boi_tokenz<racm3:break>	eoi_tokenz<eoss>)r)   hasattrr*   convert_tokens_to_idsimage_token_idr+   image_start_tokenr,   image_end_tokenimage_start_token_idimage_end_token_id	image_idssuper__init__)selfr"   r#   r)   r*   	__class__r   r   r6   M   s   zChameleonProcessor.__init__Nimagestextkwargsreturnc                 K   s  t ||\}}t|tr|g}nt|ts t|d ts td|du r,|du r,td| jtfd| jj	i|}|d 
dd}g }| j| j| j  | j }	|D ]}
|
| j|	}
|sb|
| jj7 }
||
 qQi }|dury| j|fi |d	 }|d 
d
d}|d 
dd}| j|fi |d d
di}| j||dgd |rt|d }t|d }d|t|| j< | |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`.
        r   zAInvalid input text. Please provide a string, or a list of stringsNz&You must provide either text or imagestokenizer_init_kwargsr   r   Fimages_kwargsr   r   image)
modalities	input_ids   mm_token_type_ids)datatensor_type)r   
isinstancestrlist	TypeError
ValueError_merge_kwargsr   r#   init_kwargspopr0   r*   r)   r1   replace	sep_tokenappendr"   _check_special_mm_tokensnparray
zeros_likeisinr4   tolistr   )r7   r:   r;   audiovideosr<   output_kwargsr   prompt_stringsone_img_tokenssampleimage_inputsr   r   text_inputs	array_idsrD   r   r   r   __call__\   sF   )
zChameleonProcessor.__call__c                 K   sL   i }|dur| j d gt| }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.
        N   rC   )num_image_tokensnum_image_patchesr   )r)   lenupdater   )r7   image_sizesr<   vision_datarc   rd   r   r   r   _get_num_multimodal_tokens   s   z-ChameleonProcessor._get_num_multimodal_tokensc                 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   argsr<   r   r   r   rk         zChameleonProcessor.batch_decodec                 O   rj   )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r#   decoderl   r   r   r   ro      rn   zChameleonProcessor.decodec                 C   s"   | j j}| jj}tt|| S N)r#   model_input_namesr"   rI   dictfromkeys)r7   tokenizer_input_namesimage_processor_input_namesr   r   r   rq      s   z$ChameleonProcessor.model_input_names)r'   r(   )NNNNrp   )r   r   r   __doc__
attributestokenizer_classimage_processor_classintrH   r6   r   r   r   r   r   rI   r   r   r   ra   ri   rk   ro   propertyrq   __classcell__r   r   r8   r   r!   6   s0    

Rr!   )rv   typingr   r   numpyrS   feature_extraction_utilsr   image_utilsr   processing_utilsr   r   r	   r
   r   r   tokenization_utils_baser   r   r   r   r!   __all__r   r   r   r   <module>   s     
(