

"""simple docstring"""




import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

      if is_vision_available():
            from transformers import MaskaFormerImageProcessor

if is_vision_available():
      from PIL import Image







class   __lowercase      :

  def __init__(	self		:      Any       ,A		:      Union[str, Any]       ,A		:      Optional[Any]=2       ,A		:      Tuple=True       ,A		:      Tuple=False       ,A		:      Optional[int]=10       ,A		:      Any=3       ,A		:      Tuple=32 * 8       ,A		:      List[Any]=32 * 8       ,A		:      int=4       ,A		:      List[Any]=64       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	Tuple        =       parent
   UpperCAmelCase__       :	Union[str, Any]        =       batch_size
   UpperCAmelCase__       :	Tuple        =       is_training
   UpperCAmelCase__       :	Optional[Any]        =       use_auxiliary_loss
   UpperCAmelCase__       :	int        =       num_queries
   UpperCAmelCase__       :	Tuple        =       num_channels
   UpperCAmelCase__       :	List[str]        =       min_size
   UpperCAmelCase__       :	Optional[Any]        =       max_size
   UpperCAmelCase__       :	Tuple        =       num_labels
   UpperCAmelCase__       :	List[str]        =       hidden_dim
   UpperCAmelCase__       :	Union[str, Any]        =       hidden_dim

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]     ).to(
       A     )

   UpperCAmelCase__       :	Optional[int]        =       torch.ones([self.batch_size, self.min_size, self.max_size]       ,device=A     )

   UpperCAmelCase__       :	Union[str, Any]        =       (
       torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]       ,device=A     ) > 0.5
   ).float()
   UpperCAmelCase__       :	Optional[Any]        =       (torch.rand((self.batch_size, self.num_labels)       ,device=A     ) > 0.5).long()

   UpperCAmelCase__       :	Dict        =       self.get_config()
   return config, pixel_values, pixel_mask, mask_labels, class_labels

  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[int]        =       MaskaFormerConfig(
       hidden_size=self.hidden_dim       ,)
   UpperCAmelCase__       :	int        =       self.num_queries
   UpperCAmelCase__       :	str        =       self.num_labels

   UpperCAmelCase__       :	List[Any]        =       [1, 1, 1, 1]
   UpperCAmelCase__       :	List[Any]        =       self.num_channels

   UpperCAmelCase__       :	List[Any]        =       64
   UpperCAmelCase__       :	str        =       128
   UpperCAmelCase__       :	int        =       self.hidden_dim
   UpperCAmelCase__       :	List[Any]        =       self.hidden_dim
   UpperCAmelCase__       :	int        =       self.hidden_dim
   return config

  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	List[str]        =       self.prepare_config_and_inputs()
   UpperCAmelCase__       :	List[Any]        =       {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
   return config, inputs_dict

  def  __lowercase							(	self		:      Optional[int]       ,A		:      Any       ,A		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       output.encoder_hidden_states
   UpperCAmelCase__       :	List[str]        =       output.pixel_decoder_hidden_states
   UpperCAmelCase__       :	Optional[Any]        =       output.transformer_decoder_hidden_states

   self.parent.assertTrue(len(A     )       ,len(config.backbone_config.depths     )     )
   self.parent.assertTrue(len(A     )       ,len(config.backbone_config.depths     )     )
   self.parent.assertTrue(len(A     )       ,config.decoder_layers     )

  def  __lowercase							(	self		:      List[Any]       ,A		:      List[Any]       ,A		:      Dict       ,A		:      Union[str, Any]       ,A		:      str=False     ):






   '''simple docstring'''
   with torch.no_grad():
    UpperCAmelCase__       :	Optional[Any]        =       MaskaFormerModel(config=A     )
    model.to(A     )
    model.eval()

    UpperCAmelCase__       :	Tuple        =       model(pixel_values=A       ,pixel_mask=A     )
    UpperCAmelCase__       :	Optional[int]        =       model(A       ,output_hidden_states=A     )

   self.parent.assertEqual(
       output.transformer_decoder_last_hidden_state.shape       ,(self.batch_size, self.num_queries, self.hidden_dim)       ,)
   # let's ensure the other two hidden state exists
   self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None     )
   self.parent.assertTrue(output.encoder_last_hidden_state is not None     )

   if output_hidden_states:
    self.check_output_hidden_state(A       ,A     )




  def  __lowercase							(	self		:      Tuple       ,A		:      List[str]       ,A		:      Dict       ,A		:      Tuple       ,A		:      Any       ,A		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       MaskaFormerForUniversalSegmentation(config=A     )
   model.to(A     )
   model.eval()

   def comm_check_on_output(A		:      str     ):
    # let's still check that all the required stuff is there
    self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None     )
    self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None     )
    self.parent.assertTrue(result.encoder_last_hidden_state is not None     )
    # okay, now we need to check the logits shape
    # due to the encoder compression, masks have a //4 spatial size
    self.parent.assertEqual(
        result.masks_queries_logits.shape       ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)       ,)
    # + 1 for null class
    self.parent.assertEqual(
        result.class_queries_logits.shape       ,(self.batch_size, self.num_queries, self.num_labels + 1)     )

   with torch.no_grad():
    UpperCAmelCase__       :	Optional[Any]        =       model(pixel_values=A       ,pixel_mask=A     )
    UpperCAmelCase__       :	Tuple        =       model(A     )

    comm_check_on_output(A     )

    UpperCAmelCase__       :	Optional[Any]        =       model(
        pixel_values=A       ,pixel_mask=A       ,mask_labels=A       ,class_labels=A     )

   comm_check_on_output(A     )

   self.parent.assertTrue(result.loss is not None     )
   self.parent.assertEqual(result.loss.shape       ,torch.Size([1]     )     )







