






"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import BlipImageProcessor


class   _lowercase			(  unittest.TestCase    ):


      def __init__(     self					:						Optional[int]				, a					:						Dict				, a					:						Tuple=7				, a					:						int=3				, a					:						Dict=1_8				, a					:						Tuple=3_0				, a					:						Union[str, Any]=4_0_0				, a					:						Optional[int]=True				, a					:						int=None				, a					:						Tuple=True				, a					:						str=False				, a					:						List[str]=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]				, a					:						Optional[Any]=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]				, a					:						List[str]=True				, ):





            """simple docstring"""







            __snake_case   :     Tuple	      =size if size is not None else {'''height''': 2_0, '''width''': 2_0}
            __snake_case   :     Optional[Any]	      =parent
            __snake_case   :     Dict	      =batch_size
            __snake_case   :     Any	      =num_channels
            __snake_case   :     Optional[int]	      =image_size
            __snake_case   :     Tuple	      =min_resolution
            __snake_case   :     str	      =max_resolution
            __snake_case   :     Optional[int]	      =do_resize
            __snake_case   :     Optional[int]	      =size
            __snake_case   :     int	      =do_normalize
            __snake_case   :     Optional[int]	      =image_mean
            __snake_case   :     Dict	      =image_std
            __snake_case   :     Optional[int]	      =do_pad
            __snake_case   :     int	      =do_convert_rgb


      def _UpperCamelCase    (     self					:						Dict    ):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
                "do_convert_rgb": self.do_convert_rgb,
                "do_pad": self.do_pad,
            }







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





            """simple docstring"""







            assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

            if equal_resolution:
                  __snake_case   :     Optional[Any]	      =[]
                  for i in range(self.batch_size    ):
                        image_inputs.append(
                            np.random.randint(
                                2_5_5				, size=(self.num_channels, self.max_resolution, self.max_resolution)				, dtype=np.uinta    )    )
            else:
                  __snake_case   :     Optional[Any]	      =[]
                  for i in range(self.batch_size    ):
                        __snake_case      ,					__snake_case   :     Any	      =np.random.choice(np.arange(self.min_resolution				, self.max_resolution    )				, 2    )
                        image_inputs.append(np.random.randint(2_5_5				, size=(self.num_channels, width, height)				, dtype=np.uinta    )    )

            if not numpify and not torchify:
                  # PIL expects the channel dimension as last dimension
                  __snake_case   :     List[Any]	      =[Image.fromarray(np.moveaxis(a				, 0				, -1    )    ) for x in image_inputs]

            if torchify:
                  __snake_case   :     Optional[int]	      =[torch.from_numpy(a    ) for x in image_inputs]

            return image_inputs



@require_torch
@require_vision
class   _lowercase			(  lowerCAmelCase		,	unittest.TestCase    ):
      _a :  Optional[int]										= BlipImageProcessor if is_vision_available() else None


      def _UpperCamelCase    (     self					:						Tuple    ):





            """simple docstring"""







            __snake_case   :     str	      =BlipImageProcessingTester(self    )


      @property
      def _UpperCamelCase    (     self					:						Optional[int]    ):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase    (     self					:						List[Any]    ):





            """simple docstring"""







            __snake_case   :     Optional[int]	      =self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(a				, '''do_resize'''    )    )
            self.assertTrue(hasattr(a				, '''size'''    )    )
            self.assertTrue(hasattr(a				, '''do_normalize'''    )    )
            self.assertTrue(hasattr(a				, '''image_mean'''    )    )
            self.assertTrue(hasattr(a				, '''image_std'''    )    )
            self.assertTrue(hasattr(a				, '''do_convert_rgb'''    )    )


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





            """simple docstring"""







            pass


      def _UpperCamelCase    (     self					:						Tuple    ):





            """simple docstring"""







            __snake_case   :     List[Any]	      =self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            __snake_case   :     List[str]	      =self.image_processor_tester.prepare_inputs(equal_resolution=a    )
            for image in image_inputs:
                  self.assertIsInstance(a				, Image.Image    )

            # Test not batched input
            __snake_case   :     Optional[Any]	      =image_processor(image_inputs[0]				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )

            # Test batched
            __snake_case   :     Optional[Any]	      =image_processor(a				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )


      def _UpperCamelCase    (     self					:						Optional[int]    ):





            """simple docstring"""







            __snake_case   :     List[Any]	      =self.image_processing_class(**self.image_processor_dict    )
            # create random numpy tensors
            __snake_case   :     Tuple	      =self.image_processor_tester.prepare_inputs(equal_resolution=a				, numpify=a    )
            for image in image_inputs:
                  self.assertIsInstance(a				, np.ndarray    )

            # Test not batched input
            __snake_case   :     Optional[int]	      =image_processor(image_inputs[0]				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )

            # Test batched
            __snake_case   :     Dict	      =image_processor(a				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )







      def _UpperCamelCase    (     self					:						str    ):





            """simple docstring"""







            __snake_case   :     Tuple	      =self.image_processing_class(**self.image_processor_dict    )
            # create random PyTorch tensors
            __snake_case   :     int	      =self.image_processor_tester.prepare_inputs(equal_resolution=a				, torchify=a    )
            for image in image_inputs:
                  self.assertIsInstance(a				, torch.Tensor    )

            # Test not batched input
            __snake_case   :     int	      =image_processor(image_inputs[0]				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )

            # Test batched
            __snake_case   :     Dict	      =image_processor(a				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )



@require_torch
@require_vision
class   _lowercase			(  lowerCAmelCase		,	unittest.TestCase    ):
      _a :  Union[str, Any]										= BlipImageProcessor if is_vision_available() else None


      def _UpperCamelCase    (     self					:						Optional[int]    ):





            """simple docstring"""







            __snake_case   :     List[Any]	      =BlipImageProcessingTester(self				, num_channels=4    )
            __snake_case   :     List[str]	      =3


      @property
      def _UpperCamelCase    (     self					:						int    ):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase    (     self					:						Any    ):





            """simple docstring"""







            __snake_case   :     Dict	      =self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(a				, '''do_resize'''    )    )
            self.assertTrue(hasattr(a				, '''size'''    )    )
            self.assertTrue(hasattr(a				, '''do_normalize'''    )    )
            self.assertTrue(hasattr(a				, '''image_mean'''    )    )
            self.assertTrue(hasattr(a				, '''image_std'''    )    )
            self.assertTrue(hasattr(a				, '''do_convert_rgb'''    )    )


      def _UpperCamelCase    (     self					:						List[str]    ):





            """simple docstring"""







            pass







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





            """simple docstring"""







            __snake_case   :     Any	      =self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            __snake_case   :     Dict	      =self.image_processor_tester.prepare_inputs(equal_resolution=a    )
            for image in image_inputs:
                  self.assertIsInstance(a				, Image.Image    )

            # Test not batched input
            __snake_case   :     int	      =image_processor(image_inputs[0]				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    1,
                    self.expected_encoded_image_num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )

            # Test batched
            __snake_case   :     List[str]	      =image_processor(a				, return_tensors='''pt'''    ).pixel_values
            self.assertEqual(
                encoded_images.shape				, (
                    self.image_processor_tester.batch_size,
                    self.expected_encoded_image_num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )				, )










"""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()


