





'''simple docstring'''




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            =       logging.get_logger(__name__)



def 		__A		(  lowerCamelCase_			,			lowerCamelCase_	):


		"""simple docstring"""



		SCREAMING_SNAKE_CASE :				int		=			b.T
		SCREAMING_SNAKE_CASE :				Dict		=			np.sum(np.square(lowerCamelCase_	)			,			axis=1	)
		SCREAMING_SNAKE_CASE :				Any		=			np.sum(np.square(lowerCamelCase_	)			,			axis=0	)
		SCREAMING_SNAKE_CASE :				Dict		=			np.matmul(lowerCamelCase_			,			lowerCamelCase_	)
		SCREAMING_SNAKE_CASE :				Tuple		=			aa[:, None] - 2 * ab + ba[None, :]
		return d



def 		__A		(  lowerCamelCase_			,			lowerCamelCase_	):


		"""simple docstring"""



		SCREAMING_SNAKE_CASE :				Optional[int]		=			x.reshape(-1			,			3	)
		SCREAMING_SNAKE_CASE :				Dict		=			squared_euclidean_distance(lowerCamelCase_			,			lowerCamelCase_	)
		return np.argmin(lowerCamelCase_			,			axis=1	)




class      UpperCamelCase__					(					lowercase_			):




					"""simple docstring"""
					SCREAMING_SNAKE_CASE__				=	['''pixel_values''']


					def __init__(						self				:			Any      ,						lowerCamelCase_				:			Optional[Union[List[List[int]], np.ndarray]] = None      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Dict[str, int] = None      ,						lowerCamelCase_				:			PILImageResampling = PILImageResampling.BILINEAR      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			bool = True      ,						**lowerCamelCase_				:			str      ,						):

							'''simple docstring'''



							super().__init__(**lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			size if size is not None else {"""height""": 2_56, """width""": 2_56}
							SCREAMING_SNAKE_CASE :				List[str]		=			get_size_dict(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			np.array(lowerCamelCase_						) if clusters is not None else None
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			do_resize
							SCREAMING_SNAKE_CASE :				List[str]		=			size
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			resample
							SCREAMING_SNAKE_CASE :				Dict		=			do_normalize
							SCREAMING_SNAKE_CASE :				str		=			do_color_quantize


					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			np.ndarray      ,						lowerCamelCase_				:			Dict[str, int]      ,						lowerCamelCase_				:			PILImageResampling = PILImageResampling.BILINEAR      ,						lowerCamelCase_				:			Optional[Union[str, ChannelDimension]] = None      ,						**lowerCamelCase_				:			Tuple      ,						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			get_size_dict(lowerCamelCase_						)
							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(
							    lowerCamelCase_      ,						size=(size["""height"""], size["""width"""])      ,						resample=lowerCamelCase_      ,						data_format=lowerCamelCase_      ,						**lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			np.ndarray      ,						lowerCamelCase_				:			Optional[Union[str, ChannelDimension]] = None      ,						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Any		=			rescale(image=lowerCamelCase_      ,						scale=1 / 127.5      ,						data_format=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			image - 1
							return image



					def lowerCamelCase_			(						self				:			Optional[int]      ,						lowerCamelCase_				:			ImageInput      ,						lowerCamelCase_				:			bool = None      ,						lowerCamelCase_				:			Dict[str, int] = None      ,						lowerCamelCase_				:			PILImageResampling = None      ,						lowerCamelCase_				:			bool = None      ,						lowerCamelCase_				:			Optional[bool] = None      ,						lowerCamelCase_				:			Optional[Union[List[List[int]], np.ndarray]] = None      ,						lowerCamelCase_				:			Optional[Union[str, TensorType]] = None      ,						lowerCamelCase_				:			Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST      ,						**lowerCamelCase_				:			Any      ,						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Tuple		=			do_resize if do_resize is not None else self.do_resize
							SCREAMING_SNAKE_CASE :				Dict		=			size if size is not None else self.size
							SCREAMING_SNAKE_CASE :				str		=			get_size_dict(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Dict		=			resample if resample is not None else self.resample
							SCREAMING_SNAKE_CASE :				Tuple		=			do_normalize if do_normalize is not None else self.do_normalize
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			do_color_quantize if do_color_quantize is not None else self.do_color_quantize
							SCREAMING_SNAKE_CASE :				List[str]		=			clusters if clusters is not None else self.clusters
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			np.array(lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				Any		=			make_list_of_images(lowerCamelCase_						)

							if not valid_images(lowerCamelCase_						):
									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.
							SCREAMING_SNAKE_CASE :				Dict		=			[to_numpy_array(lowerCamelCase_						) for image in images]

							if do_resize:
									SCREAMING_SNAKE_CASE :				Optional[int]		=			[self.resize(image=lowerCamelCase_      ,						size=lowerCamelCase_      ,						resample=lowerCamelCase_						) for image in images]

							if do_normalize:
									SCREAMING_SNAKE_CASE :				Union[str, Any]		=			[self.normalize(image=lowerCamelCase_						) for image in images]

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

									# flatten to (batch_size, height*width)
									SCREAMING_SNAKE_CASE :				str		=			images.shape[0]
									SCREAMING_SNAKE_CASE :				int		=			images.reshape(lowerCamelCase_      ,						-1						)

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

							SCREAMING_SNAKE_CASE :				Dict		=			{"""input_ids""": images}
							return BatchFeature(data=lowerCamelCase_      ,						tensor_type=lowerCamelCase_						)










'''simple docstring'''




import os
import sys
import unittest


__UpperCAmelCase            =       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__UpperCAmelCase            =       os.path.join(git_repo_path, """src""", """transformers""")

__UpperCAmelCase            =       """
{0} = None
"""

__UpperCAmelCase            =       """
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
"""


__UpperCAmelCase            =       """
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""




class      UpperCamelCase__					(					unittest.TestCase			):




					"""simple docstring"""


					def lowerCamelCase_			(						self				:			List[str]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Dict		=			find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""						)
							self.assertIsNone(lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				str		=			find_backend("""    if not is_tokenizers_available():"""						)
							self.assertEqual(lowerCamelCase_      ,						"""tokenizers"""						)

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			find_backend("""    if not is_tensorflow_text_available():"""						)
							self.assertEqual(lowerCamelCase_      ,						"""tensorflow_text"""						)

							SCREAMING_SNAKE_CASE :				List[str]		=			find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""						)
							self.assertEqual(lowerCamelCase_      ,						"""sentencepiece_and_tokenizers"""						)

							SCREAMING_SNAKE_CASE :				Tuple		=			find_backend(
							    """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""						)
							self.assertEqual(lowerCamelCase_      ,						"""sentencepiece_and_tensorflow_text"""						)

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			find_backend(
							    """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""						)
							self.assertEqual(lowerCamelCase_      ,						"""sentencepiece_and_tokenizers_and_vision"""						)


					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Optional[Any]		=			read_init()
							# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
							self.assertIn("""torch"""      ,						lowerCamelCase_						)
							self.assertIn("""tensorflow_text"""      ,						lowerCamelCase_						)
							self.assertIn("""sentencepiece_and_tokenizers"""      ,						lowerCamelCase_						)

							# Likewise, we can't assert on the exact content of a key
							self.assertIn("""BertModel"""      ,						objects["""torch"""]						)
							self.assertIn("""TFBertModel"""      ,						objects["""tf"""]						)
							self.assertIn("""FlaxBertModel"""      ,						objects["""flax"""]						)
							self.assertIn("""BertModel"""      ,						objects["""torch"""]						)
							self.assertIn("""TFBertTokenizer"""      ,						objects["""tensorflow_text"""]						)
							self.assertIn("""convert_slow_tokenizer"""      ,						objects["""sentencepiece_and_tokenizers"""]						)


					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				str		=			create_dummy_object("""CONSTANT"""      ,						"""'torch'"""						)
							self.assertEqual(lowerCamelCase_      ,						"""\nCONSTANT = None\n"""						)

							SCREAMING_SNAKE_CASE :				List[Any]		=			create_dummy_object("""function"""      ,						"""'torch'"""						)
							self.assertEqual(
							    lowerCamelCase_      ,						"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""						)

							SCREAMING_SNAKE_CASE :				str		=			"""
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			create_dummy_object("""FakeClass"""      ,						"""'torch'"""						)
							self.assertEqual(lowerCamelCase_      ,						lowerCamelCase_						)



					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			"""# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
							SCREAMING_SNAKE_CASE :				List[Any]		=			create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}						)
							self.assertEqual(dummy_files["""torch"""]      ,						lowerCamelCase_						)