@require_torch
class   __lowercase      (     __lowerCamelCase						,      __lowerCamelCase						,      unittest.TestCase       ):
  snake_case_												=							(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
  snake_case_												=							{"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

  snake_case_												=							False
  snake_case_												=							False
  snake_case_												=							False
  snake_case_												=							False

  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       MaskaFormerModelTester(self     )
   UpperCAmelCase__       :	Union[str, Any]        =       ConfigTester(self       ,config_class=A       ,has_text_modality=A     )

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   self.config_tester.run_common_tests()

  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	List[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()
   self.model_tester.create_and_check_maskaformer_model(A       ,**A       ,output_hidden_states=A     )

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[Any]        =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A     )

  @unittest.skip(reason="""Mask2Former does not use inputs_embeds"""     )
  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   pass

  @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""     )
  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   pass

  @unittest.skip(reason="""Mask2Former is not a generative model"""     )
  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   pass

  @unittest.skip(reason="""Mask2Former does not use token embeddings"""     )
  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   pass

  @require_torch_multi_gpu
  @unittest.skip(
      reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""     )
  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   pass

  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""     )
  def  __lowercase							(	self		:      Union[str, Any]     ):






   '''simple docstring'''
   pass

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()

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

    UpperCAmelCase__       :	Tuple        =       ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]       ,A     )

  @slow
  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
    UpperCAmelCase__       :	Union[str, Any]        =       MaskaFormerModel.from_pretrained(A     )
    self.assertIsNotNone(A     )

  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       (self.model_tester.min_size,) * 2
   UpperCAmelCase__       :	Dict        =       {
       """pixel_values""": torch.randn((2, 3, *size)       ,device=A     ),
       """mask_labels""": torch.randn((2, 10, *size)       ,device=A     ),
       """class_labels""": torch.zeros(2       ,10       ,device=A     ).long(),
   }
   UpperCAmelCase__       :	List[Any]        =       self.model_tester.get_config()

   UpperCAmelCase__       :	Union[str, Any]        =       MaskaFormerForUniversalSegmentation(A     ).to(A     )
   UpperCAmelCase__       :	List[str]        =       model(**A     )
   self.assertTrue(outputs.loss is not None     )

  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	str        =       self.model_tester.prepare_config_and_inputs_for_common()
   self.model_tester.create_and_check_maskaformer_model(A       ,**A       ,output_hidden_states=A     )

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    UpperCAmelCase__       :	Optional[int]        =       model_class(A     ).to(A     )
    UpperCAmelCase__       :	str        =       model(**A       ,output_attentions=A     )
    self.assertTrue(outputs.attentions is not None     )

  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   if not self.model_tester.is_training:
    return

   UpperCAmelCase__       :	Optional[int]        =       self.all_model_classes[1]
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	Union[str, Any]        =       self.model_tester.prepare_config_and_inputs()

   UpperCAmelCase__       :	Union[str, Any]        =       model_class(A     )
   model.to(A     )
   model.train()

   UpperCAmelCase__       :	Optional[Any]        =       model(A       ,mask_labels=A       ,class_labels=A     ).loss
   loss.backward()




  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[str]        =       self.all_model_classes[1]
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[int]        =       self.model_tester.prepare_config_and_inputs()
   UpperCAmelCase__       :	Optional[Any]        =       True
   UpperCAmelCase__       :	Optional[Any]        =       True

   UpperCAmelCase__       :	int        =       model_class(A     ).to(A     )
   model.train()

   UpperCAmelCase__       :	Tuple        =       model(A       ,mask_labels=A       ,class_labels=A     )

   UpperCAmelCase__       :	Tuple        =       outputs.encoder_hidden_states[0]
   encoder_hidden_states.retain_grad()

   UpperCAmelCase__       :	Tuple        =       outputs.pixel_decoder_hidden_states[0]
   pixel_decoder_hidden_states.retain_grad()

   UpperCAmelCase__       :	int        =       outputs.transformer_decoder_hidden_states[0]
   transformer_decoder_hidden_states.retain_grad()

   UpperCAmelCase__       :	Union[str, Any]        =       outputs.attentions[0]
   attentions.retain_grad()

   outputs.loss.backward(retain_graph=A     )

   self.assertIsNotNone(encoder_hidden_states.grad     )
   self.assertIsNotNone(pixel_decoder_hidden_states.grad     )
   self.assertIsNotNone(transformer_decoder_hidden_states.grad     )
   self.assertIsNotNone(attentions.grad     )







