
     `i>                         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 ddlmZmZ  G d ded	
          Z G d ded	
          ZdZ G d de          ZdgZdS )    )OptionalUnion)ImagesKwargsProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput   )BatchFeature)
ImageInputmake_flat_list_of_imagesc                   <    e Zd ZU ee         ed<   ee         ed<   dS )Llama4ImagesKwargsmax_patchesresize_to_max_canvasN)__name__
__module____qualname__r   int__annotations__bool     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/llama4/processing_llama4.pyr   r      s2         #"4.(((((r   r   F)totalc                   &    e Zd ZU eed<   dddiiZdS )Llama4ProcessorKwargsimages_kwargstext_kwargspadding_sideleftN)r   r   r   r   r   	_defaultsr   r   r   r   r      s0         %%%%F
IIIr   r   a>  {{- bos_token }}
{%- if custom_tools is defined %}
    {%- set tools = custom_tools %}
{%- endif %}
{%- if not tools_in_user_message is defined %}
    {%- set tools_in_user_message = true %}
{%- endif %}
{%- if not date_string is defined %}
    {%- if strftime_now is defined %}
        {%- set date_string = strftime_now("%d %b %Y") %}
    {%- else %}
        {%- set date_string = "26 Jul 2024" %}
    {%- endif %}
{%- endif %}
{%- if not tools is defined %}
    {%- set tools = none %}
{%- endif %}

{#- This block extracts the system message, so we can slot it into the right place. #}
{%- if messages[0]['role'] == 'system' %}    
    {%- if messages[0]['content'] is string %}
        {%- set system_message = messages[0]['content']|trim %}
    {%- else %}
        {#- FIXME: The processor requires an array, always. #}
        {%- set system_message = messages[0]['content'][0]['text']|trim %}
    {%- endif %}
    {%- set messages = messages[1:] %}
    {%- set user_supplied_system_message = true %}
{%- else %}
    {%- set system_message = "" %}
    {%- set user_supplied_system_message = false %}
{%- endif %}

{#- System message if the user supplied one #}
{%- if user_supplied_system_message %}
    {{- "<|header_start|>system<|header_end|>

" }}
    {%- if tools is not none %}
        {{- "Environment: ipython
" }}
    {%- endif %}
    {%- if tools is not none and not tools_in_user_message %}
        {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }}
        {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
        {{- "Do not use variables.

" }}
        {%- for t in tools %}
            {{- t | tojson(indent=4) }}
            {{- "

" }}
        {%- endfor %}
    {%- endif %}
    {{- system_message }}
    {{- "<|eot|>" }}
{%- endif %}

{#- Custom tools are passed in a user message with some extra guidance #}
{%- if tools_in_user_message and not tools is none %}
    {#- Extract the first user message so we can plug it in here #}
    {%- if messages | length != 0 %}
        {%- set first_user_message = messages[0]['content']|trim %}
        {%- set messages = messages[1:] %}
    {%- else %}
        {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }}
{%- endif %}
    {{- '<|header_start|>user<|header_end|>

' -}}
    {{- "Given the following functions, please respond with a JSON for a function call " }}
    {{- "with its proper arguments that best answers the given prompt.

" }}
    {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
    {{- "Do not use variables.

" }}
    {%- for t in tools %}
        {{- t | tojson(indent=4) }}
        {{- "

" }}
    {%- endfor %}
    {{- first_user_message + "<|eot|>"}}
{%- endif %}

{%- for message in messages %}
    {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}
    {{- '<|header_start|>' + message['role'] + '<|header_end|>

' }}
        {%- if message['content'] is string %}
            {{- message['content'] }}
        {%- else %}
            {%- for content in message['content'] %}
                {%- if content['type'] == 'image' %}
                    {{- '<|image|>' }}
                {%- elif content['type'] == 'text' %}
                    {{- content['text'] }}
                {%- endif %}
            {%- endfor %}
        {%- endif %}
        {{- "<|eot|>" }}
    {%- elif 'tool_calls' in message and message.tool_calls|length > 0 %}
       {{- '<|header_start|>assistant<|header_end|>

' -}}
       {{- '<|python_start|>' }}
        {%- if message['content'] is string %}
            {{- message['content'] }}
        {%- else %}
            {%- for content in message['content'] %}
                {%- if content['type'] == 'image' %}
                    {{- '<|image|>' }}
                {%- elif content['type'] == 'text' %}
                    {{- content['text'] }}
                {%- endif %}
            {%- endfor %}
        {%- endif %}
       {{- '<|python_end|>' }}
        {%- for tool_call in message.tool_calls %}
           {{- '{"name": "' + tool_call.function.name + '", ' }}
           {{- '"parameters": ' }}
           {{- tool_call.function.arguments | tojson }}
           {{- "}" }}
        {%- endfor %}
       {{- "<|eot|>" }}
    {%- elif message.role == "tool" or message.role == "ipython" %}
        {{- "<|header_start|>ipython<|header_end|>

" }}
        {%- if message.content is mapping or message.content is iterable %}
            {{- message.content | tojson }}
        {%- else %}
            {{- message.content }}
        {%- endif %}
        {{- "<|eot|>" }}
    {%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
    {{- '<|header_start|>assistant<|header_end|>

' }}
{%- endif %}
c                        e Zd ZdZddgZdZdZddddd	d	d
ddddefdede	f fdZ
d Z	 	 	 	 ddee         deeeeee         ee         f                  dee         defdZ xZS )Llama4Processora  
    Constructs a Llama4 processor which wraps a [`AutoImageProcessor`] and
    [`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
    tokenizer functionalities. See the [`~Llama4Processor.__call__`] and [`~Llama4Processor.decode`] for more information.
    Args:
        image_processor ([`AutoImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`], *optional*):
            The tokenizer is a required input.
        patch_size (`int`, *optional*, defaults to 28):
            The size of image patches for tokenization.
        img_size (`int`, *optional*, defaults to 364):
            The size of the image to be tokenized. This should correspond to the size given to the image processor.
        image_token (`str`, *optional*, defaults to `"<|image|>"`):
            The token to be used to represent an image in the text.
        downsample_factor (`int`, *optional*, defaults to 1):
            The factor by which to scale the patch size.
        start_of_img_token (`str`, *optional*, defaults to `"<|START_OF_IMG|>"`):
            The token to be used to represent the start of an image in the text.
        end_of_img_token (`str`, *optional*, defaults to `"<|END_OF_IMG|>"`):
            The token to be used to represent the end of an image in the text.
        img_patch_token (`str`, *optional*, defaults to `"<|IMG_PATCH|>"`):
            The token to be used to represent an image patch in the text.
        img_line_break_token (`str`, *optional*, defaults to `"<|IMG_LINE_BREAK|>"`):
            The token to be used to represent a line break in the text.
        tile_token (`str`, *optional*, defaults to `"TILE"`):
            The token to be used to represent an image patch in the text.
        tile_global_token (`str`, *optional*, defaults to `"TILE_GLOBAL"`):
            The token to be used to represent the cover image in the text.
        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AutoImageProcessorAutoTokenizerN   g      ?	<|image|><|image_start|><|image_end|>	<|patch|><|tile_x_separator|><|tile_y_separator|>
