






"""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 os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				Any     ,    SCREAMING_SNAKE_CASE							:				List[str]=()     ,    SCREAMING_SNAKE_CASE							:				Union[str, Any]=None     ,    SCREAMING_SNAKE_CASE							:				Dict="no"     ,    SCREAMING_SNAKE_CASE							:				int="29500" ):


							'''simple docstring'''







							__lowerCamelCase   :   Optional[int]       =False
							__lowerCamelCase   :   Tuple       =False
							if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ):
														__lowerCamelCase   :   Optional[int]       =True
							elif "IPython" in sys.modules:
														__lowerCamelCase   :   int       ='''google.colab''' in str(sys.modules['''IPython'''].get_ipython() )

							try:
														__lowerCamelCase   :   str       =PrecisionType(mixed_precision.lower() )
							except ValueError:
														raise ValueError(
														    F'Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.' )

							if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME'''     ,    SCREAMING_SNAKE_CASE ) is not None):
														# TPU launch
														import torch_xla.distributed.xla_multiprocessing as xmp

														if len(AcceleratorState._shared_state ) > 0:
																					raise ValueError(
																					    '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside '''
																					    '''your training function. Restart your notebook and make sure no cells initializes an '''
																					    '''`Accelerator`.''' )
														if num_processes is None:
																					__lowerCamelCase   :   int       =8

														__lowerCamelCase   :   Optional[Any]       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    distributed_type='''TPU''' )
														print(F'Launching a training on {num_processes} TPU cores.' )
														xmp.spawn(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )
							elif in_colab:
														# No need for a distributed launch otherwise as it's either CPU or one GPU.
														if torch.cuda.is_available():
																					print('''Launching training on one GPU.''' )
														else:
																					print('''Launching training on one CPU.''' )
														function(*SCREAMING_SNAKE_CASE )
							else:
														if num_processes is None:
																					raise ValueError(
																					    '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' )

														if num_processes > 1:
																					# Multi-GPU launch
																					from torch.multiprocessing import start_processes
																					from torch.multiprocessing.spawn import ProcessRaisedException

																					if len(AcceleratorState._shared_state ) > 0:
																												raise ValueError(
																												    '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized '''
																												    '''inside your training function. Restart your notebook and make sure no cells initializes an '''
																												    '''`Accelerator`.''' )

																					if torch.cuda.is_initialized():
																												raise ValueError(
																												    '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction '''
																												    '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA '''
																												    '''function.''' )

																					# torch.distributed will expect a few environment variable to be here. We set the ones common to each
																					# process here (the other ones will be set be the launcher).
																					with patch_environment(
																					    world_size=SCREAMING_SNAKE_CASE     ,    master_addr='''127.0.01'''     ,    master_port=SCREAMING_SNAKE_CASE     ,    mixed_precision=SCREAMING_SNAKE_CASE ):
																												__lowerCamelCase   :   List[str]       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    distributed_type='''MULTI_GPU''' )
																												print(F'Launching training on {num_processes} GPUs.' )
																												try:
																																			start_processes(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )
																												except ProcessRaisedException as e:
																																			if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
																																										raise RuntimeError(
																																										    '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. '''
																																										    '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. '''
																																										    '''Please review your imports and test them when running the `notebook_launcher()` to identify '''
																																										    '''which one is problematic.''' ) from e

														else:
																					# No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
																					if is_mps_available():
																												__lowerCamelCase   :   Optional[Any]       ='''1'''
																												print('''Launching training on MPS.''' )
																					elif torch.cuda.is_available():
																												print('''Launching training on one GPU.''' )
																					else:
																												print('''Launching training on CPU.''' )
																					function(*SCREAMING_SNAKE_CASE )



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				str     ,    SCREAMING_SNAKE_CASE							:				Optional[int]=()     ,    SCREAMING_SNAKE_CASE							:				Optional[Any]=2 ):


							'''simple docstring'''







							from torch.multiprocessing import start_processes

							with tempfile.NamedTemporaryFile() as tmp_file:
														# torch.distributed will expect a few environment variable to be here. We set the ones common to each
														# process here (the other ones will be set be the launcher).
														with patch_environment(
														    world_size=SCREAMING_SNAKE_CASE     ,    master_addr='''127.0.01'''     ,    master_port='''29500'''     ,    accelerate_mixed_precision='''no'''     ,    accelerate_debug_rdv_file=tmp_file.name     ,    accelerate_use_cpu='''yes'''     ,    ):
																					__lowerCamelCase   :   Tuple       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    debug=SCREAMING_SNAKE_CASE )
																					start_processes(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )




