# Copyright 2026 WebBrain and the HuggingFace Inc. team. All rights reserved. # # Adapted from moonshotai/Kimi-VL-A3B-Instruct's processing_kimi_vl.py # (Apache-2.0), itself based on the Qwen2-VL processor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Processor for Laguna XS 2.1 Vision: wraps LagunaImageProcessor + the Laguna tokenizer.""" from typing import List, Union from transformers.feature_extraction_utils import BatchFeature from transformers.image_utils import ImageInput from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack from transformers.tokenization_utils_base import PreTokenizedInput, TextInput from transformers.utils import logging logger = logging.get_logger(__name__) class LagunaProcessorKwargs(ProcessingKwargs, total=False): _defaults = { "text_kwargs": {"padding": False}, "images_kwargs": {}, } class LagunaProcessor(ProcessorMixin): r""" Constructs a Laguna processor which wraps [`LagunaImageProcessor`] and the Laguna tokenizer into a single processor. The chat template emits one literal `〈|SPECIAL_10|〉` placeholder per image (wrapped in `〈|SPECIAL_8|〉image〈|SPECIAL_9|〉...〈|SPECIAL_11|〉` — four previously-unused reserved special-token ids repurposed as media start/content/pad/end markers, see ``config.json``'s ``media_placeholder_token_id`` and the model card). This processor expands that single placeholder into ``grid_h * grid_w / merge_length`` repeats — the number of tokens the vision tower + projector will actually produce for that image's resolution — before tokenization. """ attributes = ["image_processor", "tokenizer"] valid_kwargs = ["chat_template"] image_processor_class = "AutoImageProcessor" tokenizer_class = "AutoTokenizer" def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs): self.image_token = "〈|SPECIAL_10|〉" super().__init__(image_processor, tokenizer, chat_template=chat_template) def __call__( self, images: ImageInput = None, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, **kwargs: Unpack[LagunaProcessorKwargs], ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least one of `images` or `text`.") output_kwargs = self._merge_kwargs( LagunaProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) if images is not None: image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"]) image_grid_hws = image_inputs["image_grid_hws"] else: image_inputs = {} image_grid_hws = None if isinstance(text, str): text = [text] elif not isinstance(text, list) and not isinstance(text[0], str): raise ValueError("Invalid input text. Please provide a string, or a list of strings") if image_grid_hws is not None: merge_length = self.image_processor.merge_kernel_size[0] * self.image_processor.merge_kernel_size[1] index = 0 for i in range(len(text)): while self.image_token in text[i]: num_tokens = int(image_grid_hws[index].prod() // merge_length) text[i] = text[i].replace(self.image_token, "〈|PLACEHOLDER|〉" * num_tokens, 1) index += 1 text[i] = text[i].replace("〈|PLACEHOLDER|〉", self.image_token) text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"]) return BatchFeature(data={**text_inputs, **image_inputs}) def batch_decode(self, *args, **kwargs): return self.tokenizer.batch_decode(*args, **kwargs) def decode(self, *args, **kwargs): return self.tokenizer.decode(*args, **kwargs) @property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) __all__ = ["LagunaProcessor", "LagunaProcessorKwargs"]