__UpperCAmelCase			=					1E-4
def 	lowerCAmelCase    (       ):
 '''simple docstring'''





 UpperCAmelCase__       :	Optional[int]        =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
 return image







@require_vision
@slow
class   __lowercase      (     unittest.TestCase       ):

  @cached_property
  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   return "facebook/mask2former-swin-small-coco-instance"

  @cached_property
  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints     ) if is_vision_available() else None

  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       MaskaFormerModel.from_pretrained(self.model_checkpoints     ).to(A     )
   UpperCAmelCase__       :	str        =       self.default_image_processor
   UpperCAmelCase__       :	List[Any]        =       prepare_img()
   UpperCAmelCase__       :	Tuple        =       image_processor(A       ,return_tensors="""pt"""     ).to(A     )
   UpperCAmelCase__       :	Optional[Any]        =       inputs["""pixel_values"""].shape
   # check size is divisible by 32
   self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
   # check size
   self.assertEqual(A       ,(1, 3, 384, 384)     )

   with torch.no_grad():
    UpperCAmelCase__       :	int        =       model(**A     )

   UpperCAmelCase__       :	List[Any]        =       torch.tensor(
       [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]]     ).to(A     )
   self.assertTrue(
       torch.allclose(
           outputs.encoder_last_hidden_state[0, 0, :3, :3]       ,A       ,atol=A     )     )

   UpperCAmelCase__       :	Union[str, Any]        =       torch.tensor(
       [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]]     ).to(A     )
   self.assertTrue(
       torch.allclose(
           outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]       ,A       ,atol=A     )     )

   UpperCAmelCase__       :	int        =       torch.tensor(
       [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]]     ).to(A     )
   self.assertTrue(
       torch.allclose(
           outputs.transformer_decoder_last_hidden_state[0, :3, :3]       ,A       ,atol=A     )     )

  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints     ).to(A     ).eval()
   UpperCAmelCase__       :	Union[str, Any]        =       self.default_image_processor
   UpperCAmelCase__       :	List[str]        =       prepare_img()
   UpperCAmelCase__       :	List[str]        =       image_processor(A       ,return_tensors="""pt"""     ).to(A     )
   UpperCAmelCase__       :	Optional[int]        =       inputs["""pixel_values"""].shape
   # check size is divisible by 32
   self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
   # check size
   self.assertEqual(A       ,(1, 3, 384, 384)     )

   with torch.no_grad():
    UpperCAmelCase__       :	Optional[Any]        =       model(**A     )
   # masks_queries_logits
   UpperCAmelCase__       :	Dict        =       outputs.masks_queries_logits
   self.assertEqual(
       masks_queries_logits.shape       ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)     )
   UpperCAmelCase__       :	Optional[Any]        =       [
       [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1],
       [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1],
       [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5],
   ]
   UpperCAmelCase__       :	Dict        =       torch.tensor(A     ).to(A     )
   self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       ,A       ,atol=A     )     )
   # class_queries_logits
   UpperCAmelCase__       :	Any        =       outputs.class_queries_logits
   self.assertEqual(class_queries_logits.shape       ,(1, model.config.num_queries, model.config.num_labels + 1)     )
   UpperCAmelCase__       :	str        =       torch.tensor(
       [
           [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2],
           [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3],
           [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5],
       ]     ).to(A     )
   self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       ,A       ,atol=A     )     )




  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints     ).to(A     ).eval()
   UpperCAmelCase__       :	str        =       self.default_image_processor

   UpperCAmelCase__       :	Any        =       image_processor(
       [np.zeros((3, 800, 1_333)     ), np.zeros((3, 800, 1_333)     )]       ,segmentation_maps=[np.zeros((384, 384)     ).astype(np.floataa     ), np.zeros((384, 384)     ).astype(np.floataa     )]       ,return_tensors="""pt"""       ,)

   UpperCAmelCase__       :	Tuple        =       inputs["""pixel_values"""].to(A     )
   UpperCAmelCase__       :	List[Any]        =       [el.to(A     ) for el in inputs["""mask_labels"""]]
   UpperCAmelCase__       :	Union[str, Any]        =       [el.to(A     ) for el in inputs["""class_labels"""]]

   with torch.no_grad():
    UpperCAmelCase__       :	Optional[int]        =       model(**A     )

   self.assertTrue(outputs.loss is not None     )













