





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 UpperCAmelCase_							:


  def __init__(       self   ,__snake_case   ,__snake_case=1_3   ,__snake_case=3_2   ,__snake_case=2   ,__snake_case=3   ,__snake_case=1_6   ,__snake_case=[1, 2, 1]   ,__snake_case=[2, 2, 4]   ,__snake_case=2   ,__snake_case=2.0   ,__snake_case=True   ,__snake_case=0.0   ,__snake_case=0.0   ,__snake_case=0.1   ,__snake_case="gelu"   ,__snake_case=False   ,__snake_case=True   ,__snake_case=0.02   ,__snake_case=1E-5   ,__snake_case=True   ,__snake_case=None   ,__snake_case=True   ,__snake_case=1_0   ,__snake_case=8   ,__snake_case=["stage1", "stage2"]   ,__snake_case=[1, 2]   ,):



       """simple docstring"""





       A_					      =					parent
       A_					      =					batch_size
       A_					      =					image_size
       A_					      =					patch_size
       A_					      =					num_channels
       A_					      =					embed_dim
       A_					      =					depths
       A_					      =					num_heads
       A_					      =					window_size
       A_					      =					mlp_ratio
       A_					      =					qkv_bias
       A_					      =					hidden_dropout_prob
       A_					      =					attention_probs_dropout_prob
       A_					      =					drop_path_rate
       A_					      =					hidden_act
       A_					      =					use_absolute_embeddings
       A_					      =					patch_norm
       A_					      =					layer_norm_eps
       A_					      =					initializer_range
       A_					      =					is_training
       A_					      =					scope
       A_					      =					use_labels
       A_					      =					type_sequence_label_size
       A_					      =					encoder_stride
       A_					      =					out_features
       A_					      =					out_indices


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

       A_					      =					None
       if self.use_labels:
            A_					      =					ids_tensor([self.batch_size]   ,self.type_sequence_label_size   )

       A_					      =					self.get_config()

       return config, pixel_values, labels


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       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 	__UpperCAmelCase    (       self   ,__snake_case   ,__snake_case   ,__snake_case   ):



       """simple docstring"""





       A_					      =					SwinModel(config=__snake_case   )
       model.to(__snake_case   )
       model.eval()
       A_					      =					model(__snake_case   )

       A_					      =					((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths   ) - 1))
       A_					      =					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 	__UpperCAmelCase    (       self   ,__snake_case   ,__snake_case   ,__snake_case   ):



       """simple docstring"""





       A_					      =					SwinBackbone(config=__snake_case   )
       model.to(__snake_case   )
       model.eval()
       A_					      =					model(__snake_case   )

       # 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], 1_6, 1_6]   )

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

       # verify backbone works with out_features=None
       A_					      =					None
       A_					      =					SwinBackbone(config=__snake_case   )
       model.to(__snake_case   )
       model.eval()
       A_					      =					model(__snake_case   )

       # 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 	__UpperCAmelCase    (       self   ,__snake_case   ,__snake_case   ,__snake_case   ):



       """simple docstring"""





       A_					      =					SwinForMaskedImageModeling(config=__snake_case   )
       model.to(__snake_case   )
       model.eval()
       A_					      =					model(__snake_case   )
       self.parent.assertEqual(
           result.logits.shape   ,(self.batch_size, self.num_channels, self.image_size, self.image_size)   )

       # test greyscale images
       A_					      =					1
       A_					      =					SwinForMaskedImageModeling(__snake_case   )
       model.to(__snake_case   )
       model.eval()

       A_					      =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
       A_					      =					model(__snake_case   )
       self.parent.assertEqual(result.logits.shape   ,(self.batch_size, 1, self.image_size, self.image_size)   )


  def 	__UpperCAmelCase    (       self   ,__snake_case   ,__snake_case   ,__snake_case   ):



       """simple docstring"""





       A_					      =					self.type_sequence_label_size
       A_					      =					SwinForImageClassification(__snake_case   )
       model.to(__snake_case   )
       model.eval()
       A_					      =					model(__snake_case   ,labels=__snake_case   )
       self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.type_sequence_label_size)   )

       # test greyscale images
       A_					      =					1
       A_					      =					SwinForImageClassification(__snake_case   )
       model.to(__snake_case   )
       model.eval()

       A_					      =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
       A_					      =					model(__snake_case   )
       self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.type_sequence_label_size)   )




  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.prepare_config_and_inputs()
       (
           (
           A_
       )      ,						(
           A_
       )      ,						(
           A_
       )      ,						
       )					      =					config_and_inputs
       A_					      =					{'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_torch
class UpperCAmelCase_							(   _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE    ,		unittest.TestCase   ):
  __lowerCAmelCase      :	List[str]  	=      (
      (
          SwinModel,
          SwinBackbone,
          SwinForImageClassification,
          SwinForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  __lowerCAmelCase      :	List[Any]  	=      (
      {"""feature-extraction""": SwinModel, """image-classification""": SwinForImageClassification}
      if is_torch_available()
      else {}
  )
  __lowerCAmelCase      :	Any  	=      True

  __lowerCAmelCase      :	str  	=      False
  __lowerCAmelCase      :	Tuple  	=      False
  __lowerCAmelCase      :	int  	=      False


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					SwinModelTester(self   )
       A_					      =					ConfigTester(self   ,config_class=__snake_case   ,embed_dim=3_7   )


  def 	__UpperCAmelCase    (       self   ):



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



       """simple docstring"""





       return


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__snake_case   )


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



       """simple docstring"""





       pass


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       super().test_training_gradient_checkpointing()


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*__snake_case   )


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case   )


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__snake_case   )


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



       """simple docstring"""





       pass


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



       """simple docstring"""





       pass


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()

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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()

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

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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()
       A_					      =					True

       for model_class in self.all_model_classes:
            A_					      =					True
            A_					      =					False
            A_					      =					True
            A_					      =					model_class(__snake_case   )
            model.to(__snake_case   )
            model.eval()
            with torch.no_grad():
                 A_					      =					model(**self._prepare_for_class(__snake_case   ,__snake_case   )   )
            A_					      =					outputs.attentions
            A_					      =					len(self.model_tester.depths   )
            self.assertEqual(len(__snake_case   )   ,__snake_case   )

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

            self.assertListEqual(
                list(attentions[0].shape[-3:]   )   ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]   ,)
            A_					      =					len(__snake_case   )

            # Check attention is always last and order is fine
            A_					      =					True
            A_					      =					True
            A_					      =					model_class(__snake_case   )
            model.to(__snake_case   )
            model.eval()
            with torch.no_grad():
                 A_					      =					model(**self._prepare_for_class(__snake_case   ,__snake_case   )   )

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

            A_					      =					outputs.attentions

            self.assertEqual(len(__snake_case   )   ,__snake_case   )

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


  def 	__UpperCAmelCase    (       self   ,__snake_case   ,__snake_case   ,__snake_case   ,__snake_case   ):



       """simple docstring"""





       A_					      =					model_class(__snake_case   )
       model.to(__snake_case   )
       model.eval()

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

       A_					      =					outputs.hidden_states

       A_					      =					getattr(
           self.model_tester   ,'''expected_num_hidden_layers'''   ,len(self.model_tester.depths   ) + 1   )
       self.assertEqual(len(__snake_case   )   ,__snake_case   )

       # Swin has a different seq_length
       A_					      =					(
           config.patch_size
           if isinstance(config.patch_size   ,collections.abc.Iterable   )
           else (config.patch_size, config.patch_size)
       )

       A_					      =					(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":
            A_					      =					outputs.reshaped_hidden_states
            self.assertEqual(len(__snake_case   )   ,__snake_case   )

            A_      ,						A_      ,						A_      ,						A_					      =					reshaped_hidden_states[0].shape
            A_					      =					(
                reshaped_hidden_states[0].view(__snake_case   ,__snake_case   ,height * width   ).permute(0   ,2   ,1   )
            )
            self.assertListEqual(
                list(reshaped_hidden_states.shape[-2:]   )   ,[num_patches, self.model_tester.embed_dim]   ,)


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()

       A_					      =					(
           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:
            A_					      =					True
            self.check_hidden_states_output(__snake_case   ,__snake_case   ,__snake_case   ,__snake_case   )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            A_					      =					True

            self.check_hidden_states_output(__snake_case   ,__snake_case   ,__snake_case   ,__snake_case   )


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()
       A_					      =					3

       A_					      =					(
           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)
       )
       A_					      =					(
           config.patch_size
           if isinstance(config.patch_size   ,collections.abc.Iterable   )
           else (config.patch_size, config.patch_size)
       )

       A_					      =					image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       A_					      =					image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
            A_					      =					True
            self.check_hidden_states_output(__snake_case   ,__snake_case   ,__snake_case   ,(padded_height, padded_width)   )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            A_					      =					True
            self.check_hidden_states_output(__snake_case   ,__snake_case   ,__snake_case   ,(padded_height, padded_width)   )


  @slow
  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A_					      =					SwinModel.from_pretrained(__snake_case   )
            self.assertIsNotNone(__snake_case   )




  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_      ,						A_					      =					self.model_tester.prepare_config_and_inputs_for_common()

       A_					      =					_config_zero_init(__snake_case   )
       for model_class in self.all_model_classes:
            A_					      =					model_class(config=__snake_case   )
            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 UpperCAmelCase_							(   unittest.TestCase   ):


  @cached_property
  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       return (
           AutoImageProcessor.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''   )
           if is_vision_available()
           else None
       )




  @slow
  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					SwinForImageClassification.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''   ).to(__snake_case   )
       A_					      =					self.default_image_processor

       A_					      =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
       A_					      =					image_processor(images=__snake_case   ,return_tensors='''pt'''   ).to(__snake_case   )

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

       # verify the logits
       A_					      =					torch.Size((1, 1_0_0_0)   )
       self.assertEqual(outputs.logits.shape   ,__snake_case   )
       A_					      =					torch.tensor([-0.0948, -0.6454, -0.0921]   ).to(__snake_case   )
       self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,__snake_case   ,atol=1E-4   )   )





