
    h                         d dl mZ ddlmZ ddlmZ ddl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 G d de      ZdgZy)    )Union   )BatchFeature)
ImageInput)ProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)loggingc                       e Zd Zddii dZy)Ovis2ProcessorKwargspaddingF)text_kwargsimage_kwargsN)__name__
__module____qualname__	_defaults     h/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/transformers/models/ovis2/processing_ovis2.pyr   r      s     u
 	Ir   r   F)totalc            
            e Zd ZdZddgZdZdZ	 	 	 	 	 d fd	Z	 	 ddede	e
eee
   ee   f   d	ee   d
efdZdee
   deee      fdZd Zd Zed        Z xZS )Ovis2Processora  
    Constructs a Ovis2 processor which wraps Ovis2 image processor and a Qwen2 tokenizer into a single processor.

    [`Ovis2Processor`] offers all the functionalities of [`Ovis2VideoProcessor`], [`Ovis2ImageProcessor`] and [`Qwen2TokenizerFast`]. See the
    [`~Ovis2Processor.__call__`] and [`~Ovis2Processor.decode`] for more information.

    Args:
        image_processor ([`Ovis2ImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`Qwen2TokenizerFast`], *optional*):
            The tokenizer is a required input.
        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 `"<image>"`):
            Special token used to denote image location.
        image_seq_length (`int`, *optional*, defaults to 256):
            The number of image tokens to be used for each image in the input.
    image_processor	tokenizerAutoImageProcessorAutoTokenizerc                     || _         t        |d      r|j                  n|| _        t        |dd       r|j                  n|j                  | j                        | _        t        |   ||fd|i| y )Nimage_tokenimage_token_idchat_template)image_seq_lengthhasattrr!   getattrr"   convert_tokens_to_idssuper__init__)selfr   r   r#   r!   r$   kwargs	__class__s          r   r)   zOvis2Processor.__init__=   sy     !14;I}4U900[f y"2D9 $$001A1AB 	
 	)[=[TZ[r   imagestextr+   returnc                     | j                   t        fd| j                  j                  i|}t	        |t
              r|g}n.t	        |t              st	        |d   t
              st        d      i }|G | j                  |fi |d   }|j                  d      j                         }| j                  ||      } | j                  |fi |d   }t        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 Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        Ovis2ImageProcessor's [`~Ovis2ImageProcessor.__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).

        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`.
            - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
        tokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringsimages_kwargsgridsr   )data)_merge_kwargsr   r   init_kwargs
isinstancestrlist
ValueErrorr   poptolist_expand_image_tokensr   )r*   r-   r.   r+   output_kwargsimage_inputsimage_gridstext_inputss           r   __call__zOvis2Processor.__call__O   s    B +** 
"&.."<"<
 
 dC 6DD$'
47C0H`aa/4//Y-:XYL&**73::<K,,T;?D$dnnTJ]=-IJ!@K!@<!@AAr   r3   c                 |   g }d}|D ]  }d|v r||   }|d   |d   }}dd| j                   z   d}	||z  dkD  rOt        |      D ]A  }
t        |      D ]#  }|	d| j                   z   z  }	||dz
  k  s|	dz  }	% |
|dz
  k  s=|	dz  }	C |	d	z  }	|j                  d|	d      }|dz  }d|v r|j                  |        |S )
Nr   <image>   z<IMG_START>z
<IMG_ATOM>z
<IMG_GRID>z	<IMG_COL>z	<IMG_ROW>z	<IMG_END>)r$   rangereplaceappend)r*   r.   r3   processed_text
grid_indexsamplegridrowcolplaceholderrcs               r   r=   z#Ovis2Processor._expand_image_tokens   s   
 
 	*Fv%Z(7DGS +L4;P;P,P+QQ[\9q="3Z 7!&s ;A'lT=R=R.R-STK 37{ +{ :; sQw;';6K7 {*	;Ba
 v%  !!&)#	*$ r   c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r   batch_decoder*   argsr+   s      r   rS   zOvis2Processor.batch_decode   s     
 +t~~**D;F;;r   c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r   decoderT   s      r   rW   zOvis2Processor.decode   s     
 %t~~$$d5f55r   c                     | j                   j                  }| j                  j                  }t        |      t        |      z   S )N)r   model_input_namesr   r9   )r*   tokenizer_input_namesimage_processor_input_namess      r   rY   z Ovis2Processor.model_input_names   s;     $ @ @&*&:&:&L&L#)*T2M-NNNr   )NNNrD      )NN)r   r   r   __doc__
attributesimage_processor_classtokenizer_classr)   r   r   r   r
   r9   r	   r   r   rB   intr=   rS   rW   propertyrY   __classcell__)r,   s   @r   r   r   %   s    & $[1J0%O \( "^b4B4B I0$y/4HYCZZ[4B -.	4B
 
4Bl9o DI6<6 O Or   r   N)typingr   feature_extraction_utilsr   image_utilsr   processing_utilsr   r   r	   tokenization_utils_baser
   r   utilsr   
get_loggerr   loggerr   r   __all__r   r   r   <module>rm      sZ      4 % H H C  
		H	%+5 MO^ MO` 
r   