from __future__ import annotations

from PIL import Image

# Define glider example
__a   :							Tuple						= [
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

# Define blinker example
__a   :							Optional[Any]						= [[0, 1, 0], [0, 1, 0], [0, 1, 0]]



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      list[list[int]]     )    ->   list[list[int]]:





    """simple docstring"""

    __A       =						[]
    for i in range(len(__lowercase     )     ):
        __A       =						[]
        for j in range(len(cells[i]     )     ):
            # Get the number of live neighbours
            __A       =						0
            if i > 0 and j > 0:
                neighbour_count += cells[i - 1][j - 1]
            if i > 0:
                neighbour_count += cells[i - 1][j]
            if i > 0 and j < len(cells[i]     ) - 1:
                neighbour_count += cells[i - 1][j + 1]
            if j > 0:
                neighbour_count += cells[i][j - 1]
            if j < len(cells[i]     ) - 1:
                neighbour_count += cells[i][j + 1]
            if i < len(__lowercase     ) - 1 and j > 0:
                neighbour_count += cells[i + 1][j - 1]
            if i < len(__lowercase     ) - 1:
                neighbour_count += cells[i + 1][j]
            if i < len(__lowercase     ) - 1 and j < len(cells[i]     ) - 1:
                neighbour_count += cells[i + 1][j + 1]

            # Rules of the game of life (excerpt from Wikipedia):
            # 1. Any live cell with two or three live neighbours survives.
            # 2. Any dead cell with three live neighbours becomes a live cell.
            # 3. All other live cells die in the next generation.
            #    Similarly, all other dead cells stay dead.
            __A       =						cells[i][j] == 1
            if (
                (alive and 2 <= neighbour_count <= 3)
                or not alive
                and neighbour_count == 3
            ):
                next_generation_row.append(1     )
            else:
                next_generation_row.append(0     )

        next_generation.append(__lowercase     )
    return next_generation



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      list[list[int]]      ,					__lowercase :      int     )    ->   list[Image.Image]:





    """simple docstring"""

    __A       =						[]
    for _ in range(__lowercase     ):
        # Create output image
        __A       =						Image.new("""RGB"""      ,					(len(cells[0]     ), len(__lowercase     ))     )
        __A       =						img.load()

        # Save cells to image
        for x in range(len(__lowercase     )     ):
            for y in range(len(cells[0]     )     ):
                __A       =						2_5_5 - cells[y][x] * 2_5_5
                __A       =						(colour, colour, colour)

        # Save image
        images.append(__lowercase     )
        __A       =						new_generation(__lowercase     )
    return images


if __name__ == "__main__":
  __a   :							Optional[int]						= generate_images(GLIDER, 16)
  images[0].save("out.gif", save_all=True, append_images=images[1:])




