






"""simple docstring"""

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
					from PIL import Image

					from transformers import ConvNextImageProcessor


class 	__lowerCamelCase       :





		'''simple docstring'''






		def __init__(     self							:			Union[str, Any]		,    a_							:			Tuple		,    a_							:			Optional[Any]=13		,    a_							:			List[str]=32		,    a_							:			Dict=3		,    a_							:			Dict=4		,    a_							:			Tuple=[10, 20, 30, 40]		,    a_							:			List[str]=[2, 2, 3, 2]		,    a_							:			Optional[int]=True		,    a_							:			List[str]=True		,    a_							:			str=37		,    a_							:			Tuple="gelu"		,    a_							:			int=10		,    a_							:			str=0.02		,    a_							:			Tuple=3		,    a_							:			List[Any]=None		,    ):
				lowerCAmelCase_     :							str             =    parent
				lowerCAmelCase_     :							Dict             =    batch_size
				lowerCAmelCase_     :							Tuple             =    image_size
				lowerCAmelCase_     :							Optional[Any]             =    num_channels
				lowerCAmelCase_     :							str             =    num_stages
				lowerCAmelCase_     :							int             =    hidden_sizes
				lowerCAmelCase_     :							Any             =    depths
				lowerCAmelCase_     :							Optional[int]             =    is_training
				lowerCAmelCase_     :							int             =    use_labels
				lowerCAmelCase_     :							List[str]             =    intermediate_size
				lowerCAmelCase_     :							int             =    hidden_act
				lowerCAmelCase_     :							Dict             =    type_sequence_label_size
				lowerCAmelCase_     :							List[str]             =    initializer_range
				lowerCAmelCase_     :							Optional[int]             =    scope





		def      lowerCamelCase (     self							:			Optional[Any]			):
				lowerCAmelCase_     :							Union[str, Any]             =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

				lowerCAmelCase_     :							List[str]             =    None
				if self.use_labels:
						lowerCAmelCase_     :							Dict             =    ids_tensor([self.batch_size]		,    self.type_sequence_label_size			)

				lowerCAmelCase_     :							Tuple             =    self.get_config()

				return config, pixel_values, labels





		def      lowerCamelCase (     self							:			Any			):
				return ConvNextConfig(
				    num_channels=self.num_channels		,    hidden_sizes=self.hidden_sizes		,    depths=self.depths		,    num_stages=self.num_stages		,    hidden_act=self.hidden_act		,    is_decoder=a_		,    initializer_range=self.initializer_range		,    )





		def      lowerCamelCase (     self							:			Dict		,    a_							:			Union[str, Any]		,    a_							:			Optional[int]		,    a_							:			Any			):
				lowerCAmelCase_     :							str             =    TFConvNextModel(config=a_			)
				lowerCAmelCase_     :							Any             =    model(a_		,    training=a_			)
				# expected last hidden states: B, C, H // 32, W // 32
				self.parent.assertEqual(
				    result.last_hidden_state.shape		,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)		,    )





		def      lowerCamelCase (     self							:			str		,    a_							:			Optional[int]		,    a_							:			Optional[Any]		,    a_							:			Any			):
				lowerCAmelCase_     :							Dict             =    self.type_sequence_label_size
				lowerCAmelCase_     :							Optional[int]             =    TFConvNextForImageClassification(a_			)
				lowerCAmelCase_     :							Optional[Any]             =    model(a_		,    labels=a_		,    training=a_			)
				self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.type_sequence_label_size)			)





		def      lowerCamelCase (     self							:			Dict			):
				lowerCAmelCase_     :							Union[str, Any]             =    self.prepare_config_and_inputs()
				lowerCAmelCase_       ,			lowerCAmelCase_       ,			lowerCAmelCase_     :							Union[str, Any]             =    config_and_inputs
				lowerCAmelCase_     :							Optional[Any]             =    {"pixel_values": pixel_values}
				return config, inputs_dict







