






"""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      UpperCamelCase_			(__A	):
	__magic_name__       =							['''image_processor''', '''tokenizer''']
	__magic_name__       =							'''OwlViTImageProcessor'''
	__magic_name__       =							('''CLIPTokenizer''', '''CLIPTokenizerFast''')





	def __init__( self   :					List[Any]      ,      lowerCAmelCase_   :					Any=None      ,      lowerCAmelCase_   :					str=None      ,      **lowerCAmelCase_   :					Union[str, Any]		)		->     str:
				UpperCAmelCase_	:					Optional[Any]     	=   None
				if "feature_extractor" in kwargs:
							warnings.warn(
							    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
							    " instead."      ,      lowerCAmelCase_      ,      )
							UpperCAmelCase_	:					int     	=   kwargs.pop("feature_extractor"		)

				UpperCAmelCase_	:					str     	=   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__(lowerCAmelCase_      ,      lowerCAmelCase_		)





	def __call__( self   :					Optional[int]      ,      lowerCAmelCase_   :					List[Any]=None      ,      lowerCAmelCase_   :					Tuple=None      ,      lowerCAmelCase_   :					List[str]=None      ,      lowerCAmelCase_   :					Optional[int]="max_length"      ,      lowerCAmelCase_   :					Tuple="np"      ,      **lowerCAmelCase_   :					List[Any]		)		->     List[str]:

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

							elif isinstance(lowerCAmelCase_      ,      lowerCAmelCase_		) and isinstance(text[0]      ,      lowerCAmelCase_		):
										UpperCAmelCase_	:					str     	=   []

										# Maximum number of queries across batch
										UpperCAmelCase_	:					Union[str, Any]     	=   max([len(lowerCAmelCase_		) for t in text]		)

										# Pad all batch samples to max number of text queries
										for t in text:
													if len(lowerCAmelCase_		) != max_num_queries:
																UpperCAmelCase_	:					int     	=   t + [" "] * (max_num_queries - len(lowerCAmelCase_		))

													UpperCAmelCase_	:					List[str]     	=   self.tokenizer(lowerCAmelCase_      ,      padding=lowerCAmelCase_      ,      return_tensors=lowerCAmelCase_      ,      **lowerCAmelCase_		)
													encodings.append(lowerCAmelCase_		)
							else:
										raise TypeError("Input text should be a string, a list of strings or a nested list of strings"		)

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

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

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

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

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

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

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

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

							UpperCAmelCase_	:					Union[str, Any]     	=   BatchEncoding()
							UpperCAmelCase_	:					List[str]     	=   input_ids
							UpperCAmelCase_	:					Any     	=   attention_mask

				if query_images is not None:
							UpperCAmelCase_	:					Optional[int]     	=   BatchEncoding()
							UpperCAmelCase_	:					Any     	=   self.image_processor(
							    lowerCAmelCase_      ,      return_tensors=lowerCAmelCase_      ,      **lowerCAmelCase_		).pixel_values
							UpperCAmelCase_	:					str     	=   query_pixel_values

				if images is not None:
							UpperCAmelCase_	:					Tuple     	=   self.image_processor(lowerCAmelCase_      ,      return_tensors=lowerCAmelCase_      ,      **lowerCAmelCase_		)

				if text is not None and images is not None:
							UpperCAmelCase_	:					List[str]     	=   image_features.pixel_values
							return encoding
				elif query_images is not None and images is not None:
							UpperCAmelCase_	:					Optional[Any]     	=   image_features.pixel_values
							return encoding
				elif text is not None or query_images is not None:
							return encoding
				else:
							return BatchEncoding(data=dict(**lowerCAmelCase_		)      ,      tensor_type=lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]      ,      *lowerCAmelCase_   :					Any      ,      **lowerCAmelCase_   :					int		)		->     Optional[Any]:
				return self.image_processor.post_process(*lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					int      ,      *lowerCAmelCase_   :					str      ,      **lowerCAmelCase_   :					Optional[int]		)		->     Dict:
				return self.image_processor.post_process_object_detection(*lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]      ,      *lowerCAmelCase_   :					Union[str, Any]      ,      **lowerCAmelCase_   :					Dict		)		->     Tuple:
				return self.image_processor.post_process_image_guided_detection(*lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[Any]      ,      *lowerCAmelCase_   :					Optional[Any]      ,      **lowerCAmelCase_   :					Tuple		)		->     List[str]:
				return self.tokenizer.batch_decode(*lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]      ,      *lowerCAmelCase_   :					List[str]      ,      **lowerCAmelCase_   :					Optional[Any]		)		->     int:
				return self.tokenizer.decode(*lowerCAmelCase_      ,      **lowerCAmelCase_		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]		)		->     Any:
				warnings.warn(
				    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."      ,      lowerCAmelCase_      ,      )
				return self.image_processor_class





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					str		)		->     Any:
				warnings.warn(
				    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,      lowerCAmelCase_      ,      )
				return self.image_processor











"""simple docstring"""
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor







class      UpperCamelCase_			(unittest.TestCase	):





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					List[str]=13      ,      lowerCAmelCase_   :					Union[str, Any]=3      ,      lowerCAmelCase_   :					Union[str, Any]=224      ,      lowerCAmelCase_   :					List[Any]=30      ,      lowerCAmelCase_   :					Any=400      ,      lowerCAmelCase_   :					Any=True      ,      lowerCAmelCase_   :					Dict=None      ,      lowerCAmelCase_   :					int=True      ,      lowerCAmelCase_   :					Any=[0.5, 0.5, 0.5]      ,      lowerCAmelCase_   :					str=[0.5, 0.5, 0.5]      ,      )		->     Dict:
				UpperCAmelCase_	:					int     	=   size if size is not None else {"height": 18, "width": 18}
				UpperCAmelCase_	:					List[Any]     	=   parent
				UpperCAmelCase_	:					int     	=   batch_size
				UpperCAmelCase_	:					Optional[int]     	=   num_channels
				UpperCAmelCase_	:					Dict     	=   image_size
				UpperCAmelCase_	:					Union[str, Any]     	=   min_resolution
				UpperCAmelCase_	:					List[str]     	=   max_resolution
				UpperCAmelCase_	:					Dict     	=   do_resize
				UpperCAmelCase_	:					Optional[int]     	=   size
				UpperCAmelCase_	:					List[str]     	=   do_normalize
				UpperCAmelCase_	:					List[Any]     	=   image_mean
				UpperCAmelCase_	:					Dict     	=   image_std





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Union[str, Any]:
				return {
				    "image_mean": self.image_mean,
				    "image_std": self.image_std,
				    "do_normalize": self.do_normalize,
				    "do_resize": self.do_resize,
				    "size": self.size,
				}







@require_torch
@require_vision
class      UpperCamelCase_			(__A							,		unittest.TestCase	):
	__magic_name__       =							ViTImageProcessor if is_vision_available() else None





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   EfficientFormerImageProcessorTester(self		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				return self.image_proc_tester.prepare_image_processor_dict()





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple		)		->     str:
				UpperCAmelCase_	:					Tuple     	=   self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_mean"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_std"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_normalize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_resize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "size"		)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     List[str]:
				pass





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     int:
				# Initialize image_processor
				UpperCAmelCase_	:					str     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				UpperCAmelCase_	:					int     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      Image.Image		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[Any]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					str     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					List[str]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random numpy tensors
				UpperCAmelCase_	:					List[str]     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      numpify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      np.ndarray		)

				# Test not batched input
				UpperCAmelCase_	:					str     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Dict     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					Optional[Any]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PyTorch tensors
				UpperCAmelCase_	:					Dict     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      torchify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      torch.Tensor		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )



