






"""simple docstring"""





import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import EfficientNetForImageClassification, EfficientNetModel
    from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class   _lowercase			:


      def __init__(     self					:						int				, a					:						Optional[Any]				, a					:						Optional[Any]=1_3				, a					:						str=3_2				, a					:						List[str]=3				, a					:						Optional[int]=[3, 3, 5]				, a					:						List[Any]=[3_2, 1_6, 2_4]				, a					:						List[str]=[1_6, 2_4, 4_0]				, a					:						List[str]=[1, 1, 2]				, a					:						Optional[Any]=[1, 1, 2]				, a					:						int=[1, 6, 6]				, a					:						Optional[int]=True				, a					:						str=True				, a					:						Optional[Any]=3_7				, a					:						Optional[Any]="gelu"				, a					:						Union[str, Any]=1_0				, ):





            """simple docstring"""







            __snake_case   :     List[Any]	      =parent
            __snake_case   :     Optional[int]	      =batch_size
            __snake_case   :     Tuple	      =image_size
            __snake_case   :     Tuple	      =num_channels
            __snake_case   :     Optional[int]	      =kernel_sizes
            __snake_case   :     Any	      =in_channels
            __snake_case   :     Optional[int]	      =out_channels
            __snake_case   :     List[Any]	      =strides
            __snake_case   :     Optional[Any]	      =num_block_repeats
            __snake_case   :     Dict	      =expand_ratios
            __snake_case   :     Tuple	      =is_training
            __snake_case   :     List[Any]	      =hidden_act
            __snake_case   :     Tuple	      =num_labels
            __snake_case   :     Optional[int]	      =use_labels


      def _UpperCamelCase    (     self					:						Any    ):





            """simple docstring"""







            __snake_case   :     Union[str, Any]	      =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            __snake_case   :     str	      =None
            if self.use_labels:
                  __snake_case   :     Optional[int]	      =ids_tensor([self.batch_size]				, self.num_labels    )

            __snake_case   :     str	      =self.get_config()
            return config, pixel_values, labels


      def _UpperCamelCase    (     self					:						int    ):





            """simple docstring"""







            return EfficientNetConfig(
                num_channels=self.num_channels				, kernel_sizes=self.kernel_sizes				, in_channels=self.in_channels				, out_channels=self.out_channels				, strides=self.strides				, num_block_repeats=self.num_block_repeats				, expand_ratios=self.expand_ratios				, hidden_act=self.hidden_act				, num_labels=self.num_labels				, )


      def _UpperCamelCase    (     self					:						int				, a					:						List[str]				, a					:						List[Any]				, a					:						str    ):





            """simple docstring"""







            __snake_case   :     Optional[Any]	      =EfficientNetModel(config=a    )
            model.to(a    )
            model.eval()
            __snake_case   :     List[Any]	      =model(a    )
            # expected last hidden states: B, C, H // 4, W // 4
            self.parent.assertEqual(
                result.last_hidden_state.shape				, (self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)				, )


      def _UpperCamelCase    (     self					:						Dict				, a					:						List[Any]				, a					:						Union[str, Any]				, a					:						Any    ):





            """simple docstring"""







            __snake_case   :     Any	      =EfficientNetForImageClassification(a    )
            model.to(a    )
            model.eval()
            __snake_case   :     Tuple	      =model(a				, labels=a    )
            self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_labels)    )







      def _UpperCamelCase    (     self					:						str    ):





            """simple docstring"""







            __snake_case   :     Any	      =self.prepare_config_and_inputs()
            __snake_case      ,					__snake_case      ,					__snake_case   :     Union[str, Any]	      =config_and_inputs
            __snake_case   :     int	      ={'''pixel_values''': pixel_values}
            return config, inputs_dict