patch_sizepixel_shuffle_ratioc                 L   t                                          |||           t          t          d|dz  z                      | _        || _        || _        || _        |                    | j                  | _	        || _
        || _        |	| _        |
| _        || _        d S )N)chat_templateg      ?   )super__init__r   rounddownsample_ratior1   fake_image_tokenimage_tokenconvert_tokens_to_idsimage_token_idstart_of_img_tokenend_of_img_tokenimg_patch_token
tile_tokentile_global_token)selfr&   r'   r1   r2   r:   r;   start_of_image_tokenend_of_image_tokenpatch_tokentile_x_separator_tokentile_y_separator_tokenr4   kwargs	__class__s                 r   r7   zLlama4Processor.__init__Q   s      	)=QQQ #E#1Da1G*H$I$I J J$ 0&'==d>NOO"6 2*0!7r   c                     d}|\  }}||z  dk    r?t          |          D ]/}t          |          D ]}|d|z  z  }||dz
  k     r|dz  }|dz  }0|dz  }|d|z  z  }|dz  }|S )z
        Create a structured string representation of image tokens

        Args:
           num_patches: Number of patches in the image

        Returns:
            String with appropriate image tokens
        r,      r.   r/   r0   r+   r-   )range)rC   aspect_rationum_patches_per_chunk
