

'''simple docstring'''






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      lowercase_      (lowerCamelCase__ ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE       :    Union[str, Any]							     =     ['image_processor', 'tokenizer']
  SCREAMING_SNAKE_CASE       :    str							     =     'OwlViTImageProcessor'
  SCREAMING_SNAKE_CASE       :    List[str]							     =     ('CLIPTokenizer', 'CLIPTokenizerFast')






  def __init__( self  :	Any   ,lowercase__  :	str=None   ,lowercase__  :	Any=None   ,**lowercase__  :	List[Any]     ):
   __lowercase				    =					None
   if "feature_extractor" in kwargs:
    warnings.warn(
        '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
        ''' instead.'''   ,lowercase__   ,)
    __lowercase				    =					kwargs.pop('''feature_extractor'''     )

   __lowercase				    =					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__(lowercase__   ,lowercase__     )






  def __call__( self  :	str   ,lowercase__  :	Tuple=None   ,lowercase__  :	List[Any]=None   ,lowercase__  :	Dict=None   ,lowercase__  :	List[str]="max_length"   ,lowercase__  :	List[Any]="np"   ,**lowercase__  :	Dict     ):

   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(lowercase__   ,lowercase__     ) or (isinstance(lowercase__   ,lowercase__     ) and not isinstance(text[0]   ,lowercase__     )):
     __lowercase				    =					[self.tokenizer(lowercase__   ,padding=lowercase__   ,return_tensors=lowercase__   ,**lowercase__     )]

    elif isinstance(lowercase__   ,lowercase__     ) and isinstance(text[0]   ,lowercase__     ):
     __lowercase				    =					[]

     # Maximum number of queries across batch
     __lowercase				    =					max([len(lowercase__     ) for t in text]     )

     # Pad all batch samples to max number of text queries
     for t in text:
      if len(lowercase__     ) != max_num_queries:
       __lowercase				    =					t + [''' '''] * (max_num_queries - len(lowercase__     ))

      __lowercase				    =					self.tokenizer(lowercase__   ,padding=lowercase__   ,return_tensors=lowercase__   ,**lowercase__     )
      encodings.append(lowercase__     )
    else:
     raise TypeError('''Input text should be a string, a list of strings or a nested list of strings'''     )

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

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

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

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

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

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

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

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

    __lowercase				    =					BatchEncoding()
    __lowercase				    =					input_ids
    __lowercase				    =					attention_mask

   if query_images is not None:
    __lowercase				    =					BatchEncoding()
    __lowercase				    =					self.image_processor(
        lowercase__   ,return_tensors=lowercase__   ,**lowercase__     ).pixel_values
    __lowercase				    =					query_pixel_values

   if images is not None:
    __lowercase				    =					self.image_processor(lowercase__   ,return_tensors=lowercase__   ,**lowercase__     )

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






  def    SCREAMING_SNAKE_CASE ( self  :	int   ,*lowercase__  :	Optional[int]   ,**lowercase__  :	Tuple     ):
   return self.image_processor.post_process(*lowercase__   ,**lowercase__     )






  def    SCREAMING_SNAKE_CASE ( self  :	Dict   ,*lowercase__  :	List[Any]   ,**lowercase__  :	int     ):
   return self.image_processor.post_process_object_detection(*lowercase__   ,**lowercase__     )






  def    SCREAMING_SNAKE_CASE ( self  :	int   ,*lowercase__  :	List[str]   ,**lowercase__  :	Union[str, Any]     ):
   return self.image_processor.post_process_image_guided_detection(*lowercase__   ,**lowercase__     )






  def    SCREAMING_SNAKE_CASE ( self  :	int   ,*lowercase__  :	str   ,**lowercase__  :	Union[str, Any]     ):
   return self.tokenizer.batch_decode(*lowercase__   ,**lowercase__     )






  def    SCREAMING_SNAKE_CASE ( self  :	str   ,*lowercase__  :	List[Any]   ,**lowercase__  :	Dict     ):
   return self.tokenizer.decode(*lowercase__   ,**lowercase__     )






  @property
  def    SCREAMING_SNAKE_CASE ( self  :	List[Any]     ):
   warnings.warn(
       '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''   ,lowercase__   ,)
   return self.image_processor_class






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





'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


_UpperCamelCase 							=  {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  ["""ViTFeatureExtractor"""]
      _UpperCamelCase 							=  ["""ViTImageProcessor"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  [
          """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """ViTForImageClassification""",
          """ViTForMaskedImageModeling""",
          """ViTModel""",
          """ViTPreTrainedModel""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  [
          """TFViTForImageClassification""",
          """TFViTModel""",
          """TFViTPreTrainedModel""",
      ]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  [
          """FlaxViTForImageClassification""",
          """FlaxViTModel""",
          """FlaxViTPreTrainedModel""",
      ]

if TYPE_CHECKING:
      from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .feature_extraction_vit import ViTFeatureExtractor
            from .image_processing_vit import ViTImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_vit import (
                VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                ViTForImageClassification,
                ViTForMaskedImageModeling,
                ViTModel,
                ViTPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel


else:
      import sys

      _UpperCamelCase 							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

