Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.3#4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16import re17from typing import Optional, Union18 19import numpy as np20 21from ...feature_extraction_utils import BatchFeature22from ...image_utils import ImageInput, make_nested_list_of_images23from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack24from ...tokenization_utils_base import PreTokenizedInput, TextInput25from ...utils import to_py_obj26 27 28class Gemma3ImagesKwargs(ImagesKwargs):29 do_pan_and_scan: Optional[bool]30 pan_and_scan_min_crop_size: Optional[int]31 pan_and_scan_max_num_crops: Optional[int]32 pan_and_scan_min_ratio_to_activate: Optional[float]33 do_convert_rgb: Optional[bool]34 35 36class Gemma3ProcessorKwargs(ProcessingKwargs, total=False):37 images_kwargs: Gemma3ImagesKwargs38 _defaults = {39 "text_kwargs": {40 "padding": False,41 "return_mm_token_type_ids": True,42 },43 "images_kwargs": {44 "do_convert_rgb": True,45 "do_pan_and_scan": False,46 "pan_and_scan_min_crop_size": 256,47 "pan_and_scan_max_num_crops": 4,48 "pan_and_scan_min_ratio_to_activate": 1.2,49 },50 }51 52 53class Gemma3Processor(ProcessorMixin):54 attributes = ["image_processor", "tokenizer"]55 image_processor_class = "AutoImageProcessor"56 tokenizer_class = "AutoTokenizer"57 58 def __init__(59 self,60 image_processor,61 tokenizer,62 chat_template=None,63 image_seq_length: int = 256,64 **kwargs,65 ):66 self.image_seq_length = image_seq_length67 self.image_token_id = tokenizer.image_token_id68 self.boi_token = tokenizer.boi_token69 self.image_token = tokenizer.image_token70 image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)71 self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"72 73 super().__init__(74 image_processor=image_processor,75 tokenizer=tokenizer,76 chat_template=chat_template,77 **kwargs,78 )79 80 def __call__(81 self,82 images: Optional[ImageInput] = None,83 text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,84 videos=None,85 audio=None,86 **kwargs: Unpack[Gemma3ProcessorKwargs],87 ) -> BatchFeature:88 if text is None and images is None:89 raise ValueError("Provide at least one of `text` or `images`.")90 91 output_kwargs = self._merge_kwargs(92 Gemma3ProcessorKwargs,93 tokenizer_init_kwargs=self.tokenizer.init_kwargs,94 **kwargs,95 )96 97 if isinstance(text, str):98 text = [text]99 elif not isinstance(text, list) and not isinstance(text[0], str):100 raise TypeError("Invalid input text. Please provide a string, or a list of strings")101 102 image_inputs = {}103 if images is not None:104 images = self.image_processor.fetch_images(images)105 batched_images = make_nested_list_of_images(images)106 image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])107 108 # Create empty text to be replaced with placeholders109 if not text:110 text = [" ".join([self.boi_token] * len(images)) for images in batched_images]111 112 if len(batched_images) != len(text):113 raise ValueError(114 f"Received inconsistently sized batches of images ({len(batched_images)}) and text ({len(text)})."115 )116 117 # Replace image tokens by the full expanded sequence118 num_crops = to_py_obj(image_inputs.pop("num_crops"))119 batch_num_crops = [[num_crops.pop(0) for _ in range(len(images))] for images in batched_images]120 for batch_idx, (prompt, images, num_crops) in enumerate(zip(text, batched_images, batch_num_crops)):121 image_indexes = [m.start() for m in re.finditer(self.boi_token, prompt)]122 123 if len(images) != len(image_indexes):124 raise ValueError(125 f"Prompt contained {len(image_indexes)} image tokens but received {len(images)} images."126 )127 128 # Insert additional image tokens for Pan-and-Scan crops129 for num, idx in reversed(list(zip(num_crops, image_indexes))):130 if num:131 formatted_image_text = (132 f"Here is the original image {self.boi_token} and here are some crops to help you see better "133 + " ".join([self.boi_token] * num)134 )135 prompt = prompt[:idx] + formatted_image_text + prompt[idx + len(self.boi_token) :]136 text[batch_idx] = prompt137 138 # Expand placeholder image tokens to the full image token sequence139 text = [prompt.replace(self.boi_token, self.full_image_sequence) for prompt in text]140 141 return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)142 return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)143 text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])144 self._check_special_mm_tokens(text, text_inputs, modalities=["image"])145 146 # Add token type ids manually, as tokenizer can't do arbitrary position token types147 if return_mm_token_type_ids:148 array_ids = np.array(text_inputs["input_ids"])149 mm_token_type_ids = np.zeros_like(array_ids)150 mm_token_type_ids[array_ids == self.image_token_id] = 1151 text_inputs["token_type_ids"] = mm_token_type_ids.tolist()152 153 return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)154 155 def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):156 """157 Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.158 159 Args:160 image_sizes (`list[list[int]]`, *optional*):161 The input sizes formatted as (height, width) per each image.162 163 Returns:164 `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided165 input modalities, along with other useful data.166 """167 168 vision_data = {}169 if image_sizes is not None:170 # NOTE: no image cropping supported yet171 num_image_tokens = [self.image_seq_length] * len(image_sizes)172 num_image_patches = [1] * len(image_sizes)173 174 vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})175 176 return MultiModalData(**vision_data)177 178 @property179 def model_input_names(self):180 tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids"]181 image_processor_input_names = self.image_processor.model_input_names182 183 image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]184 return list(tokenizer_input_names + image_processor_input_names)185 186 187__all__ = ["Gemma3Processor"]188 