



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


UpperCAmelCase_				:     Any              =    logging.get_logger(__name__)
def    UpperCamelCase		(  _A					: List[Any]					,				_A					: Tuple							)->  Optional[int]:





						"""simple docstring"""





						A__					=  b.T
						A__					=  np.sum(np.square(_A							)					,				axis=1							)
						A__					=  np.sum(np.square(_A							)					,				axis=0							)
						A__					=  np.matmul(_A					,				_A							)
						A__					=  aa[:, None] - 2 * ab + ba[None, :]
						return d
def    UpperCamelCase		(  _A					: Any					,				_A					: Optional[Any]							)->  Dict:





						"""simple docstring"""





						A__					=  x.reshape(-1					,				3							)
						A__					=  squared_euclidean_distance(_A					,				_A							)
						return np.argmin(_A					,				axis=1							)






class       UpperCamelCase							(		snake_case__      ):
	lowerCAmelCase			:       Dict								=			["""pixel_values"""]



	def __init__(  self					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = True					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = PILImageResampling.BILINEAR					,			UpperCAmelCase__ = True					,			UpperCAmelCase__ = True					,			**UpperCAmelCase__					,			):
							super().__init__(**__lowercase						)
							A__					=  size if size is not None else {'''height''': 256, '''width''': 256}
							A__					=  get_size_dict(__lowercase						)
							A__					=  np.array(__lowercase						) if clusters is not None else None
							A__					=  do_resize
							A__					=  size
							A__					=  resample
							A__					=  do_normalize
							A__					=  do_color_quantize



	def 					__A				(  self					,			UpperCAmelCase__					,			UpperCAmelCase__					,			UpperCAmelCase__ = PILImageResampling.BILINEAR					,			UpperCAmelCase__ = None					,			**UpperCAmelCase__					,			):
							A__					=  get_size_dict(__lowercase						)
							if "height" not in size or "width" not in size:
													raise ValueError(F"""Size dictionary must contain both height and width keys. Got {size.keys()}"""						)
							return resize(
							    __lowercase					,			size=(size["height"], size["width"])					,			resample=__lowercase					,			data_format=__lowercase					,			**__lowercase						)



	def 					__A				(  self					,			UpperCAmelCase__					,			UpperCAmelCase__ = None					,			):
							A__					=  rescale(image=__lowercase					,			scale=1 / 127.5					,			data_format=__lowercase						)
							A__					=  image - 1
							return image



	def 					__A				(  self					,			UpperCAmelCase__					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = None					,			UpperCAmelCase__ = ChannelDimension.FIRST					,			**UpperCAmelCase__					,			):
							A__					=  do_resize if do_resize is not None else self.do_resize
							A__					=  size if size is not None else self.size
							A__					=  get_size_dict(__lowercase						)
							A__					=  resample if resample is not None else self.resample
							A__					=  do_normalize if do_normalize is not None else self.do_normalize
							A__					=  do_color_quantize if do_color_quantize is not None else self.do_color_quantize
							A__					=  clusters if clusters is not None else self.clusters
							A__					=  np.array(__lowercase						)

							A__					=  make_list_of_images(__lowercase						)

							if not valid_images(__lowercase						):
													raise ValueError(
													    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
													    "torch.Tensor, tf.Tensor or jax.ndarray."						)

							if do_resize and size is None or resample is None:
													raise ValueError("Size and resample must be specified if do_resize is True."						)

							if do_color_quantize and clusters is None:
													raise ValueError("Clusters must be specified if do_color_quantize is True."						)

							# All transformations expect numpy arrays.
							A__					=  [to_numpy_array(__lowercase						) for image in images]

							if do_resize:
													A__					=  [self.resize(image=__lowercase					,			size=__lowercase					,			resample=__lowercase						) for image in images]

							if do_normalize:
													A__					=  [self.normalize(image=__lowercase						) for image in images]

							if do_color_quantize:
													A__					=  [to_channel_dimension_format(__lowercase					,			ChannelDimension.LAST						) for image in images]
													# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
													A__					=  np.array(__lowercase						)
													A__					=  color_quantize(__lowercase					,			__lowercase						).reshape(images.shape[:-1]						)

													# flatten to (batch_size, height*width)
													A__					=  images.shape[0]
													A__					=  images.reshape(__lowercase					,			-1						)

													# We need to convert back to a list of images to keep consistent behaviour across processors.
													A__					=  list(__lowercase						)
							else:
													A__					=  [to_channel_dimension_format(__lowercase					,			__lowercase						) for image in images]

							A__					=  {'''input_ids''': images}
							return BatchFeature(data=__lowercase					,			tensor_type=__lowercase						)












