processing_ovis2.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # coding=utf-8
  2. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Optional, Union
  16. from ...feature_extraction_utils import BatchFeature
  17. from ...image_utils import ImageInput
  18. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  19. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. class Ovis2ProcessorKwargs(ProcessingKwargs, total=False):
  23. _defaults = {
  24. "text_kwargs": {
  25. "padding": False,
  26. },
  27. "image_kwargs": {},
  28. }
  29. class Ovis2Processor(ProcessorMixin):
  30. r"""
  31. Constructs a Ovis2 processor which wraps Ovis2 image processor and a Qwen2 tokenizer into a single processor.
  32. [`Ovis2Processor`] offers all the functionalities of [`Ovis2VideoProcessor`], [`Ovis2ImageProcessor`] and [`Qwen2TokenizerFast`]. See the
  33. [`~Ovis2Processor.__call__`] and [`~Ovis2Processor.decode`] for more information.
  34. Args:
  35. image_processor ([`Ovis2ImageProcessor`], *optional*):
  36. The image processor is a required input.
  37. tokenizer ([`Qwen2TokenizerFast`], *optional*):
  38. The tokenizer is a required input.
  39. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  40. in a chat into a tokenizable string.
  41. image_token (`str`, *optional*, defaults to `"<image>"`):
  42. Special token used to denote image location.
  43. image_seq_length (`int`, *optional*, defaults to 256):
  44. The number of image tokens to be used for each image in the input.
  45. """
  46. attributes = ["image_processor", "tokenizer"]
  47. image_processor_class = "AutoImageProcessor"
  48. tokenizer_class = "AutoTokenizer"
  49. def __init__(
  50. self,
  51. image_processor=None,
  52. tokenizer=None,
  53. chat_template=None,
  54. image_token="<image>",
  55. image_seq_length=256,
  56. **kwargs,
  57. ):
  58. self.image_seq_length = image_seq_length
  59. self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
  60. self.image_token_id = (
  61. tokenizer.image_token_id
  62. if getattr(tokenizer, "image_token_id", None)
  63. else tokenizer.convert_tokens_to_ids(self.image_token)
  64. )
  65. super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
  66. def __call__(
  67. self,
  68. images: Optional[ImageInput] = None,
  69. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  70. **kwargs: Unpack[Ovis2ProcessorKwargs],
  71. ) -> BatchFeature:
  72. """
  73. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  74. and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
  75. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  76. Ovis2ImageProcessor's [`~Ovis2ImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
  77. of the above two methods for more information.
  78. Args:
  79. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  80. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  81. tensor. Both channels-first and channels-last formats are supported.
  82. text (`str`, `List[str]`, `List[List[str]]`):
  83. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  84. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  85. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  86. Returns:
  87. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  88. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  89. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  90. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  91. `None`).
  92. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  93. - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
  94. """
  95. output_kwargs = self._merge_kwargs(
  96. Ovis2ProcessorKwargs,
  97. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  98. **kwargs,
  99. )
  100. if isinstance(text, str):
  101. text = [text]
  102. elif not isinstance(text, list) and not isinstance(text[0], str):
  103. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  104. image_inputs = {}
  105. if images is not None:
  106. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  107. image_grids = image_inputs.pop("grids").tolist()
  108. text = self._expand_image_tokens(text, image_grids)
  109. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
  110. return BatchFeature(data={**text_inputs, **image_inputs})
  111. def _expand_image_tokens(
  112. self,
  113. text: list[TextInput],
  114. grids: list[list[int]],
  115. ):
  116. processed_text = []
  117. grid_index = 0
  118. for sample in text:
  119. while "<image>" in sample:
  120. grid = grids[grid_index]
  121. row, col = grid[0], grid[1]
  122. placeholder = f"<IMG_START>{'<IMG_ATOM>' * self.image_seq_length}<IMG_GRID>"
  123. if row * col > 1:
  124. for r in range(row):
  125. for c in range(col):
  126. placeholder += f"{'<IMG_ATOM>' * self.image_seq_length}"
  127. if c < col - 1:
  128. placeholder += "<IMG_COL>"
  129. if r < row - 1:
  130. placeholder += "<IMG_ROW>"
  131. placeholder += "<IMG_END>"
  132. sample = sample.replace("<image>", placeholder, 1)
  133. grid_index += 1
  134. processed_text.append(sample)
  135. return processed_text
  136. def batch_decode(self, *args, **kwargs):
  137. """
  138. This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  139. refer to the docstring of this method for more information.
  140. """
  141. return self.tokenizer.batch_decode(*args, **kwargs)
  142. def decode(self, *args, **kwargs):
  143. """
  144. This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  145. the docstring of this method for more information.
  146. """
  147. return self.tokenizer.decode(*args, **kwargs)
  148. @property
  149. def model_input_names(self):
  150. tokenizer_input_names = self.tokenizer.model_input_names
  151. image_processor_input_names = self.image_processor.model_input_names
  152. return list(tokenizer_input_names) + list(image_processor_input_names)
  153. __all__ = ["Ovis2Processor"]