Ë
    T^(h€B  ã                   ó°   — d dl mZ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y)é    )ÚListÚ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<   y)ÚLlama4ImagesKwargsÚmax_patchesÚresize_to_max_canvasN)Ú__name__Ú
__module__Ú__qualname__r   ÚintÚ__annotations__Úbool© ó    új/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/llama4/processing_llama4.pyr   r   "   s   … Ø˜#‘ÓØ" 4™.Ô(r   r   F)Útotalc                   ó$   — e Zd ZU eed<   dddiiZy)ÚLlama4ProcessorKwargsÚimages_kwargsÚtext_kwargsÚpadding_sideÚleftN)r   r   r   r   r   Ú	_defaultsr   r   r   r   r   '   s   … Ø%Ó%àØ˜Fð
ð�Ir   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g d¢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d„ Zd„ Ze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)Úchat_templateÚimage_tokenÚ
patch_sizeÚimg_sizeÚdownsample_factorÚstart_of_img_tokenÚend_of_img_tokenÚimg_patch_tokenÚimg_line_break_tokenÚ
tile_tokenÚtile_global_tokenÚAutoImageProcessorÚAutoTokenizerNé   g      à?ú	<|image|>ú<|image_start|>ú<|image_end|>ú	<|patch|>ú<|tile_x_separator|>ú<|tile_y_separator|>r+   Úpixel_shuffle_ratioc                 óØ   •— t         ‰| �  |||¬«       t        t        d|dz  z  «      «      | _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        y )N)r)   g      ð?é   )ÚsuperÚ__init__r   ÚroundÚdownsample_ratior+   Úfake_image_tokenr*   r.   r/   r0   r2   r3   )Úselfr'   r(   r+   r=   rD   r*   Ústart_of_image_tokenÚend_of_image_tokenÚpatch_tokenÚtile_x_separator_tokenÚtile_y_separator_tokenr)   ÚkwargsÚ	__class__s                 €r   rA   zLlama4Processor.__init__f   st   ø€ ô  	‰Ñ˜¨)À=ÐÔQä #¤E¨#Ð1DÀaÑ1GÑ*HÓ$IÓ JˆÔØ$ˆŒà 0ˆÔØ&ˆÔØ"6ˆÔØ 2ˆÔØ*ˆÔØ0ˆŒØ!7ˆÕr   c                 ó¾   — d}|\  }}||z  dkD  r;t        |«      D ]-  }t        |«      D ]  }|d|z  z  }||dz
  k  sŒ|dz  }Œ |dz  }Œ/ |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
        r8   é   r:   r;   r<   r7   r9   )Úrange)rE   Úaspect_ratioÚnum_patches_per_chunkÚ
img_stringÚratio_hÚratio_wÚyyÚxxs           r   Ú_prompt_split_imagez#Llama4Processor._prompt_split_imageƒ   s¦   € ð 'ˆ
Ø'Ñˆ�Ø�WÑ˜qÒ Ü˜G“nò 5�Ü ›.ò =�BØ +Ð0EÑ"EÑE�JØ˜G a™KÓ'Ø"Ð&<Ñ<™
ð=ð
 Ð4Ñ4‘