img_stringratio_hratio_wyyxxs           r   _prompt_split_imagez#Llama4Processor._prompt_split_imageo   s     '
'Wq  Gnn 5 5.. = =B+0E"EEJGaK''"&<<
44

k!
k$999
o%
r   imagestextrI   returnc                 Z    |t          d            j        t          fd j        j        i|}t          |t          t          f          s|g}i }| j        	                    |          }t          |          }  j        dd|i|d         }|d         d         j        dd         \  }}	t          | j        z  |	 j        z  z   j        z            }
|                    d	          }t!           fd
|D                       }|t#          |          k    r#t          d| dt#          |           d          d}g }|D ]}|                     j                  }|dk    r|                    |           8|                     j                  }g }t-          |          D ]V\  }}|                    |           ||k     r6                     ||         |
          }|dz  }|                    |           W|                    d                    |                     |t#          |          k    rt          d          |}|d                             dd          }  j        |fi |d         }                     ||dg           t5          i |||          S )au  
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text.
        To prepare the vision inputs, this method forwards the `images` and `kwargs` arguments to
        Llama4ImageProcessor's [`~Llama4ImageProcessor.__call__`] if `images` is not `None`.

        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`.
        NzYou have to specify text.tokenizer_init_kwargsrV   r   pixel_valuesr   aspect_ratiosc              3   L   K   | ]}|                     j                  V  d S )N)countr:   ).0promptrC   s     r   	<genexpr>z+Llama4Processor.__call__.<locals>.<genexpr>   s2      $\$\VV\\$2G%H%H$\$\$\$\$\$\r   zFound z) placeholders across the batch, but have z flattened images.rL    zONumber of image placeholders in the prompt does not match the number of images.r    return_tensorsimage)
modalities)datatensor_typer   )
ValueError_merge_kwargsr   r'   init_kwargs
isinstancelisttupler&   fetch_imagesr   shaper   r1   r9   popsumlenr_   r:   appendsplit	enumeraterU   join_check_special_mm_tokensr   )rC   rV   rW   audiovideosrI   output_kwargsimage_inputsimage_heightimage_widthrO   r]   total_placeholdersimage_indexprocessed_textra   placeholder_countprompt_splits
new_promptlocal_image_index
split_parttokens_for_this_imagerd   text_inputss   `                       r   __call__zLlama4Processor.__call__   sB   L <8999**!
 
"&."<
 
 
 $u.. 	6D )66v>>F-f55F/4/``v`A_``L(4^(DQ(G(Mbcc(R%L+$'0[DO5STX\Xmm% %! ),,_==M!$$\$\$\$\W[$\$\$\!\!\!S[[00 @/ @ @ #F@ @ @  
 KN ; ;$*LL1F$G$G!$))"))&111 &T-B C C
5>}5M5M A A1%z%%j111(+<<<040H0H)+68M1 1- $q("))*?@@@%%bggj&9&9::::c&kk)) !rsss!D&}599:JDQQ$dnTJJ]=-IJJ%%dKWI%NNN!@K!@<!@n]]]]r   )NNNN)r   r   r   __doc__
attributesimage_processor_classtokenizer_classr4   r   floatr7   rU   r   r   r   r
   r	   rm   r   r   r   r   __classcell__)rJ   s   @r   r%   r%   +   s=        B $[1J0%O %($.*55#8 8 	8
 #8 8 8 8 8 8<  : (,hlb^ b^$b^ uY(94	?DQbLccdeb^ ./b^ 
b^ b^ b^ b^ b^ b^ b^ b^r   r%   N)typingr   r   transformers.processing_utilsr   r   r   r   $transformers.tokenization_utils_baser	   r
   image_processing_utilsr   image_utilsr   r   r   r   r4   r%   __all__r   r   r   <module>r      s:  " # " " " " " " " ` ` ` ` ` ` ` ` ` ` ` ` M M M M M M M M 2 2 2 2 2 2 ? ? ? ? ? ? ? ?) ) ) ) )U ) ) ) )
    ,E     ]PA^ A^ A^ A^ A^n A^ A^ A^H 
r   