o
    eia7                     @   s   d dl 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 ddlmZ G dd ded	d
ZdZeG dd deZdgZdS )    )ProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput   )BatchFeature)
ImageInputmake_flat_list_of_images)auto_docstringc                   @   s   e Zd ZdddiiZdS )Llama4ProcessorKwargstext_kwargspadding_sideleftN)__name__
__module____qualname__	_defaults r   r   j/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/llama4/processing_llama4.pyr      s
    r   F)totala>  {{- 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                       s   e Zd Zddddddddddd	efd
edef fddZdd Ze		dde	dB de
eB ee
 B ee B dB dee defddZ  ZS )Llama4ProcessorN   g      ?	<|image|><|image_start|><|image_end|>	<|patch|><|tile_x_separator|><|tile_y_separator|>
patch_sizepixel_shuffle_ratioc                    sj   t  j|||d ttd|d  | _|| _|| _|| _|| j| _	|| _
|| _|	| _|
| _|| _dS )a~  
        patch_size (`int`, *optional*, defaults to 28):
            The size of image patches for tokenization.
        pixel_shuffle_ratio (`float`, *optional*, defaults to `0.5`):
            The ratio used for pixel shuffling when processing images. This controls the downsampling factor
            applied to image patches. The actual downsampling ratio is calculated as `1 / (pixel_shuffle_ratio^2)`.
        fake_image_token (`str`, *optional*, defaults to `"<|image|>"`):
            The placeholder token in the text that will be replaced with actual image tokens. This token serves
            as a marker indicating where images should be inserted in the text sequence.
        image_token (`str`, *optional*, defaults to `"<|image|>"`):
            The token to be used to represent an image in the text.
        start_of_image_token (`str`, *optional*, defaults to `"<|image_start|>"`):
            The special token that marks the beginning of an image sequence in the text. This token is prepended
            to image token sequences to delimit image boundaries.
        end_of_image_token (`str`, *optional*, defaults to `"<|image_end|>"`):
            The special token that marks the end of an image sequence in the text. This token is appended to
            image token sequences to delimit image boundaries.
        patch_token (`str`, *optional*, defaults to `"<|patch|>"`):
            The token used to represent individual image patches. Multiple patch tokens are used to represent
            the full image, with the number depending on the image size and patch configuration.
        tile_x_separator_token (`str`, *optional*, defaults to `"<|tile_x_separator|>"`):
            The token used to separate tiles (patches) horizontally within an image. This token is inserted
            between patches in the same row when images are split into multiple tiles.
        tile_y_separator_token (`str`, *optional*, defaults to `"<|tile_y_separator|>"`):
            The token used to separate tiles (patches) vertically within an image. This token is inserted
            between rows of patches when images are split into multiple tiles.
        )chat_templateg      ?   N)super__init__introunddownsample_ratior   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)selfimage_processor	tokenizerr   r    r(   r)   start_of_image_tokenend_of_image_tokenpatch_tokentile_x_separator_tokentile_y_separator_tokenr!   kwargs	__class__r   r   r$   %   s   +
zLlama4Processor.__init__c                 C   s|   d}|\}}|| dkr.t |D ]}t |D ]}|d| 7 }||d k r(|d7 }q|d7 }q|d7 }|d| 7 }|d7 }|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   r   r   r   )range)r1   aspect_rationum_patches_per_chunk
img_stringratio_hratio_wyyxxr   r   r   _prompt_split_image^   s   

z#Llama4Processor._prompt_split_imageimagestextr9   returnc                    s  |du rt d jtfd jji|}t|ttfs|g}i }|dur҈ j	|}t
|} jdd|i|d }|d d jdd \}}t| j | j   j }|d	}	t fd
d|D }
|
t|krzt d|
 dt| dd}g }|D ]E}| j}|dkr|| q| j}g }t|D ]\}}|| ||k r |	| |}|d7 }|| q|d| q|t|krt d|}|d dd} j|fi |d } j||dgd ti |||dS )aA  
        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_kwargsrF   images_kwargspixel_valuesr   aspect_ratiosc                 3   s    | ]	}|  jV  qd S )N)countr(   ).0promptr1   r   r   	<genexpr>   s    z+Llama4Processor.__call__.<locals>.<genexpr>zFound z) placeholders across the batch, but have z flattened images.r<    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   r3   init_kwargs
isinstancelisttupler2   fetch_imagesr
   shaper%   r   r'   popsumlenrN   r(   appendsplit	enumeraterE   join_check_special_mm_tokensr   )r1   rF   rG   r9   output_kwargsimage_inputsimage_heightimage_widthr?   rM   total_placeholdersimage_indexprocessed_textrP   placeholder_countprompt_splits
new_promptlocal_image_index
split_parttokens_for_this_imagerT   text_inputsr   rQ   r   __call__y   sl   



zLlama4Processor.__call__)NN)r   r   r   r!   r%   floatr$   rE   r   r	   r   r   r]   r   r   r   rw   __classcell__r   r   r:   r   r   #   s>    9r   N)transformers.processing_utilsr   r   r   $transformers.tokenization_utils_baser   r   image_processing_utilsr   image_utilsr	   r
   utilsr   r   r!   r   __all__r   r   r   r   <module>   s    
&