@require_tf
class 	__lowerCamelCase       (				A__				,							A__				,							unittest.TestCase    ):





		'''simple docstring'''






		a_			:       str      =							(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
		a_			:       Union[str, Any]      =							(
		    {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
		    if is_tf_available()
		    else {}
		)

		a_			:       Dict      =							False
		a_			:       Tuple      =							False
		a_			:       Any      =							False
		a_			:       int      =							False
		a_			:       Dict      =							False





		def      lowerCamelCase (     self							:			int			):
				lowerCAmelCase_     :							str             =    TFConvNextModelTester(self			)
				lowerCAmelCase_     :							Union[str, Any]             =    ConfigTester(
				    self		,    config_class=a_		,    has_text_modality=a_		,    hidden_size=37		,    )





		@unittest.skip(reason="ConvNext does not use inputs_embeds"			)
		def      lowerCamelCase (     self							:			Any			):
				pass





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU"			)			) == 0		,    reason="TF does not support backprop for grouped convolutions on CPU."		,    )
		@slow
		def      lowerCamelCase (     self							:			Dict			):
				super().test_keras_fit()





		@unittest.skip(reason="ConvNext does not support input and output embeddings"			)
		def      lowerCamelCase (     self							:			str			):
				pass





		def      lowerCamelCase (     self							:			Any			):
				lowerCAmelCase_       ,			lowerCAmelCase_     :							int             =    self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowerCAmelCase_     :							Optional[int]             =    model_class(a_			)
						lowerCAmelCase_     :							Union[str, Any]             =    inspect.signature(model.call			)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						lowerCAmelCase_     :							List[Any]             =    [*signature.parameters.keys()]

						lowerCAmelCase_     :							Union[str, Any]             =    ["pixel_values"]
						self.assertListEqual(arg_names[:1]		,    a_			)





		def      lowerCamelCase (     self							:			Optional[int]			):
				lowerCAmelCase_     :							Optional[Any]             =    self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a_			)





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU"			)			) == 0		,    reason="TF does not support backprop for grouped convolutions on CPU."		,    )
		def      lowerCamelCase (     self							:			Optional[int]			):
				super().test_dataset_conversion()





		def      lowerCamelCase (     self							:			int			):
				def check_hidden_states_output(a_							:			List[Any]		,    a_							:			Union[str, Any]		,    a_							:			Any			):
						lowerCAmelCase_     :							Any             =    model_class(a_			)

						lowerCAmelCase_     :							Tuple             =    model(**self._prepare_for_class(a_		,    a_			)			)
						lowerCAmelCase_     :							List[str]             =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowerCAmelCase_     :							Union[str, Any]             =    self.model_tester.num_stages
						self.assertEqual(len(a_			)		,    expected_num_stages + 1			)

						# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
						self.assertListEqual(
						    list(hidden_states[0].shape[-2:]			)		,    [self.model_tester.image_size // 4, self.model_tester.image_size // 4]		,    )

				lowerCAmelCase_       ,			lowerCAmelCase_     :							Tuple             =    self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowerCAmelCase_     :							Optional[int]             =    True
						check_hidden_states_output(a_		,    a_		,    a_			)

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						lowerCAmelCase_     :							List[str]             =    True

						check_hidden_states_output(a_		,    a_		,    a_			)





		def      lowerCamelCase (     self							:			Dict			):
				lowerCAmelCase_       ,			lowerCAmelCase_     :							List[Any]             =    self.model_tester.prepare_config_and_inputs_for_common()

				def check_equivalence(a_							:			Dict		,    a_							:			List[Any]		,    a_							:			int		,    a_							:			Tuple={}			):
						lowerCAmelCase_     :							Any             =    model(a_		,    return_dict=a_		,    **a_			)
						lowerCAmelCase_     :							List[Any]             =    model(a_		,    return_dict=a_		,    **a_			).to_tuple()

						def recursive_check(a_							:			List[str]		,    a_							:			int			):
								if isinstance(a_		,    (List, Tuple)			):
										for tuple_iterable_value, dict_iterable_value in zip(a_		,    a_			):
												recursive_check(a_		,    a_			)
								elif tuple_object is None:
										return
								else:
										self.assertTrue(
										    all(tf.equal(a_		,    a_			)			)		,    msg=(
										        "Tuple and dict output are not equal. Difference:"
										        f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object			)			)}'''
										    )		,    )

								recursive_check(a_		,    a_			)

				for model_class in self.all_model_classes:
						lowerCAmelCase_     :							Tuple             =    model_class(a_			)

						lowerCAmelCase_     :							Tuple             =    self._prepare_for_class(a_		,    a_			)
						lowerCAmelCase_     :							List[Any]             =    self._prepare_for_class(a_		,    a_			)
						check_equivalence(a_		,    a_		,    a_			)

						lowerCAmelCase_     :							Dict             =    self._prepare_for_class(a_		,    a_		,    return_labels=a_			)
						lowerCAmelCase_     :							Any             =    self._prepare_for_class(a_		,    a_		,    return_labels=a_			)
						check_equivalence(a_		,    a_		,    a_			)

						lowerCAmelCase_     :							Optional[int]             =    self._prepare_for_class(a_		,    a_			)
						lowerCAmelCase_     :							str             =    self._prepare_for_class(a_		,    a_			)
						check_equivalence(a_		,    a_		,    a_		,    {"output_hidden_states": True}			)

						lowerCAmelCase_     :							Union[str, Any]             =    self._prepare_for_class(a_		,    a_		,    return_labels=a_			)
						lowerCAmelCase_     :							str             =    self._prepare_for_class(a_		,    a_		,    return_labels=a_			)
						check_equivalence(a_		,    a_		,    a_		,    {"output_hidden_states": True}			)





		def      lowerCamelCase (     self							:			Union[str, Any]			):
				lowerCAmelCase_     :							Dict             =    self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*a_			)





		@slow
		def      lowerCamelCase (     self							:			str			):
				lowerCAmelCase_     :							Optional[Any]             =    TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"			)
				self.assertIsNotNone(a_			)







def 	__lowerCamelCase			(						)		->					int:

		"""simple docstring"""







		lowerCAmelCase_     :							Dict             =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
		return image



@require_tf
@require_vision
class 	__lowerCamelCase       (				unittest.TestCase    ):





		'''simple docstring'''






		@cached_property
		def      lowerCamelCase (     self							:			List[str]			):
				return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"			) if is_vision_available() else None





		@slow
		def      lowerCamelCase (     self							:			Any			):
				lowerCAmelCase_     :							Tuple             =    TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"			)

				lowerCAmelCase_     :							List[Any]             =    self.default_image_processor
				lowerCAmelCase_     :							Optional[int]             =    prepare_img()
				lowerCAmelCase_     :							int             =    image_processor(images=a_		,    return_tensors="tf"			)

				# forward pass
				lowerCAmelCase_     :							Union[str, Any]             =    model(**a_			)

				# verify the logits
				lowerCAmelCase_     :							str             =    tf.TensorShape((1, 10_00)			)
				self.assertEqual(outputs.logits.shape		,    a_			)

				lowerCAmelCase_     :							Any             =    tf.constant([-0.0260, -0.4739, 0.1911]			)

				tf.debugging.assert_near(outputs.logits[0, :3]		,    a_		,    atol=1e-4			)








"""simple docstring"""

from __future__ import annotations

from PIL import Image

# Define the first generation of cells
# fmt: off
lowercase__      =				[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

def 	__lowerCamelCase			(						__UpperCamelCase )		->					list[int]:

		"""simple docstring"""







		return [int(__UpperCamelCase ) for c in f'''{ruleset:08}'''[:8]]

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )		->					list[int]:

		"""simple docstring"""







		lowerCAmelCase_     :							int             =    len(cells[0] )  # 31
		lowerCAmelCase_     :							List[Any]             =    []
		for i in range(__UpperCamelCase ):
				# Get the neighbors of each cell
				# Handle neighbours outside bounds by using 0 as their value
				lowerCAmelCase_     :							List[str]             =    0 if i == 0 else cells[time][i - 1]
				lowerCAmelCase_     :							Optional[int]             =    0 if i == population - 1 else cells[time][i + 1]
				# Define a new cell and add it to the new generation
				lowerCAmelCase_     :							List[Any]             =    7 - int(f'''{left_neighbor}{cells[time][i]}{right_neighbor}'''   , 2 )
				next_generation.append(rule[situation] )
		return next_generation

def 	__lowerCamelCase			(						__UpperCamelCase )		->					Image.Image:

		"""simple docstring"""







		lowerCAmelCase_     :							List[str]             =    Image.new("RGB"   , (len(cells[0] ), len(__UpperCamelCase )) )
		lowerCAmelCase_     :							List[str]             =    img.load()
		# Generates image
		for w in range(img.width ):
				for h in range(img.height ):
						lowerCAmelCase_     :							Union[str, Any]             =    255 - int(255 * cells[h][w] )
						lowerCAmelCase_     :							List[str]             =    (color, color, color)
		return img


if __name__ == "__main__":
					lowercase__      =				bin(int(input("""Rule:\n""").strip()))[2:]
					lowercase__      =				format_ruleset(int(rule_num))
					for time in range(16):
										CELLS.append(new_generation(CELLS, rule, time))
					lowercase__      =				generate_image(CELLS)
					# Uncomment to save the image
					# img.save(f"rule_{rule_num}.png")
					img.show()
