DoruC/Grounded-Segment-Anything
0
1# coding=utf-82# Copyright 2023 The HuggingFace Inc. team.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 at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""16Image/Text processor class for ALIGN17"""18 19 20from ...processing_utils import ProcessorMixin21from ...tokenization_utils_base import BatchEncoding22 23 24class AlignProcessor(ProcessorMixin):25 r"""26 Constructs an ALIGN processor which wraps [`EfficientNetImageProcessor`] and27 [`BertTokenizer`]/[`BertTokenizerFast`] into a single processor that interits both the image processor and28 tokenizer functionalities. See the [`~AlignProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more29 information.30 31 Args:32 image_processor ([`EfficientNetImageProcessor`]):33 The image processor is a required input.34 tokenizer ([`BertTokenizer`, `BertTokenizerFast`]):35 The tokenizer is a required input.36 """37 38 attributes = ["image_processor", "tokenizer"]39 image_processor_class = "EfficientNetImageProcessor"40 tokenizer_class = ("BertTokenizer", "BertTokenizerFast")41 42 def __init__(self, image_processor, tokenizer):43 super().__init__(image_processor, tokenizer)44 45 def __call__(self, text=None, images=None, padding="max_length", max_length=64, return_tensors=None, **kwargs):46 """47 Main method to prepare text(s) and image(s) to be fed as input to the model. This method forwards the `text`48 and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode49 the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to50 EfficientNetImageProcessor's [`~EfficientNetImageProcessor.__call__`] if `images` is not `None`. Please refer51 to the doctsring of the above two methods for more information.52 53 Args:54 text (`str`, `List[str]`):55 The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings56 (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set57 `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).58 images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):59 The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch60 tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a61 number of channels, H and W are image height and width.62 padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `max_length`):63 Activates and controls padding for tokenization of input text. Choose between [`True` or `'longest'`,64 `'max_length'`, `False` or `'do_not_pad'`]65 max_length (`int`, *optional*, defaults to `max_length`):66 Maximum padding value to use to pad the input text during tokenization.67 68 return_tensors (`str` or [`~utils.TensorType`], *optional*):69 If set, will return tensors of a particular framework. Acceptable values are:70 71 - `'tf'`: Return TensorFlow `tf.constant` objects.72 - `'pt'`: Return PyTorch `torch.Tensor` objects.73 - `'np'`: Return NumPy `np.ndarray` objects.74 - `'jax'`: Return JAX `jnp.ndarray` objects.75 76 Returns:77 [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:78 79 - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.80 - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when81 `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not82 `None`).83 - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.84 """85 if text is None and images is None:86 raise ValueError("You have to specify either text or images. Both cannot be none.")87 88 if text is not None:89 encoding = self.tokenizer(90 text, padding=padding, max_length=max_length, return_tensors=return_tensors, **kwargs91 )92 93 if images is not None:94 image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)95 96 if text is not None and images is not None:97 encoding["pixel_values"] = image_features.pixel_values98 return encoding99 elif text is not None:100 return encoding101 else:102 return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)103 104 def batch_decode(self, *args, **kwargs):105 """106 This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please107 refer to the docstring of this method for more information.108 """109 return self.tokenizer.batch_decode(*args, **kwargs)110 111 def decode(self, *args, **kwargs):112 """113 This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to114 the docstring of this method for more information.115 """116 return self.tokenizer.decode(*args, **kwargs)117 118 @property119 def model_input_names(self):120 tokenizer_input_names = self.tokenizer.model_input_names121 image_processor_input_names = self.image_processor.model_input_names122 return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))123 