ð5ð 	�kÑ!ˆ
Ø�kÐ$9Ñ9Ñ9ˆ
Ø�oÑ%ˆ
àÐr   ÚimagesÚtextrK   Úreturnc                 óN  ‡ — |€t        d«      ‚ ‰ j                  t        fd‰ j                  j                  i|¤Ž}t        |t        t        f«      s|g}i }|��§t        |«      } ‰ j                  dd|i|d   ¤Ž}|d   d   j                  dd \  }}	t        |‰ j                  z  |	‰ j                  z  z  ‰ j                  z  «      }
|j                  d	«      }t        ˆ fd
„|D «       «      }|t!        |«      k7  rt        d|› dt!        |«      › d�«      ‚d}g }|D ]Æ  }|j#                  ‰ j$                  «      }|dk(  r|j'                  |«       Œ5|j)                  ‰ j$                  «      }g }t+        |«      D ]G  \  }}|j'                  |«       ||k  sŒ‰ j-                  ||   |
«      }|dz  }|j'                  |«       ŒI |j'                  dj/                  |«      «       ŒÈ |t!        |«      k7  rt        d«      ‚|} ‰ j                  |fi |d   ¤Ž}t1        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_kwargsrX   r    Úpixel_valuesr   éþÿÿÿÚaspect_ratiosc              3   óT   •K  — | ]  }|j                  ‰j                  «      –— Œ! y ­w©N)ÚcountrD   )Ú.0ÚpromptrE   s     €r   ú	<genexpr>z+Llama4Processor.__call__.<locals>.<genexpr>Ú   s    øè ø€ Ò$\ÈV V§\¡\°$×2GÑ2G×%HÑ$\ùs   ƒ%(zFound z) placeholders across the batch, but have z flattened images.rN   Ú zONumber of image placeholders in the prompt does not match the number of images.r!   )Údatar   )Ú
ValueErrorÚ_merge_kwargsr   r(   Úinit_kwargsÚ
isinstanceÚlistÚtupler   r'   Úshaper   r+   rC   ÚpopÚsumÚlenrb   rD   ÚappendÚsplitÚ	enumeraterW   Újoinr   )rE   rX   rY   ÚaudioÚvideosrK   Úoutput_kwargsÚimage_inputsÚimage_heightÚimage_widthrQ   r_   Útotal_placeholdersÚimage_indexÚprocessed_textrd   Úplaceholder_countÚprompt_splitsÚ
new_promptÚlocal_image_indexÚ
split_partÚtokens_for_this_imageÚtext_inputss   `                      r   Ú__call__zLlama4Processor.__call__�   sx  ø€ ðL ˆ<ÜÐ8Ó9Ð9à*˜×*Ñ*Ü!ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆô ˜$¤¤u Ô.Ø�6ˆDð ˆØÑÜ-¨fÓ5ˆFØ/˜4×/Ñ/Ñ`°vÐ`ÀÈÑA_Ñ`ˆLØ(4°^Ñ(DÀQÑ(G×(MÑ(MÈbÈcÐ(RÑ%ˆL˜+Ü$'Ø §¡Ñ0°[ÀDÇOÁOÑ5SÑTÐX\×XmÑXmÑmó%Ð!ð )×,Ñ,¨_Ó=ˆMä!$Ó$\ÐW[Ô$\Ó!\ÐØ!¤S¨£[Ò0Ü ØÐ/Ð0ð 1 Ü # F£˜}Ð,>ð@óð ð
 ˆKØˆNØò ;�Ø$*§L¡L°×1FÑ1FÓ$GÐ!Ø$¨Ò)à"×)Ñ)¨&Ô1ØØ &§¡¨T×-BÑ-BÓ C�Ø�
Ü5>¸}Ó5Mò AÑ1Ð% zØ×%Ñ% jÔ1Ø(Ð+<Ó<Ø04×0HÑ0HØ)¨+Ñ6Ð8Mó1Ð-ð $ qÑ(˜Ø"×)Ñ)Ð*?Õ@ðAð ×%Ñ% b§g¡g¨jÓ&9Õ:ð!;ð$ œc &›kÒ)Ü Ð!rÓsÐsà!ˆDà$�d—n‘n TÑJ¨]¸=Ñ-IÑJˆäÐ!@ KÐ!@°<Ð!@ÔAÐAr   c                 ó:   —  | j                   j                  |i |¤ŽS )zÇ
        This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r(   Úbatch_decode©rE   ÚargsrK   s      r   rˆ   zLlama4Processor.batch_decodeþ   s    € ð
 +ˆt�~‰~×*Ñ*¨DÐ;°FÑ;Ð;r   c                 ó:   —  | j                   j                  |i |¤ŽS )zÁ
        This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r(   Údecoder‰   s      r   rŒ   zLlama4Processor.decode  s    € ð
 %ˆt�~‰~×$Ñ$ dÐ5¨fÑ5Ð5r   c                 óˆ   — | j                   j                  }| j                  j                  }t        |«      t        |«      z   S ra   )r(   Úmodel_input_namesr'   rl   )rE   Útokenizer_input_namesÚimage_processor_input_namess      r   rŽ   z!Llama4Processor.model_input_names  s;   € à $§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#ÜÐ)Ó*¬TÐ2MÓ-NÑNÐNr   )NNNN)r   r   r   Ú__doc__Ú
attributesÚvalid_kwargsÚimage_processor_classÚtokenizer_classr)   r   ÚfloatrA   rW   r   r   r   r   r
   r   r	   r   r   r†   rˆ   rŒ   ÚpropertyrŽ   Ú__classcell__)rL   s   @r   r&   r&   3   sú   ø„ ñðB $ [Ð1€Jò€Lð 1ÐØ%€Oð ØØØ%(Ø$ØØ.Ø*ØØ5Ø5Ø#ñ8ð ð	8ð
 #õ8ò:ð8 (,ØhlØØñ_Bà˜Ñ$ð_Bð �u˜YÐ(9¸4À	¹?ÈDÐQbÑLcÐcÑdÑeð_Bð Ð.Ñ/ð_Bð 
ó_BòB<ò6ð ñOó ôOr   r&   N)Útypingr   r   r   Útransformers.processing_utilsr   r   r   r	   Ú$transformers.tokenization_utils_baser
   r   Úimage_processing_utilsr   Úimage_utilsr   r   r   r   r)   r&   Ú__all__r   r   r   ú<module>rŸ      sf   ð÷" )Ñ (÷ó ÷ Nå 2÷ô)˜¨Uõ )ô
Ð,°Eõ ð ]P€ô]O�nô ]Oð@ Ð
�r   