pcuenq/paddle-test-4
020
1# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15from typing import List, Union16import numpy as np17import torch18from transformers.feature_extraction_utils import BatchFeature19from transformers.processing_utils import (20 ProcessingKwargs,21 ProcessorMixin,22 Unpack,23 VideosKwargs,24)25from transformers.tokenization_utils_base import PreTokenizedInput, TextInput26 27 28ImageInput = Union[29 "PIL.Image.Image",30 np.ndarray,31 "torch.Tensor",32 List["PIL.Image.Image"],33 List[np.ndarray],34 List["torch.Tensor"],35] # noqa36 37 38VideoInput = Union[39 List["PIL.Image.Image"],40 "np.ndarray",41 "torch.Tensor",42 List["np.ndarray"],43 List["torch.Tensor"],44 List[List["PIL.Image.Image"]],45 List[List["np.ndarrray"]],46 List[List["torch.Tensor"]],47] # noqa48 49 50class PaddleOCRVLVideosProcessorKwargs(VideosKwargs, total=False):51 fps: Union[List[float], float]52 53 54class PaddleOCRVLProcessorKwargs(ProcessingKwargs, total=False):55 videos_kwargs: PaddleOCRVLVideosProcessorKwargs56 _defaults = {57 "text_kwargs": {58 "padding": False,59 },60 "videos_kwargs": {"fps": 2.0},61 }62 63 64class PaddleOCRVLProcessor(ProcessorMixin):65 r"""66 [`PaddleOCRVLProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`Qwen2TokenizerFast`]. See the67 [`~PaddleOCRVLProcessor.__call__`] and [`~PaddleOCRVLProcessor.decode`] for more information.68 Args:69 image_processor ([`SiglipImageProcessor`], *optional*):70 The image processor is a required input.71 tokenizer ([`Qwen2TokenizerFast`], *optional*):72 The tokenizer is a required input.73 chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages74 in a chat into a tokenizable string.75 """76 77 attributes = ["image_processor", "tokenizer"]78 valid_kwargs = [79 "chat_template",80 "image_std",81 "min_pixels",82 "image_mean",83 "merge_size",84 "image_processor_type",85 "temporal_patch_size",86 "patch_size",87 "max_pixels",88 ]89 90 image_processor_class = "AutoImageProcessor"91 tokenizer_class = "AutoTokenizer"92 93 def __init__(94 self, image_processor=None, tokenizer=None, chat_template=None, **kwargs95 ):96 self.image_token = (97 "<|IMAGE_PLACEHOLDER|>"98 if not hasattr(tokenizer, "image_token")99 else tokenizer.image_token100 )101 self.video_token = (102 "<|video_pad|>"103 if not hasattr(tokenizer, "video_token")104 else tokenizer.video_token105 )106 super().__init__(image_processor, tokenizer, chat_template=chat_template)107 108 def __call__(109 self,110 images: ImageInput = None,111 text: Union[112 TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]113 ] = None,114 videos: VideoInput = None,115 **kwargs: Unpack[PaddleOCRVLProcessorKwargs],116 ) -> BatchFeature:117 """118 Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`119 and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode120 the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to121 SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `vision_infos` is not `None`.122 123 Args:124 images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):125 The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch126 tensor. Both channels-first and channels-last formats are supported.127 text (`str`, `List[str]`, `List[List[str]]`):128 The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings129 (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set130 `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).131 videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):132 The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch133 tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.134 return_tensors (`str` or [`~utils.TensorType`], *optional*):135 If set, will return tensors of a particular framework. Acceptable values are:136 - `'tf'`: Return TensorFlow `tf.constant` objects.137 - `'pt'`: Return PyTorch `torch.Tensor` objects.138 - `'np'`: Return NumPy `np.ndarray` objects.139 - `'jax'`: Return JAX `jnp.ndarray` objects.140 141 Returns:142 [`BatchFeature`]: A [`BatchFeature`] with the following fields:143 144 - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.145 - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when146 `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not147 `None`).148 - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.149 - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.150 - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.151 - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.152 - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.153 """154 output_kwargs = self._merge_kwargs(155 PaddleOCRVLProcessorKwargs,156 tokenizer_init_kwargs=self.tokenizer.init_kwargs,157 **kwargs,158 )159 160 if images is not None:161 image_inputs = self.image_processor(images=images, return_tensors="pt")162 image_inputs["pixel_values"] = image_inputs["pixel_values"]163 image_grid_thw = image_inputs["image_grid_thw"]164 165 else:166 image_inputs = {}167 image_grid_thw = None168 169 if videos is not None:170 # TODO: add video processing171 videos_inputs = self.image_processor(172 images=None, videos=videos, **output_kwargs["images_kwargs"]173 )174 video_grid_thw = videos_inputs["video_grid_thw"]175 176 fps = output_kwargs["videos_kwargs"].pop("fps", 2.0)177 if isinstance(fps, (int, float)):178 second_per_grid_ts = [179 self.image_processor.temporal_patch_size / fps180 ] * len(video_grid_thw)181 elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw):182 second_per_grid_ts = [183 self.image_processor.temporal_patch_size / tmp for tmp in fps184 ]185 else:186 raise ValueError(187 f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number."188 )189 videos_inputs.update(190 {"second_per_grid_ts": torch.tensor(second_per_grid_ts)}191 )192 193 else:194 videos_inputs = {}195 video_grid_thw = None196 197 if not isinstance(text, list):198 text = [text]199 200 if image_grid_thw is not None:201 index = 0202 for i in range(len(text)):203 while self.image_token in text[i]:204 text[i] = text[i].replace(205 self.image_token,206 "<|placeholder|>"207 * (208 image_grid_thw[index].prod()209 // self.image_processor.merge_size210 // self.image_processor.merge_size211 ),212 1,213 )214 index += 1215 text[i] = text[i].replace("<|placeholder|>", self.image_token)216 217 if video_grid_thw is not None:218 index = 0219 for i in range(len(text)):220 while self.video_token in text[i]:221 text[i] = text[i].replace(222 self.video_token,223 "<|placeholder|>"224 * (225 video_grid_thw[index].prod()226 // self.image_processor.merge_size227 // self.image_processor.merge_size228 ),229 1,230 )231 index += 1232 text[i] = text[i].replace("<|placeholder|>", self.video_token)233 234 text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])235 236 return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})237 238 def batch_decode(self, *args, **kwargs):239 """240 This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please241 refer to the docstring of this method for more information.242 """243 return self.tokenizer.batch_decode(*args, **kwargs)244 245 def decode(self, *args, **kwargs):246 """247 This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to248 the docstring of this method for more information.249 """250 return self.tokenizer.decode(*args, **kwargs)251 252 def post_process_image_text_to_text(253 self,254 generated_outputs,255 skip_special_tokens=True,256 clean_up_tokenization_spaces=False,257 **kwargs,258 ):259 """260 Post-process the output of the model to decode the text.261 262 Args:263 generated_outputs (`torch.Tensor` or `np.ndarray`):264 The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`265 or `(sequence_length,)`.266 skip_special_tokens (`bool`, *optional*, defaults to `True`):267 Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.268 Clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):269 Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.270 **kwargs:271 Additional arguments to be passed to the tokenizer's `batch_decode method`.272 273 Returns:274 `List[str]`: The decoded text.275 """276 return self.tokenizer.batch_decode(277 generated_outputs,278 skip_special_tokens=skip_special_tokens,279 clean_up_tokenization_spaces=clean_up_tokenization_spaces,280 **kwargs,281 )282 283 @property284 def model_input_names(self):285 tokenizer_input_names = self.tokenizer.model_input_names286 image_processor_input_names = self.image_processor.model_input_names287 names_from_processor = list(288 dict.fromkeys(tokenizer_input_names + image_processor_input_names)289 )290 return names_from_processor + ["second_per_grid_ts"]291 292 293__all__ = ["PaddleOCRVLProcessor", "PaddleOCRVLProcessor"]294 