@require_torch
class   _lowercase			(  lowerCAmelCase		,	lowerCAmelCase		,	unittest.TestCase    ):
      _a :  Dict										= (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      _a :  List[str]										= (
          {'''feature-extraction''': EfficientNetModel, '''image-classification''': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

      _a :  int										= False
      _a :  Dict										= False
      _a :  str										= False
      _a :  Dict										= False
      _a :  Any										= False


      def _UpperCamelCase    (     self					:						int    ):





            """simple docstring"""







            __snake_case   :     str	      =EfficientNetModelTester(self    )
            __snake_case   :     Optional[int]	      =ConfigTester(
                self				, config_class=a				, has_text_modality=a				, hidden_size=3_7    )


      def _UpperCamelCase    (     self					:						Tuple    ):





            """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					:						Union[str, Any]    ):





            """simple docstring"""







            return


      @unittest.skip(reason='''EfficientNet does not use inputs_embeds'''    )
      def _UpperCamelCase    (     self					:						List[Any]    ):





            """simple docstring"""







            pass


      @unittest.skip(reason='''EfficientNet does not support input and output embeddings'''    )
      def _UpperCamelCase    (     self					:						Union[str, Any]    ):





            """simple docstring"""







            pass


      @unittest.skip(reason='''EfficientNet does not use feedforward chunking'''    )
      def _UpperCamelCase    (     self					:						Optional[Any]    ):





            """simple docstring"""







            pass


      def _UpperCamelCase    (     self					:						int    ):





            """simple docstring"""







            __snake_case      ,					__snake_case   :     Optional[Any]	      =self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __snake_case   :     Tuple	      =model_class(a    )
                  __snake_case   :     Dict	      =inspect.signature(model.forward    )
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  __snake_case   :     int	      =[*signature.parameters.keys()]

                  __snake_case   :     str	      =['''pixel_values''']
                  self.assertListEqual(arg_names[:1]				, a    )


      def _UpperCamelCase    (     self					:						Union[str, Any]    ):





            """simple docstring"""







            __snake_case   :     Optional[int]	      =self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*a    )


      def _UpperCamelCase    (     self					:						Union[str, Any]    ):





            """simple docstring"""







            def check_hidden_states_output(a					:						List[Any]				, a					:						int				, a					:						Optional[int]    ):
                  __snake_case   :     int	      =model_class(a    )
                  model.to(a    )
                  model.eval()

                  with torch.no_grad():
                        __snake_case   :     Tuple	      =model(**self._prepare_for_class(a				, a    )    )

                  __snake_case   :     List[str]	      =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                  __snake_case   :     List[Any]	      =sum(config.num_block_repeats    ) * 4
                  self.assertEqual(len(a    )				, a    )

                  # EfficientNet'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 // 2, self.model_tester.image_size // 2]				, )

            __snake_case      ,					__snake_case   :     Dict	      =self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __snake_case   :     List[Any]	      =True
                  check_hidden_states_output(a				, a				, a    )

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

                  check_hidden_states_output(a				, a				, a    )


      def _UpperCamelCase    (     self					:						Optional[int]    ):





            """simple docstring"""







            __snake_case   :     Dict	      =self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*a    )


      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''    )
      def _UpperCamelCase    (     self					:						Dict    ):





            """simple docstring"""







            pass


      @slow
      def _UpperCamelCase    (     self					:						str    ):





            """simple docstring"""







            for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __snake_case   :     str	      =EfficientNetModel.from_pretrained(a    )
                  self.assertIsNotNone(a    )







      @is_pipeline_test
      @require_vision
      @slow
      def _UpperCamelCase    (     self					:						Union[str, Any]    ):





            """simple docstring"""







            super().test_pipeline_image_classification()



def      __lowercase       (     )       ->       str:
      __snake_case   :     Any	      =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
      return image


@require_torch
@require_vision
class   _lowercase			(  unittest.TestCase    ):


      @cached_property
      def _UpperCamelCase    (     self					:						Tuple    ):





            """simple docstring"""







            return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''    ) if is_vision_available() else None







      @slow
      def _UpperCamelCase    (     self					:						Union[str, Any]    ):





            """simple docstring"""







            __snake_case   :     Optional[Any]	      =EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''    ).to(a    )

            __snake_case   :     Optional[int]	      =self.default_image_processor
            __snake_case   :     List[Any]	      =prepare_img()
            __snake_case   :     Tuple	      =image_processor(images=a				, return_tensors='''pt'''    ).to(a    )

            # forward pass
            with torch.no_grad():
                  __snake_case   :     Tuple	      =model(**a    )

            # verify the logits
            __snake_case   :     Any	      =torch.Size((1, 1_0_0_0)    )
            self.assertEqual(outputs.logits.shape				, a    )

            __snake_case   :     Any	      =torch.tensor([0.0_0_0_1, 0.0_0_0_2, 0.0_0_0_2]    ).to(a    )
            self.assertTrue(torch.allclose(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
UpperCamelCase_						:					int      				=			[[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      __lowercase       (     a			:					int			)       ->       list[int]:
      return [int(a			) for c in f'''{ruleset:08}'''[:8]]



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



def      __lowercase       (     a			:					list[list[int]]			)       ->       Image.Image:
      __snake_case   :     int	      =Image.new('''RGB'''							,		(len(cells[0]			), len(a			))			)
      __snake_case   :     List[Any]	      =img.load()
      # Generates image
      for w in range(img.width			):
            for h in range(img.height			):
                  __snake_case   :     int	      =255 - int(255 * cells[h][w]			)
                  __snake_case   :     List[str]	      =(color, color, color)
      return img


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


