processing_ovis2.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright 2025 The HuggingFace Inc. team. 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 at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # 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 and
  13. # limitations under the License.
  14. from ...feature_extraction_utils import BatchFeature
  15. from ...image_utils import ImageInput
  16. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  17. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  18. from ...utils import auto_docstring, logging
  19. logger = logging.get_logger(__name__)
  20. class Ovis2ProcessorKwargs(ProcessingKwargs, total=False):
  21. _defaults = {
  22. "text_kwargs": {
  23. "padding": False,
  24. },
  25. "image_kwargs": {},
  26. }
  27. @auto_docstring
  28. class Ovis2Processor(ProcessorMixin):
  29. def __init__(
  30. self,
  31. image_processor=None,
  32. tokenizer=None,
  33. chat_template=None,
  34. image_token="<image>",
  35. image_seq_length=256,
  36. **kwargs,
  37. ):
  38. r"""
  39. image_token (`str`, *optional*, defaults to `"<image>"`):
  40. Special token used to denote image location.
  41. image_seq_length (`int`, *optional*, defaults to 256):
  42. The number of image tokens to be used for each image in the input.
  43. """
  44. self.image_seq_length = image_seq_length
  45. self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
  46. self.image_token_id = (
  47. tokenizer.image_token_id
  48. if getattr(tokenizer, "image_token_id", None)
  49. else tokenizer.convert_tokens_to_ids(self.image_token)
  50. )
  51. super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
  52. @auto_docstring
  53. def __call__(
  54. self,
  55. images: ImageInput | None = None,
  56. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  57. **kwargs: Unpack[Ovis2ProcessorKwargs],
  58. ) -> BatchFeature:
  59. r"""
  60. Returns:
  61. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  62. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  63. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  64. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  65. `None`).
  66. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  67. - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
  68. """
  69. output_kwargs = self._merge_kwargs(
  70. Ovis2ProcessorKwargs,
  71. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  72. **kwargs,
  73. )
  74. if isinstance(text, str):
  75. text = [text]
  76. elif not isinstance(text, list) and not isinstance(text[0], str):
  77. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  78. image_inputs = {}
  79. if images is not None:
  80. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  81. image_grids = image_inputs.pop("grids").tolist()
  82. text = self._expand_image_tokens(text, image_grids)
  83. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
  84. return BatchFeature(data={**text_inputs, **image_inputs})
  85. def _expand_image_tokens(
  86. self,
  87. text: list[TextInput],
  88. grids: list[list[int]],
  89. ):
  90. processed_text = []
  91. grid_index = 0
  92. for sample in text:
  93. while "<image>" in sample:
  94. grid = grids[grid_index]
  95. row, col = grid[0], grid[1]
  96. placeholder = f"<IMG_START>{'<IMG_ATOM>' * self.image_seq_length}<IMG_GRID>"
  97. if row * col > 1:
  98. for r in range(row):
  99. for c in range(col):
  100. placeholder += f"{'<IMG_ATOM>' * self.image_seq_length}"
  101. if c < col - 1:
  102. placeholder += "<IMG_COL>"
  103. if r < row - 1:
  104. placeholder += "<IMG_ROW>"
  105. placeholder += "<IMG_END>"
  106. sample = sample.replace("<image>", placeholder, 1)
  107. grid_index += 1
  108. processed_text.append(sample)
  109. return processed_text
  110. def batch_decode(self, *args, **kwargs):
  111. """
  112. This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  113. refer to the docstring of this method for more information.
  114. """
  115. return self.tokenizer.batch_decode(*args, **kwargs)
  116. def decode(self, *args, **kwargs):
  117. """
  118. This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  119. the docstring of this method for more information.
  120. """
  121. return self.tokenizer.decode(*args, **kwargs)
  122. @property
  123. def model_input_names(self):
  124. tokenizer_input_names = self.tokenizer.model_input_names
  125. image_processor_input_names = self.image_processor.model_input_names
  126. return list(tokenizer_input_names) + list(image_processor_input_names)
  127. __all__ = ["Ovis2Processor"]