

import collections
import inspect
import unittest

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

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


if is_torch_available():
      import torch
      from torch import nn

      from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
      from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor


class     lowerCamelCase_   :




 def __init__( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase=13     ,     _UpperCAmelCase=32     ,     _UpperCAmelCase=2     ,     _UpperCAmelCase=3     ,     _UpperCAmelCase=16     ,     _UpperCAmelCase=[1, 2, 1]     ,     _UpperCAmelCase=[2, 2, 4]     ,     _UpperCAmelCase=2     ,     _UpperCAmelCase=2.0     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=0.0     ,     _UpperCAmelCase=0.0     ,     _UpperCAmelCase=0.1     ,     _UpperCAmelCase="gelu"     ,     _UpperCAmelCase=False     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=0.0_2     ,     _UpperCAmelCase=1E-5     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=None     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=10     ,     _UpperCAmelCase=8     ,     _UpperCAmelCase=["stage1", "stage2"]     ,     _UpperCAmelCase=[1, 2]     ,     ):
   __UpperCAmelCase  :     Dict		=    parent
   __UpperCAmelCase  :     str		=    batch_size
   __UpperCAmelCase  :     Tuple		=    image_size
   __UpperCAmelCase  :     List[str]		=    patch_size
   __UpperCAmelCase  :     Tuple		=    num_channels
   __UpperCAmelCase  :     List[str]		=    embed_dim
   __UpperCAmelCase  :     Optional[Any]		=    depths
   __UpperCAmelCase  :     Any		=    num_heads
   __UpperCAmelCase  :     List[str]		=    window_size
   __UpperCAmelCase  :     str		=    mlp_ratio
   __UpperCAmelCase  :     Union[str, Any]		=    qkv_bias
   __UpperCAmelCase  :     Dict		=    hidden_dropout_prob
   __UpperCAmelCase  :     Dict		=    attention_probs_dropout_prob
   __UpperCAmelCase  :     List[str]		=    drop_path_rate
   __UpperCAmelCase  :     Dict		=    hidden_act
   __UpperCAmelCase  :     Optional[int]		=    use_absolute_embeddings
   __UpperCAmelCase  :     Optional[int]		=    patch_norm
   __UpperCAmelCase  :     Tuple		=    layer_norm_eps
   __UpperCAmelCase  :     Any		=    initializer_range
   __UpperCAmelCase  :     Optional[int]		=    is_training
   __UpperCAmelCase  :     Optional[int]		=    scope
   __UpperCAmelCase  :     List[Any]		=    use_labels
   __UpperCAmelCase  :     List[Any]		=    type_sequence_label_size
   __UpperCAmelCase  :     Tuple		=    encoder_stride
   __UpperCAmelCase  :     Tuple		=    out_features
   __UpperCAmelCase  :     Dict		=    out_indices




 def 						a					( self       ):
   __UpperCAmelCase  :     List[Any]		=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

   __UpperCAmelCase  :     int		=    None
   if self.use_labels:
     __UpperCAmelCase  :     str		=    ids_tensor([self.batch_size]     ,     self.type_sequence_label_size       )

   __UpperCAmelCase  :     Optional[int]		=    self.get_config()

   return config, pixel_values, labels




 def 						a					( self       ):
   return SwinConfig(
       image_size=self.image_size     ,     patch_size=self.patch_size     ,     num_channels=self.num_channels     ,     embed_dim=self.embed_dim     ,     depths=self.depths     ,     num_heads=self.num_heads     ,     window_size=self.window_size     ,     mlp_ratio=self.mlp_ratio     ,     qkv_bias=self.qkv_bias     ,     hidden_dropout_prob=self.hidden_dropout_prob     ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,     drop_path_rate=self.drop_path_rate     ,     hidden_act=self.hidden_act     ,     use_absolute_embeddings=self.use_absolute_embeddings     ,     path_norm=self.patch_norm     ,     layer_norm_eps=self.layer_norm_eps     ,     initializer_range=self.initializer_range     ,     encoder_stride=self.encoder_stride     ,     out_features=self.out_features     ,     out_indices=self.out_indices     ,     )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     str		=    SwinModel(config=_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()
   __UpperCAmelCase  :     Dict		=    model(_UpperCAmelCase       )

   __UpperCAmelCase  :     Tuple		=    ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
   __UpperCAmelCase  :     int		=    int(config.embed_dim * 2 ** (len(config.depths       ) - 1)       )

   self.parent.assertEqual(result.last_hidden_state.shape     ,     (self.batch_size, expected_seq_len, expected_dim)       )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     List[Any]		=    SwinBackbone(config=_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()
   __UpperCAmelCase  :     Union[str, Any]		=    model(_UpperCAmelCase       )

   # verify hidden states
   self.parent.assertEqual(len(result.feature_maps       )     ,     len(config.out_features       )       )
   self.parent.assertListEqual(list(result.feature_maps[0].shape       )     ,     [self.batch_size, model.channels[0], 16, 16]       )

   # verify channels
   self.parent.assertEqual(len(model.channels       )     ,     len(config.out_features       )       )

   # verify backbone works with out_features=None
   __UpperCAmelCase  :     Any		=    None
   __UpperCAmelCase  :     Union[str, Any]		=    SwinBackbone(config=_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()
   __UpperCAmelCase  :     str		=    model(_UpperCAmelCase       )

   # verify feature maps
   self.parent.assertEqual(len(result.feature_maps       )     ,     1       )
   self.parent.assertListEqual(list(result.feature_maps[0].shape       )     ,     [self.batch_size, model.channels[-1], 4, 4]       )

   # verify channels
   self.parent.assertEqual(len(model.channels       )     ,     1       )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     Tuple		=    SwinForMaskedImageModeling(config=_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()
   __UpperCAmelCase  :     Optional[int]		=    model(_UpperCAmelCase       )
   self.parent.assertEqual(
       result.logits.shape     ,     (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

   # test greyscale images
   __UpperCAmelCase  :     Union[str, Any]		=    1
   __UpperCAmelCase  :     int		=    SwinForMaskedImageModeling(_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()

   __UpperCAmelCase  :     List[str]		=    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
   __UpperCAmelCase  :     Union[str, Any]		=    model(_UpperCAmelCase       )
   self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, 1, self.image_size, self.image_size)       )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     Tuple		=    self.type_sequence_label_size
   __UpperCAmelCase  :     Optional[Any]		=    SwinForImageClassification(_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()
   __UpperCAmelCase  :     Optional[Any]		=    model(_UpperCAmelCase     ,     labels=_UpperCAmelCase       )
   self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.type_sequence_label_size)       )

   # test greyscale images
   __UpperCAmelCase  :     Tuple		=    1
   __UpperCAmelCase  :     int		=    SwinForImageClassification(_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()

   __UpperCAmelCase  :     Optional[Any]		=    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
   __UpperCAmelCase  :     Tuple		=    model(_UpperCAmelCase       )
   self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.type_sequence_label_size)       )




 def 						a					( self       ):
   __UpperCAmelCase  :     Dict		=    self.prepare_config_and_inputs()
   (
       (
       __UpperCAmelCase
   ), (
       __UpperCAmelCase
   ), (
       __UpperCAmelCase
   ), 
   )  :     Union[str, Any]		=    config_and_inputs
   __UpperCAmelCase  :     Optional[Any]		=    {'pixel_values': pixel_values}
   return config, inputs_dict



@require_torch
class     lowerCamelCase_   ( _lowerCAmelCase  ,							_lowerCAmelCase  ,							unittest.TestCase):
 _lowerCAmelCase       		=  (
     (
         SwinModel,
         SwinBackbone,
         SwinForImageClassification,
         SwinForMaskedImageModeling,
     )
     if is_torch_available()
     else ()
 )
 _lowerCAmelCase       		=  (
     {'''feature-extraction''': SwinModel, '''image-classification''': SwinForImageClassification}
     if is_torch_available()
     else {}
 )
 _lowerCAmelCase       		=  True

 _lowerCAmelCase       		=  False
 _lowerCAmelCase       		=  False
 _lowerCAmelCase       		=  False




 def 						a					( self       ):
   __UpperCAmelCase  :     Union[str, Any]		=    SwinModelTester(self       )
   __UpperCAmelCase  :     Any		=    ConfigTester(self     ,     config_class=_UpperCAmelCase     ,     embed_dim=37       )




 def 						a					( self       ):
   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 						a					( self       ):
   return




 def 						a					( self       ):
   __UpperCAmelCase  :     str		=    self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_UpperCAmelCase       )




 @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'       )
 def 						a					( self       ):
   pass




 def 						a					( self       ):
   super().test_training_gradient_checkpointing()




 def 						a					( self       ):
   __UpperCAmelCase  :     Any		=    self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_backbone(*_UpperCAmelCase       )




 def 						a					( self       ):
   __UpperCAmelCase  :     List[Any]		=    self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase       )




 def 						a					( self       ):
   __UpperCAmelCase  :     List[str]		=    self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )




 @unittest.skip(reason='Swin does not use inputs_embeds'       )
 def 						a					( self       ):
   pass




 @unittest.skip(reason='Swin Transformer does not use feedforward chunking'       )
 def 						a					( self       ):
   pass




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     Union[str, Any]		=    self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __UpperCAmelCase  :     Any		=    model_class(_UpperCAmelCase       )
     self.assertIsInstance(model.get_input_embeddings()     ,     (nn.Module)       )
     __UpperCAmelCase  :     Tuple		=    model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(_UpperCAmelCase     ,     nn.Linear       )       )




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     Optional[Any]		=    self.model_tester.prepare_config_and_inputs_for_common()

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

     __UpperCAmelCase  :     Optional[Any]		=    ['pixel_values']
     self.assertListEqual(arg_names[:1]     ,     _UpperCAmelCase       )




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     Optional[int]		=    self.model_tester.prepare_config_and_inputs_for_common()
   __UpperCAmelCase  :     Dict		=    True

   for model_class in self.all_model_classes:
     __UpperCAmelCase  :     Any		=    True
     __UpperCAmelCase  :     Union[str, Any]		=    False
     __UpperCAmelCase  :     List[Any]		=    True
     __UpperCAmelCase  :     Dict		=    model_class(_UpperCAmelCase       )
     model.to(_UpperCAmelCase       )
     model.eval()
     with torch.no_grad():
       __UpperCAmelCase  :     str		=    model(**self._prepare_for_class(_UpperCAmelCase     ,     _UpperCAmelCase       )       )
     __UpperCAmelCase  :     int		=    outputs.attentions
     __UpperCAmelCase  :     int		=    len(self.model_tester.depths       )
     self.assertEqual(len(_UpperCAmelCase       )     ,     _UpperCAmelCase       )

     # check that output_attentions also work using config
     del inputs_dict["output_attentions"]
     __UpperCAmelCase  :     Any		=    True
     __UpperCAmelCase  :     Any		=    config.window_size**2
     __UpperCAmelCase  :     int		=    model_class(_UpperCAmelCase       )
     model.to(_UpperCAmelCase       )
     model.eval()
     with torch.no_grad():
       __UpperCAmelCase  :     Optional[Any]		=    model(**self._prepare_for_class(_UpperCAmelCase     ,     _UpperCAmelCase       )       )
     __UpperCAmelCase  :     Tuple		=    outputs.attentions
     self.assertEqual(len(_UpperCAmelCase       )     ,     _UpperCAmelCase       )

     self.assertListEqual(
         list(attentions[0].shape[-3:]       )     ,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]     ,     )
     __UpperCAmelCase  :     List[str]		=    len(_UpperCAmelCase       )

     # Check attention is always last and order is fine
     __UpperCAmelCase  :     Optional[int]		=    True
     __UpperCAmelCase  :     Any		=    True
     __UpperCAmelCase  :     List[Any]		=    model_class(_UpperCAmelCase       )
     model.to(_UpperCAmelCase       )
     model.eval()
     with torch.no_grad():
       __UpperCAmelCase  :     Tuple		=    model(**self._prepare_for_class(_UpperCAmelCase     ,     _UpperCAmelCase       )       )

     # also another +1 for reshaped_hidden_states
     __UpperCAmelCase  :     int		=    1 if model_class.__name__ == 'SwinBackbone' else 2
     self.assertEqual(out_len + added_hidden_states     ,     len(_UpperCAmelCase       )       )

     __UpperCAmelCase  :     Optional[int]		=    outputs.attentions

     self.assertEqual(len(_UpperCAmelCase       )     ,     _UpperCAmelCase       )

     self.assertListEqual(
         list(self_attentions[0].shape[-3:]       )     ,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]     ,     )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     List[str]		=    model_class(_UpperCAmelCase       )
   model.to(_UpperCAmelCase       )
   model.eval()

   with torch.no_grad():
     __UpperCAmelCase  :     List[Any]		=    model(**self._prepare_for_class(_UpperCAmelCase     ,     _UpperCAmelCase       )       )

   __UpperCAmelCase  :     int		=    outputs.hidden_states

   __UpperCAmelCase  :     List[str]		=    getattr(
       self.model_tester     ,     'expected_num_hidden_layers'     ,     len(self.model_tester.depths       ) + 1       )
   self.assertEqual(len(_UpperCAmelCase       )     ,     _UpperCAmelCase       )

   # Swin has a different seq_length
   __UpperCAmelCase  :     Union[str, Any]		=    (
       config.patch_size
       if isinstance(config.patch_size     ,     collections.abc.Iterable       )
       else (config.patch_size, config.patch_size)
   )

   __UpperCAmelCase  :     Optional[int]		=    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

   self.assertListEqual(
       list(hidden_states[0].shape[-2:]       )     ,     [num_patches, self.model_tester.embed_dim]     ,     )

   if not model_class.__name__ == "SwinBackbone":
     __UpperCAmelCase  :     Any		=    outputs.reshaped_hidden_states
     self.assertEqual(len(_UpperCAmelCase       )     ,     _UpperCAmelCase       )

     __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase  :     Optional[int]		=    reshaped_hidden_states[0].shape
     __UpperCAmelCase  :     Optional[Any]		=    (
         reshaped_hidden_states[0].view(_UpperCAmelCase     ,     _UpperCAmelCase     ,     height * width       ).permute(0     ,     2     ,     1       )
     )
     self.assertListEqual(
         list(reshaped_hidden_states.shape[-2:]       )     ,     [num_patches, self.model_tester.embed_dim]     ,     )




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     Union[str, Any]		=    self.model_tester.prepare_config_and_inputs_for_common()

   __UpperCAmelCase  :     int		=    (
       self.model_tester.image_size
       if isinstance(self.model_tester.image_size     ,     collections.abc.Iterable       )
       else (self.model_tester.image_size, self.model_tester.image_size)
   )

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

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

     self.check_hidden_states_output(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       )




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     List[str]		=    self.model_tester.prepare_config_and_inputs_for_common()
   __UpperCAmelCase  :     Tuple		=    3

   __UpperCAmelCase  :     Dict		=    (
       self.model_tester.image_size
       if isinstance(self.model_tester.image_size     ,     collections.abc.Iterable       )
       else (self.model_tester.image_size, self.model_tester.image_size)
   )
   __UpperCAmelCase  :     Optional[int]		=    (
       config.patch_size
       if isinstance(config.patch_size     ,     collections.abc.Iterable       )
       else (config.patch_size, config.patch_size)
   )

   __UpperCAmelCase  :     Optional[Any]		=    image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
   __UpperCAmelCase  :     str		=    image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

   for model_class in self.all_model_classes:
     __UpperCAmelCase  :     Union[str, Any]		=    True
     self.check_hidden_states_output(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     (padded_height, padded_width)       )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __UpperCAmelCase  :     int		=    True
     self.check_hidden_states_output(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     (padded_height, padded_width)       )




 @slow
 def 						a					( self       ):
   for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __UpperCAmelCase  :     Any		=    SwinModel.from_pretrained(_UpperCAmelCase       )
     self.assertIsNotNone(_UpperCAmelCase       )




 def 						a					( self       ):
   __UpperCAmelCase, __UpperCAmelCase  :     int		=    self.model_tester.prepare_config_and_inputs_for_common()

   __UpperCAmelCase  :     Any		=    _config_zero_init(_UpperCAmelCase       )
   for model_class in self.all_model_classes:
     __UpperCAmelCase  :     Optional[Any]		=    model_class(config=_UpperCAmelCase       )
     for name, param in model.named_parameters():
       if "embeddings" not in name and param.requires_grad:
         self.assertIn(
             ((param.data.mean() * 1E9).round() / 1E9).item()     ,     [0.0, 1.0]     ,     msg=F"Parameter {name} of model {model_class} seems not properly initialized"     ,     )



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




 @cached_property
 def 						a					( self       ):
   return (
       AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'       )
       if is_vision_available()
       else None
   )




 @slow
 def 						a					( self       ):
   __UpperCAmelCase  :     Any		=    SwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'       ).to(_UpperCAmelCase       )
   __UpperCAmelCase  :     List[str]		=    self.default_image_processor

   __UpperCAmelCase  :     int		=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
   __UpperCAmelCase  :     Union[str, Any]		=    image_processor(images=_UpperCAmelCase     ,     return_tensors='pt'       ).to(_UpperCAmelCase       )

   # forward pass
   with torch.no_grad():
     __UpperCAmelCase  :     str		=    model(**_UpperCAmelCase       )

   # verify the logits
   __UpperCAmelCase  :     Optional[int]		=    torch.Size((1, 1_000)       )
   self.assertEqual(outputs.logits.shape     ,     _UpperCAmelCase       )
   __UpperCAmelCase  :     int		=    torch.tensor([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]       ).to(_UpperCAmelCase       )
   self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,     _UpperCAmelCase     ,     atol=1E-4       )       )



