processing_janus.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # coding=utf-8
  2. # Copyright 2025 Deepseek AI and The HuggingFace 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. """
  16. Processor class for Janus.
  17. """
  18. from typing import Optional, Union
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...image_utils import ImageInput
  21. from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  22. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. DEFAULT_SYSTEM_PROMPT = (
  26. "You are a helpful language and vision assistant. "
  27. "You are able to understand the visual content that the user provides, "
  28. "and assist the user with a variety of tasks using natural language.\n\n"
  29. )
  30. class JanusTextKwargs(TextKwargs, total=False):
  31. generation_mode: str
  32. class JanusProcessorKwargs(ProcessingKwargs, total=False):
  33. text_kwargs: JanusTextKwargs
  34. _defaults = {
  35. "text_kwargs": {"padding": False, "generation_mode": "text"},
  36. "common_kwargs": {"return_tensors": "pt"},
  37. }
  38. class JanusProcessor(ProcessorMixin):
  39. r"""
  40. Constructs a Janus processor which wraps a Janus Image Processor and a Llama tokenizer into a single processor.
  41. [`JanusProcessor`] offers all the functionalities of [`JanusImageProcessor`] and [`LlamaTokenizerFast`]. See the
  42. [`~JanusProcessor.__call__`] and [`~JanusProcessor.decode`] for more information.
  43. Args:
  44. image_processor ([`JanusImageProcessor`]):
  45. The image processor is a required input.
  46. tokenizer ([`LlamaTokenizerFast`]):
  47. The tokenizer is a required input.
  48. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  49. in a chat into a tokenizable string.
  50. use_default_system_prompt (`str`, *optional*, defaults to `False`):
  51. Use default system prompt for Text Generation.
  52. """
  53. attributes = ["image_processor", "tokenizer"]
  54. image_processor_class = "JanusImageProcessor"
  55. tokenizer_class = "LlamaTokenizerFast"
  56. def __init__(self, image_processor, tokenizer, chat_template=None, use_default_system_prompt=False, **kwargs):
  57. self.num_image_tokens = 576
  58. self.image_token = tokenizer.image_token
  59. self.image_start_token = tokenizer.boi_token
  60. self.image_end_token = tokenizer.eoi_token
  61. self.use_default_system_prompt = use_default_system_prompt
  62. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  63. def __call__(
  64. self,
  65. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  66. images: Optional[ImageInput] = None,
  67. videos=None,
  68. audio=None,
  69. **kwargs: Unpack[JanusProcessorKwargs],
  70. ) -> BatchFeature:
  71. """
  72. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  73. and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
  74. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  75. JanusImageProcessor's [`~JanusImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
  76. of the above two methods for more information.
  77. Args:
  78. text (`str`, `list[str]`, `list[list[str]]`):
  79. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  80. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  81. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  82. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  83. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  84. tensor. Both channels-first and channels-last formats are supported.
  85. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  86. If set, will return tensors of a particular framework. Acceptable values are:
  87. - `'tf'`: Return TensorFlow `tf.constant` objects.
  88. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  89. - `'np'`: Return NumPy `np.ndarray` objects.
  90. - `'jax'`: Return JAX `jnp.ndarray` objects.
  91. Returns:
  92. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  93. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  94. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  95. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  96. `None`).
  97. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  98. """
  99. output_kwargs = self._merge_kwargs(
  100. JanusProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs
  101. )
  102. if text is None and images is None:
  103. raise ValueError("You must specify either text or images.")
  104. if text is not None:
  105. if isinstance(text, str):
  106. text = [text]
  107. elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
  108. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  109. generation_mode = output_kwargs["text_kwargs"].pop("generation_mode")
  110. # Replace the image token with expanded image tokens.
  111. prompt_strings = []
  112. one_img_tokens = self.image_start_token + (self.image_token * self.num_image_tokens) + self.image_end_token
  113. for prompt in text:
  114. prompt = prompt.replace(self.image_token, one_img_tokens)
  115. if self.use_default_system_prompt and generation_mode == "text":
  116. prompt = DEFAULT_SYSTEM_PROMPT + prompt
  117. if generation_mode == "image":
  118. prompt += self.image_start_token
  119. prompt_strings.append(prompt)
  120. data = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  121. # Process images if pixel values are provided.
  122. if images is not None and generation_mode != "image":
  123. data["pixel_values"] = self.image_processor(images=images, **output_kwargs["images_kwargs"])[
  124. "pixel_values"
  125. ]
  126. return BatchFeature(data=data)
  127. def postprocess(self, images: ImageInput, **kwargs):
  128. """
  129. Forwards all arguments to the image processor's `postprocess` method.
  130. Refer to the original method's docstring for more details.
  131. """
  132. return self.image_processor.postprocess(images, **kwargs)
  133. __all__ = ["JanusProcessor"]