"""simple docstring"""





import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
							from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
							from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
							from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


_UpperCamelCase					      =   DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

_UpperCamelCase					      =   'main'
# Default branch name
_UpperCamelCase					      =   'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
_UpperCamelCase					      =   'aaaaaaa'
# This commit does not exist, so we should 404.

_UpperCamelCase					      =   'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
_UpperCamelCase					      =   '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'



@contextlib.contextmanager
def 					lowerCAmelCase_      (   ):


							'''simple docstring'''







							print('''Welcome!''' )
							yield
							print('''Bye!''' )



@contextlib.contextmanager
def 					lowerCAmelCase_      (   ):


							'''simple docstring'''







							print('''Bonjour!''' )
							yield
							print('''Au revoir!''' )
class 		SCREAMING_SNAKE_CASE_				(     unittest.TestCase ):
				"""simple docstring"""




				def        __lowercase	(  self	:str      ):
											# If the spec is missing, importlib would not be able to import the module dynamically.
											assert transformers.__spec__ is not None
											assert importlib.util.find_spec('''transformers'''      ) is not None

class 		SCREAMING_SNAKE_CASE_				(     unittest.TestCase ):
				"""simple docstring"""




				@unittest.mock.patch('''sys.stdout'''    ,     new_callable=io.StringIO      )
				def        __lowercase	(  self	:str    ,     __lowercase	:str      ):
											with ContextManagers([]      ):
																		print('''Transformers are awesome!'''      )
											# The print statement adds a new line at the end of the output
											self.assertEqual(mock_stdout.getvalue()    ,     '''Transformers are awesome!\n'''      )




				@unittest.mock.patch('''sys.stdout'''    ,     new_callable=io.StringIO      )
				def        __lowercase	(  self	:Any    ,     __lowercase	:Tuple      ):
											with ContextManagers([context_en()]      ):
																		print('''Transformers are awesome!'''      )
											# The output should be wrapped with an English welcome and goodbye
											self.assertEqual(mock_stdout.getvalue()    ,     '''Welcome!\nTransformers are awesome!\nBye!\n'''      )




				@unittest.mock.patch('''sys.stdout'''    ,     new_callable=io.StringIO      )
				def        __lowercase	(  self	:List[Any]    ,     __lowercase	:Optional[Any]      ):
											with ContextManagers([context_fr(), context_en()]      ):
																		print('''Transformers are awesome!'''      )
											# The output should be wrapped with an English and French welcome and goodbye
											self.assertEqual(mock_stdout.getvalue()    ,     '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n'''      )




				@require_torch
				def        __lowercase	(  self	:Tuple      ):
											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''']      )
											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''', '''next_sentence_label''']      )
											self.assertEqual(find_labels(__lowercase      )    ,     ['''start_positions''', '''end_positions''']      )
											class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
															"""simple docstring"""
															pass

											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''']      )




				@require_tf
				def        __lowercase	(  self	:str      ):
											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''']      )
											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''', '''next_sentence_label''']      )
											self.assertEqual(find_labels(__lowercase      )    ,     ['''start_positions''', '''end_positions''']      )
											class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
															"""simple docstring"""
															pass

											self.assertEqual(find_labels(__lowercase      )    ,     ['''labels''']      )




				@require_flax
				def        __lowercase	(  self	:str      ):
											# Flax models don't have labels
											self.assertEqual(find_labels(__lowercase      )    ,     []      )
											self.assertEqual(find_labels(__lowercase      )    ,     []      )
											self.assertEqual(find_labels(__lowercase      )    ,     []      )
											class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
															"""simple docstring"""
															pass

											self.assertEqual(find_labels(__lowercase      )    ,     []      )




