processing_janus.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Copyright 2025 Deepseek AI and The HuggingFace 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. """
  15. Processor class for Janus.
  16. """
  17. from ...feature_extraction_utils import BatchFeature
  18. from ...image_utils import ImageInput
  19. from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  20. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  21. from ...utils import auto_docstring, logging
  22. logger = logging.get_logger(__name__)
  23. DEFAULT_SYSTEM_PROMPT = (
  24. "You are a helpful language and vision assistant. "
  25. "You are able to understand the visual content that the user provides, "
  26. "and assist the user with a variety of tasks using natural language.\n\n"
  27. )
  28. class JanusTextKwargs(TextKwargs, total=False):
  29. """
  30. generation_mode (`str`, *optional*, defaults to `"text"`):
  31. The generation mode indicating which modality to generate. Can be one of `"text"` or `"image"`. When set
  32. to `"text"`, the processor prepares inputs for text generation. When set to `"image"`, it prepares inputs
  33. for image generation by appending image start tokens to the prompt.
  34. """
  35. generation_mode: str
  36. class JanusProcessorKwargs(ProcessingKwargs, total=False):
  37. text_kwargs: JanusTextKwargs
  38. _defaults = {
  39. "text_kwargs": {"padding": False, "padding_side": "left", "generation_mode": "text"},
  40. "common_kwargs": {"return_tensors": "pt"},
  41. }
  42. @auto_docstring
  43. class JanusProcessor(ProcessorMixin):
  44. def __init__(self, image_processor, tokenizer, chat_template=None, use_default_system_prompt=False, **kwargs):
  45. r"""
  46. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  47. Use default system prompt for Text Generation.
  48. """
  49. self.num_image_tokens = 576
  50. self.image_token = tokenizer.image_token
  51. self.image_start_token = tokenizer.boi_token
  52. self.image_end_token = tokenizer.eoi_token
  53. self.use_default_system_prompt = use_default_system_prompt
  54. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  55. @auto_docstring
  56. def __call__(
  57. self,
  58. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  59. images: ImageInput | None = None,
  60. **kwargs: Unpack[JanusProcessorKwargs],
  61. ) -> BatchFeature:
  62. r"""
  63. Returns:
  64. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  65. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  66. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  67. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  68. `None`).
  69. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  70. """
  71. output_kwargs = self._merge_kwargs(
  72. JanusProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs
  73. )
  74. if text is None and images is None:
  75. raise ValueError("You must specify either text or images.")
  76. if text is not None:
  77. if isinstance(text, str):
  78. text = [text]
  79. elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
  80. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  81. generation_mode = output_kwargs["text_kwargs"].pop("generation_mode")
  82. # Replace the image token with expanded image tokens.
  83. prompt_strings = []
  84. one_img_tokens = self.image_start_token + (self.image_token * self.num_image_tokens) + self.image_end_token
  85. for prompt in text:
  86. prompt = prompt.replace(self.image_token, one_img_tokens)
  87. if self.use_default_system_prompt and generation_mode == "text":
  88. prompt = DEFAULT_SYSTEM_PROMPT + prompt
  89. if generation_mode == "image":
  90. prompt += self.image_start_token
  91. prompt_strings.append(prompt)
  92. data = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  93. # Process images if pixel values are provided.
  94. if images is not None and generation_mode != "image":
  95. data["pixel_values"] = self.image_processor(images=images, **output_kwargs["images_kwargs"])[
  96. "pixel_values"
  97. ]
  98. return BatchFeature(data=data)
  99. def postprocess(self, images: ImageInput, **kwargs):
  100. """
  101. Forwards all arguments to the image processor's `postprocess` method.
  102. Refer to the original method's docstring for more details.
  103. """
  104. return self.image_processor.postprocess(images, **kwargs)
  105. def post_process_multimodal_output(
  106. self, generated_outputs, skip_special_tokens=True, generation_mode=None, **kwargs
  107. ):
  108. """
  109. Post-process the output of a multimodal model to return the requested modality output.
  110. If the model cannot generated the requested modality, an error will be raised.
  111. Args:
  112. generated_outputs (`torch.Tensor` or `np.ndarray`):
  113. The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
  114. or `(sequence_length,)`.
  115. skip_special_tokens (`bool`, *optional*, defaults to `True`):
  116. Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
  117. generation_mode (`str`, *optional*):
  118. Generation mode indicated which modality to output and can be one of `["text", "image", "audio"]`.
  119. **kwargs:
  120. Additional arguments to be passed to the tokenizer's `batch_decode method`.
  121. Returns:
  122. `list[Union[str, PIL.Image.Image]]`: The decoded text or generated image.
  123. """
  124. if generation_mode is None or generation_mode == "text":
  125. return self.post_process_image_text_to_text(
  126. generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs
  127. )
  128. elif generation_mode == "image":
  129. generated_outputs = list(generated_outputs.float())
  130. images = self.postprocess(generated_outputs, return_tensors="PIL.Image.Image")
  131. return images["pixel_values"]
  132. else:
  133. raise ValueError(
  134. f"{self.__class__.__name__} got an unexpected generation_mode={generation_mode}. Supported options are only `text` and `image"
  135. )
  136. __all__ = ["JanusProcessor"]