codingutf8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license imagetext processor class for owlvit attributes imageprocessor tokenizer imageprocessorclass owlvitimageprocessor tokenizerclass cliptokenizer cliptokenizerfast def initself imageprocessornone tokenizernone kwargs featureextractor none if featureextractor in kwargs warnings warn the featureextractor argument is deprecated and will be removed in v5 use imageprocessor instead futurewarning featureextractor kwargs popfeatureextractor imageprocessor imageprocessor if imageprocessor is not none else featureextractor if imageprocessor is none raise valueerroryou need to specify an imageprocessor if tokenizer is none raise valueerroryou need to specify a tokenizer super initimageprocessor tokenizer def callself textnone imagesnone queryimagesnone paddingmaxlength returntensorsnp kwargs if text is none and queryimages is none and images is none raise valueerror you have to specify at least one text or query image or image all three cannot be none if text is not none if isinstancetext str or isinstancetext list and not isinstancetext0 list encodings self tokenizertext paddingpadding returntensorsreturntensors kwargs elif isinstancetext list and isinstancetext0 list encodings maximum number of queries across batch maxnumqueries maxlent for t in text pad all batch samples to max number of text queries for t in text if lent maxnumqueries t t maxnumqueries lent encoding self tokenizert paddingpadding returntensorsreturntensors kwargs encodings appendencoding else raise typeerrorinput text should be a string a list of strings or a nested list of strings if returntensors np inputids np concatenateencodinginputids for encoding in encodings axis0 attentionmask np concatenateencodingattentionmask for encoding in encodings axis0 elif returntensors jax and isflaxavailable import jax numpy as jnp inputids jnp concatenateencodinginputids for encoding in encodings axis0 attentionmask jnp concatenateencodingattentionmask for encoding in encodings axis0 elif returntensors pt and istorchavailable import torch inputids torch catencodinginputids for encoding in encodings dim0 attentionmask torch catencodingattentionmask for encoding in encodings dim0 elif returntensors tf and istfavailable import tensorflow as tf inputids tf stackencodinginputids for encoding in encodings axis0 attentionmask tf stackencodingattentionmask for encoding in encodings axis0 else raise valueerrortarget return tensor type could not be returned encoding batchencoding encodinginputids inputids encodingattentionmask attentionmask if queryimages is not none encoding batchencoding querypixelvalues self imageprocessor queryimages returntensorsreturntensors kwargs pixelvalues encodingquerypixelvalues querypixelvalues if images is not none imagefeatures self imageprocessorimages returntensorsreturntensors kwargs if text is not none and images is not none encodingpixelvalues imagefeatures pixelvalues return encoding elif queryimages is not none and images is not none encodingpixelvalues imagefeatures pixelvalues return encoding elif text is not none or queryimages is not none return encoding else return batchencodingdatadictimagefeatures tensortypereturntensors def postprocessself args kwargs return self imageprocessor postprocessargs kwargs def postprocessobjectdetectionself args kwargs return self imageprocessor postprocessobjectdetectionargs kwargs def postprocessimageguideddetectionself args kwargs return self imageprocessor postprocessimageguideddetectionargs kwargs def batchdecodeself args kwargs return self tokenizer batchdecodeargs kwargs def decodeself args kwargs return self tokenizer decodeargs kwargs property def featureextractorclassself warnings warn featureextractorclass is deprecated and will be removed in v5 use imageprocessorclass instead futurewarning return self imageprocessorclass property def featureextractorself warnings warn featureextractor is deprecated and will be removed in v5 use imageprocessor instead futurewarning return self imageprocessor coding utf 8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license image text processor class for owl vit constructs an owl vit processor which wraps owlvitimageprocessor and cliptokenizer cliptokenizerfast into a single processor that interits both the image processor and tokenizer functionalities see the owlvitprocessor __call__ and owlvitprocessor decode for more information args image_processor owlvitimageprocessor optional the image processor is a required input tokenizer cliptokenizer cliptokenizerfast optional the tokenizer is a required input main method to prepare for the model one or several text s and image s this method forwards the text and kwargs arguments to cliptokenizerfast s cliptokenizerfast __call__ if text is not none to encode the text to prepare the image s this method forwards the images and kwrags arguments to clipimageprocessor s clipimageprocessor __call__ if images is not none please refer to the doctsring of the above two methods for more information args text str list str list list str the sequence or batch of sequences to be encoded each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set is_split_into_words true to lift the ambiguity with a batch of sequences images pil image image np ndarray torch tensor list pil image image list np ndarray list torch tensor the image or batch of images to be prepared each image can be a pil image numpy array or pytorch tensor in case of a numpy array pytorch tensor each image should be of shape c h w where c is a number of channels h and w are image height and width query_images pil image image np ndarray torch tensor list pil image image list np ndarray list torch tensor the query image to be prepared one query image is expected per target image to be queried each image can be a pil image numpy array or pytorch tensor in case of a numpy array pytorch tensor each image should be of shape c h w where c is a number of channels h and w are image height and width return_tensors str or utils tensortype optional if set will return tensors of a particular framework acceptable values are tf return tensorflow tf constant objects pt return pytorch torch tensor objects np return numpy np ndarray objects jax return jax jnp ndarray objects returns batchencoding a batchencoding with the following fields input_ids list of token ids to be fed to a model returned when text is not none attention_mask list of indices specifying which tokens should be attended to by the model when return_attention_mask true or if attention_mask is in self model_input_names and if text is not none pixel_values pixel values to be fed to a model returned when images is not none maximum number of queries across batch pad all batch samples to max number of text queries this method forwards all its arguments to owlvitimageprocessor post_process please refer to the docstring of this method for more information this method forwards all its arguments to owlvitimageprocessor post_process_object_detection please refer to the docstring of this method for more information this method forwards all its arguments to owlvitimageprocessor post_process_one_shot_object_detection please refer to the docstring of this method for more information this method forwards all its arguments to cliptokenizerfast s pretrainedtokenizer batch_decode please refer to the docstring of this method for more information this method forwards all its arguments to cliptokenizerfast s pretrainedtokenizer decode please refer to the docstring of this method for more information
import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class OwlViTProcessor(ProcessorMixin):
    r

    attributes = ["image_processor", "tokenizer"]
    image_processor_class = "OwlViTImageProcessor"
    tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")

    def __init__(self, image_processor=None, tokenizer=None, **kwargs):
        feature_extractor = None
        if "feature_extractor" in kwargs:
            warnings.warn(
                "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                " instead.",
                FutureWarning,
            )
            feature_extractor = kwargs.pop("feature_extractor")

        image_processor = image_processor if image_processor is not None else feature_extractor
        if image_processor is None:
            raise ValueError("You need to specify an `image_processor`.")
        if tokenizer is None:
            raise ValueError("You need to specify a `tokenizer`.")

        super().__init__(image_processor, tokenizer)

    def __call__(self, text=None, images=None, query_images=None, padding="max_length", return_tensors="np", **kwargs):
        

        if text is None and query_images is None and images is None:
            raise ValueError(
                "You have to specify at least one text or query image or image. All three cannot be none."
            )

        if text is not None:
            if isinstance(text, str) or (isinstance(text, List) and not isinstance(text[0], List)):
                encodings = [self.tokenizer(text, padding=padding, return_tensors=return_tensors, **kwargs)]

            elif isinstance(text, List) and isinstance(text[0], List):
                encodings = []

                
                max_num_queries = max([len(t) for t in text])

                
                for t in text:
                    if len(t) != max_num_queries:
                        t = t + [" "] * (max_num_queries - len(t))

                    encoding = self.tokenizer(t, padding=padding, return_tensors=return_tensors, **kwargs)
                    encodings.append(encoding)
            else:
                raise TypeError("Input text should be a string, a list of strings or a nested list of strings")

            if return_tensors == "np":
                input_ids = np.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
                attention_mask = np.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)

            elif return_tensors == "jax" and is_flax_available():
                import jax.numpy as jnp

                input_ids = jnp.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
                attention_mask = jnp.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)

            elif return_tensors == "pt" and is_torch_available():
                import torch

                input_ids = torch.cat([encoding["input_ids"] for encoding in encodings], dim=0)
                attention_mask = torch.cat([encoding["attention_mask"] for encoding in encodings], dim=0)

            elif return_tensors == "tf" and is_tf_available():
                import tensorflow as tf

                input_ids = tf.stack([encoding["input_ids"] for encoding in encodings], axis=0)
                attention_mask = tf.stack([encoding["attention_mask"] for encoding in encodings], axis=0)

            else:
                raise ValueError("Target return tensor type could not be returned")

            encoding = BatchEncoding()
            encoding["input_ids"] = input_ids
            encoding["attention_mask"] = attention_mask

        if query_images is not None:
            encoding = BatchEncoding()
            query_pixel_values = self.image_processor(
                query_images, return_tensors=return_tensors, **kwargs
            ).pixel_values
            encoding["query_pixel_values"] = query_pixel_values

        if images is not None:
            image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)

        if text is not None and images is not None:
            encoding["pixel_values"] = image_features.pixel_values
            return encoding
        elif query_images is not None and images is not None:
            encoding["pixel_values"] = image_features.pixel_values
            return encoding
        elif text is not None or query_images is not None:
            return encoding
        else:
            return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)

    def post_process(self, *args, **kwargs):
        
        return self.image_processor.post_process(*args, **kwargs)

    def post_process_object_detection(self, *args, **kwargs):
        
        return self.image_processor.post_process_object_detection(*args, **kwargs)

    def post_process_image_guided_detection(self, *args, **kwargs):
        
        return self.image_processor.post_process_image_guided_detection(*args, **kwargs)

    def batch_decode(self, *args, **kwargs):
        
        return self.tokenizer.batch_decode(*args, **kwargs)

    def decode(self, *args, **kwargs):
        
        return self.tokenizer.decode(*args, **kwargs)

    @property
    def feature_extractor_class(self):
        warnings.warn(
            "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
            FutureWarning,
        )
        return self.image_processor_class

    @property
    def feature_extractor(self):
        warnings.warn(
            "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
            FutureWarning,
        )
        return self.image_processor