


import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate

class   A__							(						UpperCamelCase__					):
						UpperCAmelCase     =  CONFIG_NAME




						@register_to_config
						def __init__(    self   : str			,      _a   : bool = True			,      _a   : int = 8			,      _a   : str = "lanczos"			,      _a   : bool = True			,      _a   : bool = False			,      )							->       List[Any]:


										"""simple docstring"""





										super().__init__()




						@staticmethod
						def 							__UpperCamelCase			(    _a   : np.ndarray					)							->       PIL.Image.Image:


										"""simple docstring"""





										if images.ndim == 3:
														_SCREAMING_SNAKE_CASE     					=images[None, ...]
										_SCREAMING_SNAKE_CASE     					=(images * 255).round().astype('''uint8'''					)
										if images.shape[-1] == 1:
														# special case for grayscale (single channel) images
														_SCREAMING_SNAKE_CASE     					=[Image.fromarray(image.squeeze()			,      mode='''L'''					) for image in images]
										else:
														_SCREAMING_SNAKE_CASE     					=[Image.fromarray(_a					) for image in images]

										return pil_images




						@staticmethod
						def 							__UpperCamelCase			(    _a   : Union[List[PIL.Image.Image], PIL.Image.Image]					)							->       np.ndarray:


										"""simple docstring"""





										if not isinstance(_a			,      _a					):
														_SCREAMING_SNAKE_CASE     					=[images]
										_SCREAMING_SNAKE_CASE     					=[np.array(_a					).astype(np.floataa					) / 2_55.0 for image in images]
										_SCREAMING_SNAKE_CASE     					=np.stack(_a			,      axis=0					)

										return images




						@staticmethod
						def 							__UpperCamelCase			(    _a   : np.ndarray					)							->       torch.FloatTensor:


										"""simple docstring"""





										if images.ndim == 3:
														_SCREAMING_SNAKE_CASE     					=images[..., None]

										_SCREAMING_SNAKE_CASE     					=torch.from_numpy(images.transpose(0			,      3			,      1			,      2					)					)
										return images




						@staticmethod
						def 							__UpperCamelCase			(    _a   : torch.FloatTensor					)							->       np.ndarray:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=images.cpu().permute(0			,      2			,      3			,      1					).float().numpy()
										return images




						@staticmethod
						def 							__UpperCamelCase			(    _a   : Any					)							->       str:


										"""simple docstring"""





										return 2.0 * images - 1.0




						@staticmethod
						def 							__UpperCamelCase			(    _a   : List[Any]					)							->       Any:


										"""simple docstring"""





										return (images / 2 + 0.5).clamp(0			,      1					)




						@staticmethod
						def 							__UpperCamelCase			(    _a   : PIL.Image.Image					)							->       PIL.Image.Image:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=image.convert('''RGB'''					)
										return image




						def 							__UpperCamelCase			(    self   : Optional[int]			,      _a   : PIL.Image.Image			,      _a   : Optional[int] = None			,      _a   : Optional[int] = None			,      )							->       PIL.Image.Image:


										"""simple docstring"""





										if height is None:
														_SCREAMING_SNAKE_CASE     					=image.height
										if width is None:
														_SCREAMING_SNAKE_CASE     					=image.width

										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=(
										    x - x % self.config.vae_scale_factor for x in (width, height)
										)  # resize to integer multiple of vae_scale_factor
										_SCREAMING_SNAKE_CASE     					=image.resize((width, height)			,      resample=PIL_INTERPOLATION[self.config.resample]					)
										return image




						def 							__UpperCamelCase			(    self   : Union[str, Any]			,      _a   : Union[torch.FloatTensor, PIL.Image.Image, np.ndarray]			,      _a   : Optional[int] = None			,      _a   : Optional[int] = None			,      )							->       torch.Tensor:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=(PIL.Image.Image, np.ndarray, torch.Tensor)
										if isinstance(_a			,      _a					):
														_SCREAMING_SNAKE_CASE     					=[image]
										elif not (isinstance(_a			,      _a					) and all(isinstance(_a			,      _a					) for i in image					)):
														raise ValueError(
														    f"Input is in incorrect format: {[type(_a					) for i in image]}. Currently, we only support {', '.join(_a					)}"					)

										if isinstance(image[0]			,      PIL.Image.Image					):
														if self.config.do_convert_rgb:
																		_SCREAMING_SNAKE_CASE     					=[self.convert_to_rgb(_a					) for i in image]
														if self.config.do_resize:
																		_SCREAMING_SNAKE_CASE     					=[self.resize(_a			,      _a			,      _a					) for i in image]
														_SCREAMING_SNAKE_CASE     					=self.pil_to_numpy(_a					)  # to np
														_SCREAMING_SNAKE_CASE     					=self.numpy_to_pt(_a					)  # to pt

										elif isinstance(image[0]			,      np.ndarray					):
														_SCREAMING_SNAKE_CASE     					=np.concatenate(_a			,      axis=0					) if image[0].ndim == 4 else np.stack(_a			,      axis=0					)
														_SCREAMING_SNAKE_CASE     					=self.numpy_to_pt(_a					)
														_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=image.shape
														if self.config.do_resize and (
														    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
														):
																		raise ValueError(
																		    f"Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"
																		    f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"					)

										elif isinstance(image[0]			,      torch.Tensor					):
														_SCREAMING_SNAKE_CASE     					=torch.cat(_a			,      axis=0					) if image[0].ndim == 4 else torch.stack(_a			,      axis=0					)
														_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=image.shape

														# don't need any preprocess if the image is latents
														if channel == 4:
																		return image

														if self.config.do_resize and (
														    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
														):
																		raise ValueError(
																		    f"Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"
																		    f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"					)

        # expected range [0,1], normalize to [-1,1]
										_SCREAMING_SNAKE_CASE     					=self.config.do_normalize
										if image.min() < 0:
														warnings.warn(
														    '''Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] '''
														    f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]"			,      _a			,      )
														_SCREAMING_SNAKE_CASE     					=False

										if do_normalize:
														_SCREAMING_SNAKE_CASE     					=self.normalize(_a					)

										return image




						def 							__UpperCamelCase			(    self   : Union[str, Any]			,      _a   : torch.FloatTensor			,      _a   : str = "pil"			,      _a   : Optional[List[bool]] = None			,      )							->       Union[str, Any]:


										"""simple docstring"""





										if not isinstance(_a			,      torch.Tensor					):
														raise ValueError(
														    f"Input for postprocessing is in incorrect format: {type(_a					)}. We only support pytorch tensor"					)
										if output_type not in ["latent", "pt", "np", "pil"]:
														_SCREAMING_SNAKE_CASE     					=(
														    f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
														    '''`pil`, `np`, `pt`, `latent`'''
														)
														deprecate('''Unsupported output_type'''			,      '''1.0.0'''			,      _a			,      standard_warn=_a					)
														_SCREAMING_SNAKE_CASE     					='''np'''

										if output_type == "latent":
														return image

										if do_denormalize is None:
														_SCREAMING_SNAKE_CASE     					=[self.config.do_normalize] * image.shape[0]

										_SCREAMING_SNAKE_CASE     					=torch.stack(
										    [self.denormalize(image[i]					) if do_denormalize[i] else image[i] for i in range(image.shape[0]					)]					)

										if output_type == "pt":
														return image

										_SCREAMING_SNAKE_CASE     					=self.pt_to_numpy(_a					)

										if output_type == "np":
														return image

										if output_type == "pil":
														return self.numpy_to_pil(_a					)

class   A__							(						UpperCamelCase__					):
						UpperCAmelCase     =  CONFIG_NAME




						@register_to_config
						def __init__(    self   : List[str]			,      _a   : bool = True			,      _a   : int = 8			,      _a   : str = "lanczos"			,      _a   : bool = True			,      )							->       Dict:


										"""simple docstring"""





										super().__init__()




						@staticmethod
						def 							__UpperCamelCase			(    _a   : List[str]					)							->       Dict:


										"""simple docstring"""





										if images.ndim == 3:
														_SCREAMING_SNAKE_CASE     					=images[None, ...]
										_SCREAMING_SNAKE_CASE     					=(images * 255).round().astype('''uint8'''					)
										if images.shape[-1] == 1:
														# special case for grayscale (single channel) images
														_SCREAMING_SNAKE_CASE     					=[Image.fromarray(image.squeeze()			,      mode='''L'''					) for image in images]
										else:
														_SCREAMING_SNAKE_CASE     					=[Image.fromarray(image[:, :, :3]					) for image in images]

										return pil_images




						@staticmethod
						def 							__UpperCamelCase			(    _a   : Any					)							->       int:


										"""simple docstring"""





										return image[:, :, 1] * 2**8 + image[:, :, 2]




						def 							__UpperCamelCase			(    self   : List[str]			,      _a   : List[str]					)							->       List[str]:


										"""simple docstring"""





										if images.ndim == 3:
														_SCREAMING_SNAKE_CASE     					=images[None, ...]
										_SCREAMING_SNAKE_CASE     					=images[:, :, :, 3:]
										if images.shape[-1] == 6:
														_SCREAMING_SNAKE_CASE     					=(images_depth * 255).round().astype('''uint8'''					)
														_SCREAMING_SNAKE_CASE     					=[
														    Image.fromarray(self.rgblike_to_depthmap(_a					)			,      mode='''I;16'''					) for image_depth in images_depth
														]
										elif images.shape[-1] == 4:
														_SCREAMING_SNAKE_CASE     					=(images_depth * 6_55_35.0).astype(np.uintaa					)
														_SCREAMING_SNAKE_CASE     					=[Image.fromarray(_a			,      mode='''I;16'''					) for image_depth in images_depth]
										else:
														raise Exception('''Not supported'''					)

										return pil_images




						def 							__UpperCamelCase			(    self   : Any			,      _a   : torch.FloatTensor			,      _a   : str = "pil"			,      _a   : Optional[List[bool]] = None			,      )							->       str:


										"""simple docstring"""





										if not isinstance(_a			,      torch.Tensor					):
														raise ValueError(
														    f"Input for postprocessing is in incorrect format: {type(_a					)}. We only support pytorch tensor"					)
										if output_type not in ["latent", "pt", "np", "pil"]:
														_SCREAMING_SNAKE_CASE     					=(
														    f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
														    '''`pil`, `np`, `pt`, `latent`'''
														)
														deprecate('''Unsupported output_type'''			,      '''1.0.0'''			,      _a			,      standard_warn=_a					)
														_SCREAMING_SNAKE_CASE     					='''np'''

										if do_denormalize is None:
														_SCREAMING_SNAKE_CASE     					=[self.config.do_normalize] * image.shape[0]

										_SCREAMING_SNAKE_CASE     					=torch.stack(
										    [self.denormalize(image[i]					) if do_denormalize[i] else image[i] for i in range(image.shape[0]					)]					)

										_SCREAMING_SNAKE_CASE     					=self.pt_to_numpy(_a					)

										if output_type == "np":
														if image.shape[-1] == 6:
																		_SCREAMING_SNAKE_CASE     					=np.stack([self.rgblike_to_depthmap(im[:, :, 3:]					) for im in image]			,      axis=0					)
														else:
																		_SCREAMING_SNAKE_CASE     					=image[:, :, :, 3:]
														return image[:, :, :, :3], image_depth

										if output_type == "pil":
														return self.numpy_to_pil(_a					), self.numpy_to_depth(_a					)
										else:
														raise Exception(f"This type {output_type} is not supported"					)



import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class   A__							(						unittest.TestCase					):




						def __init__(    self   : List[Any]			,      _a   : Optional[Any]			,      _a   : int=3			,      _a   : int=32			,      _a   : str=3			,      _a   : List[str]=10			,      _a   : Optional[Any]=[10, 20, 30, 40]			,      _a   : Tuple=[1, 1, 2, 1]			,      _a   : Optional[Any]=True			,      _a   : Optional[int]=True			,      _a   : Any="relu"			,      _a   : Any=3			,      _a   : Tuple=None			,      )							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=parent
										_SCREAMING_SNAKE_CASE     					=batch_size
										_SCREAMING_SNAKE_CASE     					=image_size
										_SCREAMING_SNAKE_CASE     					=num_channels
										_SCREAMING_SNAKE_CASE     					=embeddings_size
										_SCREAMING_SNAKE_CASE     					=hidden_sizes
										_SCREAMING_SNAKE_CASE     					=depths
										_SCREAMING_SNAKE_CASE     					=is_training
										_SCREAMING_SNAKE_CASE     					=use_labels
										_SCREAMING_SNAKE_CASE     					=hidden_act
										_SCREAMING_SNAKE_CASE     					=num_labels
										_SCREAMING_SNAKE_CASE     					=scope
										_SCREAMING_SNAKE_CASE     					=len(_a					)




						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       str:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

										_SCREAMING_SNAKE_CASE     					=self.get_config()

										return config, pixel_values




						def 							__UpperCamelCase			(    self   : List[str]					)							->       Dict:


										"""simple docstring"""





										return ResNetConfig(
										    num_channels=self.num_channels			,      embeddings_size=self.embeddings_size			,      hidden_sizes=self.hidden_sizes			,      depths=self.depths			,      hidden_act=self.hidden_act			,      num_labels=self.num_labels			,      image_size=self.image_size			,      )




						def 							__UpperCamelCase			(    self   : Optional[Any]			,      _a   : Union[str, Any]			,      _a   : List[Any]					)							->       Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModel(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)

										# Output shape (b, c, h, w)
										self.parent.assertEqual(
										    result.last_hidden_state.shape			,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,      )




						def 							__UpperCamelCase			(    self   : int			,      _a   : str			,      _a   : str					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.num_labels
										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)
										self.parent.assertEqual(result.logits.shape			,      (self.batch_size, self.num_labels)					)




						def 							__UpperCamelCase			(    self   : Tuple					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.prepare_config_and_inputs()
										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=config_and_inputs
										_SCREAMING_SNAKE_CASE     					={'''pixel_values''': pixel_values}
										return config, inputs_dict

@require_flax
class   A__							(						UpperCamelCase__				,       unittest.TestCase					):
						UpperCAmelCase     =  (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False




						def 							__UpperCamelCase			(    self   : str					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModelTester(self					)
										_SCREAMING_SNAKE_CASE     					=ConfigTester(self			,      config_class=_a			,      has_text_modality=_a					)




						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       int:


										"""simple docstring"""





										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()




						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       Union[str, Any]:


										"""simple docstring"""





										return




						def 							__UpperCamelCase			(    self   : int					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a					)




						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a					)




						@unittest.skip(reason='''ResNet does not use inputs_embeds'''					)
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       List[Any]:


										"""simple docstring"""





										pass




						@unittest.skip(reason='''ResNet does not support input and output embeddings'''					)
						def 							__UpperCamelCase			(    self   : Dict					)							->       Dict:


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : Any					)							->       int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)
														_SCREAMING_SNAKE_CASE     					=inspect.signature(model.__call__					)
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														_SCREAMING_SNAKE_CASE     					=[*signature.parameters.keys()]

														_SCREAMING_SNAKE_CASE     					=['''pixel_values''']
														self.assertListEqual(arg_names[:1]			,      _a					)




						def 							__UpperCamelCase			(    self   : Dict					)							->       Union[str, Any]:


										"""simple docstring"""





										def check_hidden_states_output(_a   : Optional[Any]			,      _a   : Tuple			,      _a   : Optional[Any]					):
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)

														_SCREAMING_SNAKE_CASE     					=model(**self._prepare_for_class(_a			,      _a					)					)

														_SCREAMING_SNAKE_CASE     					=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

														_SCREAMING_SNAKE_CASE     					=self.model_tester.num_stages
														self.assertEqual(len(_a					)			,      expected_num_stages + 1					)




						@unittest.skip(reason='''ResNet does not use feedforward chunking'''					)
						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       Dict:


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : List[Any]					)							->       Any:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__					):
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(_a			,      _a					)
																		_SCREAMING_SNAKE_CASE     					=model_class(_a					)

																		@jax.jit
																		def model_jitted(_a   : Optional[Any]			,      **_a   : Any					):
																						return model(pixel_values=_a			,      **_a					)

																		with self.subTest('''JIT Enabled'''					):
																						_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		with self.subTest('''JIT Disabled'''					):
																						with jax.disable_jit():
																										_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		self.assertEqual(len(_a					)			,      len(_a					)					)
																		for jitted_output, output in zip(_a			,      _a					):
																						self.assertEqual(jitted_output.shape			,      output.shape					)







def   lowerCamelCase(				):
				_SCREAMING_SNAKE_CASE     					=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image


@require_flax
class   A__							(						unittest.TestCase					):




						@cached_property
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       Any:


										"""simple docstring"""





										return AutoImageProcessor.from_pretrained('''microsoft/resnet-50'''					) if is_vision_available() else None




						@slow
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification.from_pretrained('''microsoft/resnet-50'''					)

										_SCREAMING_SNAKE_CASE     					=self.default_image_processor
										_SCREAMING_SNAKE_CASE     					=prepare_img()
										_SCREAMING_SNAKE_CASE     					=image_processor(images=_a			,      return_tensors='''np'''					)

										_SCREAMING_SNAKE_CASE     					=model(**_a					)

										# verify the logits
										_SCREAMING_SNAKE_CASE     					=(1, 1000)
										self.assertEqual(outputs.logits.shape			,      _a					)

										_SCREAMING_SNAKE_CASE     					=jnp.array([-11.10_69, -9.78_77, -8.37_77]					)

										self.assertTrue(jnp.allclose(outputs.logits[0, :3]			,      _a			,      atol=1E-4					)					)