@require_torch
class UpperCAmelCase_							(   unittest.TestCase    ,		_SCREAMING_SNAKE_CASE   ):
  __lowerCAmelCase      :	int  	=      (SwinBackbone,) if is_torch_available() else ()
  __lowerCAmelCase      :	Union[str, Any]  	=      SwinConfig


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					SwinModelTester(self   )










# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ast
import difflib
from collections.abc import Mapping
from typing import Any, Callable, Dict





class UpperCAmelCase_							(   _SCREAMING_SNAKE_CASE   ):
  pass




def     UpperCAmelCase_						(						_UpperCAmelCase       :str     ,	_UpperCAmelCase       :Dict[str, Callable]     ,	_UpperCAmelCase       :Tuple=None     ,	_UpperCAmelCase       :Union[str, Any]=False							)  ->							Optional[int]:
     '''simple docstring'''


     try:
          A_					      =					ast.parse(_UpperCAmelCase							)
     except SyntaxError as e:
          print('''The code generated by the agent is not valid.\n'''     ,	_UpperCAmelCase							)
          return
     if state is None:
          A_					      =					{}
     A_					      =					None
     for idx, node in enumerate(expression.body							):
          try:
               A_					      =					evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
          except InterpretorError as e:
               A_					      =					f'Evaluation of the code stopped at line {idx} before the end because of the following error'
               if chat_mode:
                    msg += (
                        f'. Copy paste the following error message and send it back to the agent:\nI get an error: \'{e}\''
                    )
               else:
                    msg += f':\n{e}'
               print(_UpperCAmelCase							)
               break
          if line_result is not None:
               A_					      =					line_result

     return result