@require_torch
class     lowerCamelCase_   ( unittest.TestCase  ,							_lowerCAmelCase):
 _lowerCAmelCase       		=  (SwinBackbone,) if is_torch_available() else ()
 _lowerCAmelCase       		=  SwinConfig




 def 						a					( self       ):
   __UpperCAmelCase  :     Union[str, Any]		=    SwinModelTester(self       )








from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any


class     lowerCamelCase_   :
 _lowerCAmelCase       		=  ('''_front''', '''_back''', '''_len''')


 @dataclass
 class     lowerCamelCase_   :
  _lowerCAmelCase       		=  None
  _lowerCAmelCase       		=  None
  _lowerCAmelCase       		=  None



 class     lowerCamelCase_   :
  _lowerCAmelCase       		=  ('''_cur''',)




  def __init__( self     ,     _UpperCAmelCase       ):
    __UpperCAmelCase  :     Tuple		=    cur




  def __iter__( self       ):
    return self




  def 						a					( self       ):
    if self._cur is None:
      # finished iterating
      raise StopIteration
    __UpperCAmelCase  :     str		=    self._cur.val
    __UpperCAmelCase  :     Dict		=    self._cur.next_node

    return val




 def __init__( self     ,     _UpperCAmelCase = None       ):
   __UpperCAmelCase  :     Any		=    None
   __UpperCAmelCase  :     Any		=    None
   __UpperCAmelCase  :     int		=    0

   if iterable is not None:
     # append every value to the deque
     for val in iterable:
       self.append(_UpperCAmelCase       )




 def 						a					( self     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     Optional[Any]		=    self._Node(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       )
   if self.is_empty():
     # front = back
     __UpperCAmelCase  :     Dict		=    node
     __UpperCAmelCase  :     List[str]		=    1
   else:
     # connect nodes
     __UpperCAmelCase  :     Any		=    node
     __UpperCAmelCase  :     Tuple		=    self._back
     __UpperCAmelCase  :     Optional[Any]		=    node  # assign new back to the new node

     self._len += 1

     # make sure there were no errors
     assert not self.is_empty(), "Error on appending value."




 def 						a					( self     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     Optional[Any]		=    self._Node(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       )
   if self.is_empty():
     # front = back
     __UpperCAmelCase  :     str		=    node
     __UpperCAmelCase  :     List[str]		=    1
   else:
     # connect nodes
     __UpperCAmelCase  :     List[str]		=    self._front
     __UpperCAmelCase  :     Any		=    node
     __UpperCAmelCase  :     Dict		=    node  # assign new front to the new node

     self._len += 1

     # make sure there were no errors
     assert not self.is_empty(), "Error on appending value."




 def 						a					( self     ,     _UpperCAmelCase       ):
   for val in iterable:
     self.append(_UpperCAmelCase       )




 def 						a					( self     ,     _UpperCAmelCase       ):
   for val in iterable:
     self.appendleft(_UpperCAmelCase       )




 def 						a					( self       ):
   assert not self.is_empty(), "Deque is empty."

   __UpperCAmelCase  :     List[Any]		=    self._back
   __UpperCAmelCase  :     Optional[int]		=    self._back.prev_node  # set new back
   # drop the last node - python will deallocate memory automatically
   __UpperCAmelCase  :     int		=    None

   self._len -= 1

   return topop.val




 def 						a					( self       ):
   assert not self.is_empty(), "Deque is empty."

   __UpperCAmelCase  :     List[Any]		=    self._front
   __UpperCAmelCase  :     Union[str, Any]		=    self._front.next_node  # set new front and drop the first node
   __UpperCAmelCase  :     Union[str, Any]		=    None

   self._len -= 1

   return topop.val




 def 						a					( self       ):
   return self._front is None




 def __len__( self       ):
   return self._len




 def __eq__( self     ,     _UpperCAmelCase       ):

   if not isinstance(_UpperCAmelCase     ,     _UpperCAmelCase       ):
     return NotImplemented

   __UpperCAmelCase  :     List[str]		=    self._front
   __UpperCAmelCase  :     str		=    other._front

   # if the length of the dequeues are not the same, they are not equal
   if len(self       ) != len(_UpperCAmelCase       ):
     return False

   while me is not None and oth is not None:
     # compare every value
     if me.val != oth.val:
       return False
     __UpperCAmelCase  :     Any		=    me.next_node
     __UpperCAmelCase  :     str		=    oth.next_node

   return True




 def __iter__( self       ):
   return Deque._Iterator(self._front       )




 def __repr__( self       ):
   __UpperCAmelCase  :     int		=    []
   __UpperCAmelCase  :     Dict		=    self._front
   while aux is not None:
     # append the values in a list to display
     values_list.append(aux.val       )
     __UpperCAmelCase  :     List[str]		=    aux.next_node

   return F"[{', '.join(repr(_UpperCAmelCase       ) for val in values_list       )}]"


if __name__ == "__main__":
      import doctest

      doctest.testmod()





