
     `ix.                     
   d Z ddlmZmZ ddlZddlmZ ddl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mZ  e            rd
dlmZ  ej        e          Z G d ded          ZdefdZd Z G d de          ZdgZ dS )z
Processor class for Pixtral.
    )OptionalUnionN   )BatchFeature)
ImageInputis_valid_image)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)is_vision_availablelogging   )get_resize_output_image_sizec                   $    e Zd Zdddi ddidZdS )PixtralProcessorKwargsF)paddingreturn_mm_token_type_idsreturn_tensorspt)text_kwargsimages_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/pixtral/processing_pixtral.pyr   r   *   s;         (-
 
 d
	 	IIIr!   r   F)totalreturnc                 V    t          | t                    o|                     d          S )Nhttp)
isinstancestr
startswith)vals    r"   is_urlr+   8   s#    c3:CNN6$:$::r!   c                 >    t          |           pt          |           S N)r+   r   )elems    r"   is_image_or_image_urlr/   =   s    $<</>$///r!   c            
            e Zd ZdZddgZdZdZ	 	 	 	 	 	 	 	 ddedef fdZ	 	 	 	 dde	e
         deeeee         ee         f         dee         defdZddZed             Z x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AutoImageProcessorAutoTokenizerN   r   [IMG][IMG_BREAK]	[IMG_END]
patch_sizespatial_merge_sizec	                    || _         || _        || _        |                    | j                  | _        || _        || _        |                    | j                  | _        |                    | j                  | _        |                    | j                  | _        | j        | j        | j        g| _	        t                                          |||           d S )N)chat_template)r:   r;   image_tokenconvert_tokens_to_idsimage_token_idimage_break_tokenimage_end_tokenimage_break_token_idimage_end_token_id	image_idssuper__init__)selfr2   r3   r:   r;   r=   r>   rA   rB   kwargs	__class__s             r"   rG   zPixtralProcessor.__init___   s     %"4&'==d>NOO!2.'==d>NOO$-$C$CDDZ$[$[!"+"A"A$BV"W"W-t/H$Jab)=QQQQQr!   imagestextrI   r$   c                 V    | j         t          fd| j        j        i|}| j        | j        z  }| | j        |fd|i|d         }ni }t          |t                    r|g}n?t          |t                    s*t          |d         t                    st          d          |}	|                    d          	t          |d                   }
g }	g }|D ]}| j        |v rt          |
          \  }}||z  }||z  }| j        g|z  | j        gz   g|z  }d	 |D             }| j        |d
<   d                    |          }|                    |           |                    | j        dd          }| j        |v d|v r0|                    d          }|                    d|d          }d|v 0|	                    |           |d                             dd          }|d                             dd          } | j        |	fi |d         ddi}|                     |	|dg           |rht-          j        |d                   }t-          j        |d                   }d|t-          j        || j                  <   |                                |d<   t9          i |||          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 `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`.
        tokenizer_init_kwargsNr:   r   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesimage_sizesc                     g | ]	}|D ]}|
S r    r    ).0sublistitems      r"   
<listcomp>z-PixtralProcessor.__call__.<locals>.<listcomp>   s&    %]%]%]wU\%]%]Td%]%]%]%]r!    z<placeholder>r   r   r   r   Fimage)
modalities	input_idsmm_token_type_ids)datatensor_type)_merge_kwargsr   r3   init_kwargsr:   r;   r2   r'   r(   list	TypeErrorgetiterr>   nextrA   rB   joinappendreplacepop_check_special_mm_tokensnparray
zeros_likeisinrE   tolistr   )rH   rK   rL   audiovideosrI   output_kwargsr:   image_inputsprompt_stringsrP   replace_stringssampleheightwidthnum_height_tokensnum_width_tokensreplace_tokensreplace_strr   r   text_inputs	array_idsr[   s                           r"   __call__zPixtralProcessor.__call__w   s>   R +*"
 
"&."<
 
 
 _t'>>
/4/pp:pQ^_nQoppLLLdC   	a6DDD$'' 	a
47C0H0H 	a_``` N++7|M:;;KN O . .&&00$($5$5MFE(.*(<%',
':$)*-==AW@XX&)&*N &^%].%]%]%]N)-)=N2&"$''."9"9K#**;777#^^D,<oqQQF &&00 &//"1"5"5a"8"8K#^^O[!LLF &// %%f----&}599:JDQQ#0#?#C#CD^`e#f#f $dn^ii}]7Siidhiii%%nkwi%XXX# 	J[!9::I "k+.F G GDEbgi@@A/@/G/G/I/IK+,!@K!@<!@n]]]]r!   c                    i }|t           j                            di           }|                    |           |                    dd          p| j        j        }| j        | j        z  }g }|D ]d\  }}	t          t          j
        ||	df          |d         |d         f||f          \  }
}|
|z  }||z  }|                    |dz   |z             edgt          |          z  }|                    ||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   sizer   longest_edge)r   r:   r   )num_image_tokensnum_image_patchesr    )r   r   rb   updater2   r   r:   r;   r   rj   zerosrf   lenr	   )rH   rP   rI   vision_datar   r   r:   r   rv   rw   resized_heightresized_widthrx   ry   r   s                  r"   _get_num_multimodal_tokensz+PixtralProcessor._get_num_multimodal_tokens   sO    "2<@@RTUUM  ((( $$VT22Od6J6OD4+BBJ!!, T T0LHfeQ/00~.^0DE *J71 1 1-
 %3j$@!#0J#>  '')9A)=AR(RSSSS!"c+&6&6 64D[lmmnnn,,,,,r!   c                 D    | j         j        }| j        j        }||z   dgz   S )NrP   )r3   model_input_namesr2   )rH   tokenizer_input_namesimage_processor_input_namess      r"   r   z"PixtralProcessor.model_input_names   s,     $ @&*&:&L#$'BBm_TTr!   )NNr6   r   Nr7   r8   r9   )NNNNr-   )r   r   r   __doc__
attributesimage_processor_classtokenizer_classintrG   r   r   r   r   r   r`   r   r   r   r~   r   propertyr   __classcell__)rJ   s   @r"   r1   r1   A   sU        2 $[1J0%O "#'#R R 	R
  R R R R R R4 (,^bb^ b^$b^ I0$y/4HYCZZ[b^ /0b^ 
b^ b^ b^ b^H"- "- "- "-H U U XU U U U Ur!   r1   )!r   typingr   r   numpyrj   feature_extraction_utilsr   image_utilsr   r   processing_utilsr	   r
   r   r   tokenization_utils_baser   r   utilsr   r   image_processing_pixtralr   
get_loggerr   loggerr   boolr+   r/   r1   __all__r    r!   r"   <module>r      s    # " " " " " " "     4 4 4 4 4 4 5 5 5 5 5 5 5 5            D C C C C C C C 1 1 1 1 1 1 1 1  GFFFFFF 
	H	%	%
 
 
 
 
-U 
 
 
 
;4 ; ; ; ;
0 0 0BU BU BU BU BU~ BU BU BUJ 
r!   