
    %	&h+                         d Z ddlmZmZ ddlmZ 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  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y)z
Processor class for Pixtral.
    )ListUnion   )BatchFeature)
ImageInputis_valid_image
load_image)ProcessingKwargsProcessorMixinUnpack!_validate_images_text_input_order)PreTokenizedInput	TextInput)loggingc                        e Zd Zddii ddidZy)PixtralProcessorKwargspaddingFreturn_tensorspt)text_kwargsimages_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults     /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/pixtral/processing_pixtral.pyr   r      s$     u
 d
Ir   r   F)totalreturnc                 H    t        | t              xr | j                  d      S )Nhttp)
isinstancestr
startswith)vals    r   is_urlr(   ,   s    c3:CNN6$::r   c                 2    t        |       xs t        |       S N)r(   r   )elems    r   is_image_or_image_urlr,   1   s    $</>$//r   c            
            e Zd ZdZddgZg dZdZdZ	 	 	 	 	 	 	 	 ddedef fd	Z		 	 	 	 dd
e
d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 )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)chat_template
patch_sizespatial_merge_sizeimage_tokenimage_break_tokenimage_end_tokenAutoImageProcessorAutoTokenizerr2   r3   c	                 p    || _         || _        || _        || _        || _        t
        
|   |||       y )N)r1   )r2   r3   r4   r5   r6   super__init__)selfr/   r0   r2   r3   r1   r4   r5   r6   kwargs	__class__s             r   r;   zPixtralProcessor.__init__[   s@     %"4&!2.)=Qr   imagestextr=   r!   c                    t        ||      \  }} | j                  t        fd| j                  j                  i|}| j
                  | j                  z  }|t        |      r|g}nt        |t        t        f      rt        |d         rndt        |t        t        f      rCt        |d   t        t        f      r*t        |d   d         r|D 	cg c]  }|D ]  }	|	  }}}	nt        d      |D 
cg c]  }
t        |
t              rt        |
      n|
! }}
 | j                  |fd|i|d   }ni }t        |t              r|g}n.t        |t              st        |d   t              st        d      |}|j                  d      t!        |d         }g }g }|D ]  }| j"                  |v rt%        |      \  }}||z  }||z  }| j"                  g|z  | j&                  gz   g|z  }|D cg c]  }|D ]  }|  }}}| j(                  |d	<   d
j+                  |      }|j-                  |       |j/                  | j"                  dd      }| j"                  |v rd|v r)|j1                  d      }|j/                  d|d      }d|v r)|j-                  |         | j                  |fi |d   }t3        i |||d   d         S c c}	}w c c}
w c c}}w )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`.
        tokenizer_init_kwargsr   zdInvalid input images. Please provide a single image, a list of images, or a list of lists of images.r2   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesimage_sizes z<placeholder>   r   r   r   )datatensor_type)r   _merge_kwargsr   r0   init_kwargsr2   r3   r,   r$   listtuple
ValueErrorr%   r	   r/   getiterr4   nextr5   r6   joinappendreplacepopr   )r<   r?   r@   audiovideosr=   output_kwargsr2   sublistimageimimage_inputsprompt_stringsrD   replace_stringssampleheightwidthnum_height_tokensnum_width_tokensreplace_tokensitemreplace_strtext_inputss                           r   __call__zPixtralProcessor.__call__n   s'   R 9F***"
"&.."<"<
 
 __t'>'>>
$V, FT5M27LVTUY7W6D%=1vay4-8)&)A,7/5KG7K%%K%KK z  OUU
2s(;jnCUFU/4//p:pQ^_nQopLLdC 6DD$'
47C0H`aa N+7|M:;KN O .&&&0$($5MFE(.*(<%',
':$))*-==AWAW@XX&)&*N ;I%]wU\%]Td%]d%]N%])-)=)=N2&"$''."9K#**;7#^^D,<,<oqQF &&&0 &/"1"5"5a"8K#^^O[!LF &/ %%f-%.( %dnn^T}]7ST0K0<0mO>\]m>n
 	
Y L
 V6 &^s   K4$K/Kc                 :     | 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.
        )r0   batch_decoder<   argsr=   s      r   rj   zPixtralProcessor.batch_decode   s     
 +t~~**D;F;;r   c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r0   decoderk   s      r   rn   zPixtralProcessor.decode   s     
 %t~~$$d5f55r   c                     | j                   j                  }| j                  j                  }t        t        j                  ||z               S r*   )r0   model_input_namesr/   rL   dictfromkeys)r<   tokenizer_input_namesimage_processor_input_namess      r   rp   z"PixtralProcessor.model_input_names   sA     !% @ @&*&:&:&L&L#DMM"7:U"UVWWr   )NN   rG   Nz[IMG]z[IMG_BREAK]z	[IMG_END])NNNN)r   r   r   __doc__
attributesvalid_kwargsimage_processor_classtokenizer_classintr;   r   r   r   r   r   r   r   r   rh   rj   rn   propertyrp   __classcell__)r>   s   @r   r.   r.   5   s    2 $[1JL 1%O "#'#R 	R
  R* "^bk
k
 I0$y/4HYCZZ[k
 /0k
 
k
\<6 X Xr   r.   N)rv   typingr   r   feature_extraction_utilsr   image_utilsr   r   r	   processing_utilsr
   r   r   r   tokenization_utils_baser   r   utilsr   
get_loggerr   loggerr   boolr(   r,   r.   __all__r   r   r   <module>r      ss     4 A A k k C  
		H	%	-U 	;4 ;
0{X~ {X| 
r   