processing_tvp.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # coding=utf-8
  2. # Copyright 2023 The Intel AIA Team Authors, and 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. """
  16. Processor class for TVP.
  17. """
  18. from ...processing_utils import ProcessorMixin
  19. from ...tokenization_utils_base import BatchEncoding
  20. class TvpProcessor(ProcessorMixin):
  21. r"""
  22. Constructs an TVP processor which wraps a TVP image processor and a Bert tokenizer into a single processor.
  23. [`TvpProcessor`] offers all the functionalities of [`TvpImageProcessor`] and [`BertTokenizerFast`]. See the
  24. [`~TvpProcessor.__call__`] and [`~TvpProcessor.decode`] for more information.
  25. Args:
  26. image_processor ([`TvpImageProcessor`], *optional*):
  27. The image processor is a required input.
  28. tokenizer ([`BertTokenizerFast`], *optional*):
  29. The tokenizer is a required input.
  30. """
  31. attributes = ["image_processor", "tokenizer"]
  32. image_processor_class = "TvpImageProcessor"
  33. tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
  34. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  35. if image_processor is None:
  36. raise ValueError("You need to specify an `image_processor`.")
  37. if tokenizer is None:
  38. raise ValueError("You need to specify a `tokenizer`.")
  39. super().__init__(image_processor, tokenizer)
  40. def __call__(self, text=None, videos=None, return_tensors=None, **kwargs):
  41. """
  42. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  43. and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
  44. the text. To prepare the image(s), this method forwards the `videos` and `kwargs` arguments to
  45. TvpImageProcessor's [`~TvpImageProcessor.__call__`] if `videos` is not `None`. Please refer to the doctsring of
  46. the above two methods for more information.
  47. Args:
  48. text (`str`, `List[str]`, `List[List[str]]`):
  49. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  50. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  51. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  52. videos (`List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, `List[List[PIL.Image.Image]]`, `List[List[np.ndarrray]]`,:
  53. `List[List[torch.Tensor]]`): The video or batch of videos to be prepared. Each video should be a list
  54. of frames, which can be either PIL images or NumPy arrays. In case of NumPy arrays/PyTorch tensors,
  55. each frame should be of shape (H, W, C), where H and W are frame height and width, and C is a number of
  56. channels.
  57. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  58. If set, will return tensors of a particular framework. Acceptable values are:
  59. - `'tf'`: Return TensorFlow `tf.constant` objects.
  60. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  61. - `'np'`: Return NumPy `np.ndarray` objects.
  62. - `'jax'`: Return JAX `jnp.ndarray` objects.
  63. Returns:
  64. [`BatchEncoding`]: A [`BatchEncoding`] 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 `videos` is not `None`.
  70. """
  71. max_text_length = kwargs.pop("max_text_length", None)
  72. if text is None and videos is None:
  73. raise ValueError("You have to specify either text or videos. Both cannot be none.")
  74. encoding = {}
  75. if text is not None:
  76. textual_input = self.tokenizer.batch_encode_plus(
  77. text,
  78. truncation=True,
  79. padding="max_length",
  80. max_length=max_text_length,
  81. pad_to_max_length=True,
  82. return_tensors=return_tensors,
  83. return_token_type_ids=False,
  84. **kwargs,
  85. )
  86. encoding.update(textual_input)
  87. if videos is not None:
  88. image_features = self.image_processor(videos, return_tensors=return_tensors, **kwargs)
  89. encoding.update(image_features)
  90. return BatchEncoding(data=encoding, tensor_type=return_tensors)
  91. def batch_decode(self, *args, **kwargs):
  92. """
  93. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  94. refer to the docstring of this method for more information.
  95. """
  96. return self.tokenizer.batch_decode(*args, **kwargs)
  97. def decode(self, *args, **kwargs):
  98. """
  99. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  100. the docstring of this method for more information.
  101. """
  102. return self.tokenizer.decode(*args, **kwargs)
  103. def post_process_video_grounding(self, logits, video_durations):
  104. """
  105. Compute the time of the video.
  106. Args:
  107. logits (`torch.Tensor`):
  108. The logits output of TvpForVideoGrounding.
  109. video_durations (`float`):
  110. The video's duration.
  111. Returns:
  112. start (`float`):
  113. The start time of the video.
  114. end (`float`):
  115. The end time of the video.
  116. """
  117. start, end = (
  118. round(logits.tolist()[0][0] * video_durations, 1),
  119. round(logits.tolist()[0][1] * video_durations, 1),
  120. )
  121. return start, end
  122. @property
  123. # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
  124. def model_input_names(self):
  125. tokenizer_input_names = self.tokenizer.model_input_names
  126. image_processor_input_names = self.image_processor.model_input_names
  127. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))