def     UpperCAmelCase_						(						_UpperCAmelCase       :ast.AST     ,	_UpperCAmelCase       :Dict[str, Any]     ,	_UpperCAmelCase       :Dict[str, Callable]							)  ->							Dict:
     '''simple docstring'''


     if isinstance(_UpperCAmelCase     ,	ast.Assign							):
          # Assignement -> we evaluate the assignement which should update the state
          # We return the variable assigned as it may be used to determine the final result.
          return evaluate_assign(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.Call							):
          # Function call -> we return the value of the function call
          return evaluate_call(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.Constant							):
          # Constant -> just return the value
          return expression.value
     elif isinstance(_UpperCAmelCase     ,	ast.Dict							):
          # Dict -> evaluate all keys and values
          A_					      =					[evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							) for k in expression.keys]
          A_					      =					[evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							) for v in expression.values]
          return dict(zip(_UpperCAmelCase     ,	_UpperCAmelCase							)							)
     elif isinstance(_UpperCAmelCase     ,	ast.Expr							):
          # Expression -> evaluate the content
          return evaluate_ast(expression.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.For							):
          # For loop -> execute the loop
          return evaluate_for(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.FormattedValue							):
          # Formatted value (part of f-string) -> evaluate the content and return
          return evaluate_ast(expression.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.If							):
          # If -> execute the right branch
          return evaluate_if(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif hasattr(_UpperCAmelCase     ,	'''Index'''							) and isinstance(_UpperCAmelCase     ,	ast.Index							):
          return evaluate_ast(expression.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.JoinedStr							):
          return "".join([str(evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)							) for v in expression.values]							)
     elif isinstance(_UpperCAmelCase     ,	ast.List							):
          # List -> evaluate all elements
          return [evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							) for elt in expression.elts]
     elif isinstance(_UpperCAmelCase     ,	ast.Name							):
          # Name -> pick up the value in the state
          return evaluate_name(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     elif isinstance(_UpperCAmelCase     ,	ast.Subscript							):
          # Subscript -> return the value of the indexing
          return evaluate_subscript(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     else:
          # For now we refuse anything else. Let's add things as we need them.
          raise InterpretorError(f'{expression.__class__.__name__} is not supported.'							)

def     UpperCAmelCase_						(						_UpperCAmelCase       :str     ,	_UpperCAmelCase       :int     ,	_UpperCAmelCase       :int							)  ->							Any:
     '''simple docstring'''


     A_					      =					assign.targets
     A_					      =					evaluate_ast(assign.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)

     if len(_UpperCAmelCase							) == 1:
          A_					      =					result
     else:
          if len(_UpperCAmelCase							) != len(_UpperCAmelCase							):
               raise InterpretorError(f'Expected {len(_UpperCAmelCase							)} values but got {len(_UpperCAmelCase							)}.'							)
          for var_name, r in zip(_UpperCAmelCase     ,	_UpperCAmelCase							):
               A_					      =					r
     return result

def     UpperCAmelCase_						(						_UpperCAmelCase       :Dict     ,	_UpperCAmelCase       :Union[str, Any]     ,	_UpperCAmelCase       :int							)  ->							Optional[Any]:
     '''simple docstring'''


     if not isinstance(call.func     ,	ast.Name							):
          raise InterpretorError(
              f'It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func} of '
              f'type {type(call.func							)}.'							)
     A_					      =					call.func.id
     if func_name not in tools:
          raise InterpretorError(
              f'It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func.id}).'							)

     A_					      =					tools[func_name]
     # Todo deal with args
     A_					      =					[evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							) for arg in call.args]
     A_					      =					{keyword.arg: evaluate_ast(keyword.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							) for keyword in call.keywords}
     return func(*_UpperCAmelCase     ,	**_UpperCAmelCase							)

def     UpperCAmelCase_						(						_UpperCAmelCase       :int     ,	_UpperCAmelCase       :Union[str, Any]     ,	_UpperCAmelCase       :Tuple							)  ->							Union[str, Any]:
     '''simple docstring'''


     A_					      =					evaluate_ast(subscript.slice     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     A_					      =					evaluate_ast(subscript.value     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     if isinstance(_UpperCAmelCase     ,	(list, tuple)							):
          return value[int(_UpperCAmelCase							)]
     if index in value:
          return value[index]
     if isinstance(_UpperCAmelCase     ,	_UpperCAmelCase							) and isinstance(_UpperCAmelCase     ,	_UpperCAmelCase							):
          A_					      =					difflib.get_close_matches(_UpperCAmelCase     ,	list(value.keys()							)							)
          if len(_UpperCAmelCase							) > 0:
               return value[close_matches[0]]

     raise InterpretorError(f'Could not index {value} with \'{index}\'.'							)

def     UpperCAmelCase_						(						_UpperCAmelCase       :Optional[Any]     ,	_UpperCAmelCase       :int     ,	_UpperCAmelCase       :Tuple							)  ->							Tuple:
     '''simple docstring'''


     if name.id in state:
          return state[name.id]
     A_					      =					difflib.get_close_matches(name.id     ,	list(state.keys()							)							)
     if len(_UpperCAmelCase							) > 0:
          return state[close_matches[0]]
     raise InterpretorError(f'The variable `{name.id}` is not defined.'							)

def     UpperCAmelCase_						(						_UpperCAmelCase       :Optional[int]     ,	_UpperCAmelCase       :Union[str, Any]     ,	_UpperCAmelCase       :str							)  ->							Optional[int]:
     '''simple docstring'''


     if len(condition.ops							) > 1:
          raise InterpretorError('''Cannot evaluate conditions with multiple operators'''							)

     A_					      =					evaluate_ast(condition.left     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     A_					      =					condition.ops[0]
     A_					      =					evaluate_ast(condition.comparators[0]     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)

     if isinstance(_UpperCAmelCase     ,	ast.Eq							):
          return left == right
     elif isinstance(_UpperCAmelCase     ,	ast.NotEq							):
          return left != right
     elif isinstance(_UpperCAmelCase     ,	ast.Lt							):
          return left < right
     elif isinstance(_UpperCAmelCase     ,	ast.LtE							):
          return left <= right
     elif isinstance(_UpperCAmelCase     ,	ast.Gt							):
          return left > right
     elif isinstance(_UpperCAmelCase     ,	ast.GtE							):
          return left >= right
     elif isinstance(_UpperCAmelCase     ,	ast.Is							):
          return left is right
     elif isinstance(_UpperCAmelCase     ,	ast.IsNot							):
          return left is not right
     elif isinstance(_UpperCAmelCase     ,	ast.In							):
          return left in right
     elif isinstance(_UpperCAmelCase     ,	ast.NotIn							):
          return left not in right
     else:
          raise InterpretorError(f'Operator not supported: {comparator}'							)

def     UpperCAmelCase_						(						_UpperCAmelCase       :Optional[Any]     ,	_UpperCAmelCase       :str     ,	_UpperCAmelCase       :List[Any]							)  ->							Optional[Any]:
     '''simple docstring'''


     A_					      =					None
     if evaluate_condition(if_statement.test     ,	_UpperCAmelCase     ,	_UpperCAmelCase							):
          for line in if_statement.body:
               A_					      =					evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
               if line_result is not None:
                    A_					      =					line_result
     else:
          for line in if_statement.orelse:
               A_					      =					evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
               if line_result is not None:
                    A_					      =					line_result
     return result


def     UpperCAmelCase_						(						_UpperCAmelCase       :List[str]     ,	_UpperCAmelCase       :List[Any]     ,	_UpperCAmelCase       :Tuple							)  ->							str:
     '''simple docstring'''


     A_					      =					None
     A_					      =					evaluate_ast(for_loop.iter     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
     for counter in iterator:
          A_					      =					counter
          for expression in for_loop.body:
               A_					      =					evaluate_ast(_UpperCAmelCase     ,	_UpperCAmelCase     ,	_UpperCAmelCase							)
               if line_result is not None:
                    A_					      =					line_result
     return result



