code: 
  
  
  
  
  
  
  """simple docstring"""
  
  
  
  
  
  
  from __future__ import annotations
  
  import inspect
  import unittest
  
  from transformers import MobileViTConfig
  from transformers.file_utils import is_tf_available, is_vision_available
  from transformers.testing_utils import require_tf, slow
  
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
  from ...test_pipeline_mixin import PipelineTesterMixin
  
  
  if is_tf_available():
      import numpy as np
      import tensorflow as tf
  
      from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
      from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST
  
  
  if is_vision_available():
      from PIL import Image
  
      from transformers import MobileViTImageProcessor
  class 						__lowerCAmelCase   (			__UpperCAmelCase       ):
  
  
  
  
  
  
  
    '''simple docstring'''
  
  
    def 					UpperCamelCase__   (      self:		List[str]					):
       UpperCamelCase_     =self.config_class(**self.inputs_dict					)
       self.parent.assertTrue(hasattr(lowerCamelCase__				,			"hidden_sizes"					)					)
       self.parent.assertTrue(hasattr(lowerCamelCase__				,			"neck_hidden_sizes"					)					)
       self.parent.assertTrue(hasattr(lowerCamelCase__				,			"num_attention_heads"					)					)
  
  
  
  
  class 						__lowerCAmelCase   :
  
  
  
  
  
  
  
    '''simple docstring'''
  
  
    def __init__(      self:		Dict				,			UpperCamelCase_:		List[str]				,			UpperCamelCase_:		Union[str, Any]=13				,			UpperCamelCase_:		Optional[int]=32				,			UpperCamelCase_:		List[str]=2				,			UpperCamelCase_:		Union[str, Any]=3				,			UpperCamelCase_:		List[str]=640				,			UpperCamelCase_:		Optional[Any]=4				,			UpperCamelCase_:		int="silu"				,			UpperCamelCase_:		Dict=3				,			UpperCamelCase_:		List[str]=32				,			UpperCamelCase_:		List[str]=0.1				,			UpperCamelCase_:		Optional[int]=0.1				,			UpperCamelCase_:		Optional[int]=0.1				,			UpperCamelCase_:		Dict=0.02				,			UpperCamelCase_:		Optional[Any]=True				,			UpperCamelCase_:		List[Any]=True				,			UpperCamelCase_:		List[str]=10				,			UpperCamelCase_:		Optional[int]=None				,			):
       UpperCamelCase_     =parent
       UpperCamelCase_     =batch_size
       UpperCamelCase_     =image_size
       UpperCamelCase_     =patch_size
       UpperCamelCase_     =num_channels
       UpperCamelCase_     =last_hidden_size
       UpperCamelCase_     =num_attention_heads
       UpperCamelCase_     =hidden_act
       UpperCamelCase_     =conv_kernel_size
       UpperCamelCase_     =output_stride
       UpperCamelCase_     =hidden_dropout_prob
       UpperCamelCase_     =attention_probs_dropout_prob
       UpperCamelCase_     =classifier_dropout_prob
       UpperCamelCase_     =use_labels
       UpperCamelCase_     =is_training
       UpperCamelCase_     =num_labels
       UpperCamelCase_     =initializer_range
       UpperCamelCase_     =scope
    def 					UpperCamelCase__   (      self:		Optional[Any]					):
       UpperCamelCase_     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)
  
       UpperCamelCase_     =None
       UpperCamelCase_     =None
       if self.use_labels:
          UpperCamelCase_     =ids_tensor([self.batch_size]				,			self.num_labels					)
          UpperCamelCase_     =ids_tensor([self.batch_size, self.image_size, self.image_size]				,			self.num_labels					)
  
       UpperCamelCase_     =self.get_config()
  
       return config, pixel_values, labels, pixel_labels
    def 					UpperCamelCase__   (      self:		Optional[int]					):
       return MobileViTConfig(
           image_size=self.image_size				,			patch_size=self.patch_size				,			num_channels=self.num_channels				,			num_attention_heads=self.num_attention_heads				,			hidden_act=self.hidden_act				,			conv_kernel_size=self.conv_kernel_size				,			output_stride=self.output_stride				,			hidden_dropout_prob=self.hidden_dropout_prob				,			attention_probs_dropout_prob=self.attention_probs_dropout_prob				,			classifier_dropout_prob=self.classifier_dropout_prob				,			initializer_range=self.initializer_range				,			)
    def 					UpperCamelCase__   (      self:		Dict				,			UpperCamelCase_:		Tuple				,			UpperCamelCase_:		Tuple				,			UpperCamelCase_:		Any				,			UpperCamelCase_:		Tuple					):
       UpperCamelCase_     =TFMobileViTModel(config=lowerCamelCase__					)
       UpperCamelCase_     =model(lowerCamelCase__				,			training=lowerCamelCase__					)
       UpperCamelCase_     =UpperCamelCase_     =self.image_size // self.output_stride
       self.parent.assertEqual(
           result.last_hidden_state.shape				,			(self.batch_size, self.last_hidden_size, expected_height, expected_width)					)
    def 					UpperCamelCase__   (      self:		Tuple				,			UpperCamelCase_:		Optional[Any]				,			UpperCamelCase_:		Tuple				,			UpperCamelCase_:		List[str]				,			UpperCamelCase_:		Optional[Any]					):
       UpperCamelCase_     =self.num_labels
       UpperCamelCase_     =TFMobileViTForImageClassification(lowerCamelCase__					)
       UpperCamelCase_     =model(lowerCamelCase__				,			labels=lowerCamelCase__				,			training=lowerCamelCase__					)
       self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_labels)					)
    def 					UpperCamelCase__   (      self:		str				,			UpperCamelCase_:		str				,			UpperCamelCase_:		Union[str, Any]				,			UpperCamelCase_:		Any				,			UpperCamelCase_:		List[Any]					):
       UpperCamelCase_     =self.num_labels
       UpperCamelCase_     =TFMobileViTForSemanticSegmentation(lowerCamelCase__					)
       UpperCamelCase_     =UpperCamelCase_     =self.image_size // self.output_stride
  
       UpperCamelCase_     =model(lowerCamelCase__				,			training=lowerCamelCase__					)
       self.parent.assertEqual(
           result.logits.shape				,			(self.batch_size, self.num_labels, expected_height, expected_width)					)
  
       UpperCamelCase_     =model(lowerCamelCase__				,			labels=lowerCamelCase__				,			training=lowerCamelCase__					)
       self.parent.assertEqual(
           result.logits.shape				,			(self.batch_size, self.num_labels, expected_height, expected_width)					)
  
  
  
  
  
    def 					UpperCamelCase__   (      self:		Dict					):
       UpperCamelCase_     =self.prepare_config_and_inputs()
       UpperCamelCase_    ,							UpperCamelCase_    ,							UpperCamelCase_    ,							UpperCamelCase_     =config_and_inputs
       UpperCamelCase_     ={"pixel_values": pixel_values}
       return config, inputs_dict
  
  
  
  
  @require_tf
  class 						__lowerCAmelCase   (			__UpperCAmelCase       ,   __UpperCAmelCase       ,   unittest.TestCase       ):
  
  
  
  
  
  
  
    '''simple docstring'''
  
  
    __lowerCamelCase       :    Dict     	=			(
        (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
        if is_tf_available()
        else ()
    )
    __lowerCamelCase       :    Optional[int]     	=			(
        {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
        if is_tf_available()
        else {}
    )
  
    __lowerCamelCase       :    List[str]     	=			False
    __lowerCamelCase       :    List[Any]     	=			False
    __lowerCamelCase       :    Union[str, Any]     	=			False
    __lowerCamelCase       :    Optional[int]     	=			False
    __lowerCamelCase       :    Union[str, Any]     	=			False
    def 					UpperCamelCase__   (      self:		Dict					):
       UpperCamelCase_     =TFMobileViTModelTester(self					)
       UpperCamelCase_     =TFMobileViTConfigTester(self				,			config_class=lowerCamelCase__				,			has_text_modality=lowerCamelCase__					)
    def 					UpperCamelCase__   (      self:		List[Any]					):
       self.config_tester.run_common_tests()
    @unittest.skip(reason="MobileViT does not use inputs_embeds"					)
    def 					UpperCamelCase__   (      self:		List[str]					):
       pass
    @unittest.skip(reason="MobileViT does not support input and output embeddings"					)
    def 					UpperCamelCase__   (      self:		Optional[Any]					):
       pass
    @unittest.skip(reason="MobileViT does not output attentions"					)
    def 					UpperCamelCase__   (      self:		Any					):
       pass
    def 					UpperCamelCase__   (      self:		str					):
       UpperCamelCase_    ,							UpperCamelCase_     =self.model_tester.prepare_config_and_inputs_for_common()
  
       for model_class in self.all_model_classes:
          UpperCamelCase_     =model_class(lowerCamelCase__					)
          UpperCamelCase_     =inspect.signature(model.call					)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          UpperCamelCase_     =[*signature.parameters.keys()]
  
          UpperCamelCase_     =["pixel_values"]
          self.assertListEqual(arg_names[:1]				,			lowerCamelCase__					)
    def 					UpperCamelCase__   (      self:		int					):
       UpperCamelCase_     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase__					)
    def 					UpperCamelCase__   (      self:		Tuple					):
  
  
  
       def check_hidden_states_output(UpperCamelCase_:		Tuple				,			UpperCamelCase_:		Any				,			UpperCamelCase_:		List[Any]					):
          UpperCamelCase_     =model_class(lowerCamelCase__					)
  
          UpperCamelCase_     =model(**self._prepare_for_class(lowerCamelCase__				,			lowerCamelCase__					)					)
  
          UpperCamelCase_     =outputs.hidden_states
  
          UpperCamelCase_     =5
          self.assertEqual(len(lowerCamelCase__					)				,			lowerCamelCase__					)
  
          # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
          # with the width and height being successively divided by 2.
          UpperCamelCase_     =2
          for i in range(len(lowerCamelCase__					)					):
             self.assertListEqual(
                 list(hidden_states[i].shape[-2:]					)				,			[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]				,			)
             divisor *= 2
  
          self.assertEqual(self.model_tester.output_stride				,			divisor // 2					)
  
       UpperCamelCase_    ,							UpperCamelCase_     =self.model_tester.prepare_config_and_inputs_for_common()
  
       for model_class in self.all_model_classes:
          UpperCamelCase_     =True
          check_hidden_states_output(lowerCamelCase__				,			lowerCamelCase__				,			lowerCamelCase__					)
  
          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          UpperCamelCase_     =True
  
          check_hidden_states_output(lowerCamelCase__				,			lowerCamelCase__				,			lowerCamelCase__					)
    def 					UpperCamelCase__   (      self:		int					):
       UpperCamelCase_     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__					)
    def 					UpperCamelCase__   (      self:		Union[str, Any]					):
       UpperCamelCase_     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__					)
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices("GPU"					)					) == 0				,			reason="TF does not support backprop for grouped convolutions on CPU."				,			)
    def 					UpperCamelCase__   (      self:		Optional[int]					):
       super().test_dataset_conversion()
    def 					UpperCamelCase__   (      self:		Optional[int]				,			UpperCamelCase_:		int				,			UpperCamelCase_:		Union[str, Any]				,			UpperCamelCase_:		str=2e-1				,			UpperCamelCase_:		Union[str, Any]=2e-1					):
       self.assertTrue(np.allclose(lowerCamelCase__				,			lowerCamelCase__				,			atol=lowerCamelCase__				,			rtol=lowerCamelCase__					)					)
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices("GPU"					)					) == 0				,			reason="TF does not support backprop for grouped convolutions on CPU."				,			)
    @slow
    def 					UpperCamelCase__   (      self:		int					):
       UpperCamelCase_    ,							UpperCamelCase_     =self.model_tester.prepare_config_and_inputs_for_common()
  
       for model_class in self.all_model_classes:
          # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
          if model_class.__name__ != "TFMobileViTModel":
             UpperCamelCase_     =model_class(lowerCamelCase__					)
             if getattr(lowerCamelCase__				,			"hf_compute_loss"				,			lowerCamelCase__					):
                super().test_keras_fit()
    def 					UpperCamelCase__   (      self:		str					):
       UpperCamelCase_    ,							UpperCamelCase_     =self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes:
          # set an ignore index to correctly test the masked loss used in
          # `TFMobileViTForSemanticSegmentation`.
          if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
             UpperCamelCase_     =5
  
          UpperCamelCase_     =model_class(lowerCamelCase__					)
          if getattr(lowerCamelCase__				,			"hf_compute_loss"				,			lowerCamelCase__					):
             # The number of elements in the loss should be the same as the number of elements in the label
             UpperCamelCase_     =self._prepare_for_class(inputs_dict.copy()				,			lowerCamelCase__				,			return_labels=lowerCamelCase__					)
             UpperCamelCase_     =prepared_for_class[
                 sorted(prepared_for_class.keys() - inputs_dict.keys()				,			reverse=lowerCamelCase__					)[0]
             ]
             UpperCamelCase_     =added_label.shape.as_list()[:1]
  
             # Test that model correctly compute the loss with kwargs
             UpperCamelCase_     =self._prepare_for_class(inputs_dict.copy()				,			lowerCamelCase__				,			return_labels=lowerCamelCase__					)
             UpperCamelCase_     ={"input_ids", "pixel_values", "input_features"}
             UpperCamelCase_     =possible_input_names.intersection(set(lowerCamelCase__					)					).pop()
             UpperCamelCase_     =prepared_for_class.pop(lowerCamelCase__					)
  
             UpperCamelCase_     =model(lowerCamelCase__				,			**lowerCamelCase__					)[0]
             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
  
             # Test that model correctly compute the loss when we mask some positions
             UpperCamelCase_     =self._prepare_for_class(inputs_dict.copy()				,			lowerCamelCase__				,			return_labels=lowerCamelCase__					)
             UpperCamelCase_     ={"input_ids", "pixel_values", "input_features"}
             UpperCamelCase_     =possible_input_names.intersection(set(lowerCamelCase__					)					).pop()
             UpperCamelCase_     =prepared_for_class.pop(lowerCamelCase__					)
             if "labels" in prepared_for_class:
                UpperCamelCase_     =prepared_for_class["labels"].numpy()
                if len(labels.shape					) > 1 and labels.shape[1] != 1:
                   # labels[0] = -100
                   UpperCamelCase_     =tf.convert_to_tensor(lowerCamelCase__					)
                   UpperCamelCase_     =model(lowerCamelCase__				,			**lowerCamelCase__					)[0]
                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
                   self.assertTrue(not np.any(np.isnan(loss.numpy()					)					)					)
  
                  # Test that model correctly compute the loss with a dict
             UpperCamelCase_     =self._prepare_for_class(inputs_dict.copy()				,			lowerCamelCase__				,			return_labels=lowerCamelCase__					)
             UpperCamelCase_     =model(lowerCamelCase__					)[0]
             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
  
             # Test that model correctly compute the loss with a tuple
             UpperCamelCase_     =self._prepare_for_class(inputs_dict.copy()				,			lowerCamelCase__				,			return_labels=lowerCamelCase__					)
  
             # Get keys that were added with the _prepare_for_class function
             UpperCamelCase_     =prepared_for_class.keys() - inputs_dict.keys()
             UpperCamelCase_     =inspect.signature(model.call					).parameters
             UpperCamelCase_     =list(signature.keys()					)
  
             # Create a dictionary holding the location of the tensors in the tuple
             UpperCamelCase_     ={0: input_name}
             for label_key in label_keys:
                UpperCamelCase_     =signature_names.index(lowerCamelCase__					)
                UpperCamelCase_     =label_key
             UpperCamelCase_     =sorted(tuple_index_mapping.items()					)
             # Initialize a list with their default values, update the values and convert to a tuple
             UpperCamelCase_     =[]
  
             for name in signature_names:
                if name != "kwargs":
                   list_input.append(signature[name].default					)
  
             for index, value in sorted_tuple_index_mapping:
                UpperCamelCase_     =prepared_for_class[value]
  
             UpperCamelCase_     =tuple(lowerCamelCase__					)
  
             # Send to model
             UpperCamelCase_     =model(tuple_input[:-1]					)[0]
  
             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
  
  
  
  
  
    @slow
    def 					UpperCamelCase__   (      self:		List[Any]					):
  
  
  
       for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          UpperCamelCase_     =TFMobileViTModel.from_pretrained(lowerCamelCase__					)
          self.assertIsNotNone(lowerCamelCase__					)
  
  
  
  
  def 						_UpperCamelCase			(  )     ->   Tuple:
     UpperCamelCase_     =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
     return image
  @require_tf
  class 						__lowerCAmelCase   (			unittest.TestCase       ):
  
  
  
  
  
  
  
    '''simple docstring'''
  
  
    @slow
    def 					UpperCamelCase__   (      self:		int					):
       UpperCamelCase_     =TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"					)
  
       UpperCamelCase_     =MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"					)
       UpperCamelCase_     =prepare_img()
       UpperCamelCase_     =image_processor(images=lowerCamelCase__				,			return_tensors="tf"					)
  
       # forward pass
       UpperCamelCase_     =model(**lowerCamelCase__				,			training=lowerCamelCase__					)
  
       # verify the logits
       UpperCamelCase_     =tf.TensorShape((1, 1000)					)
       self.assertEqual(outputs.logits.shape				,			lowerCamelCase__					)
  
       UpperCamelCase_     =tf.constant([-1.9364, -1.2327, -0.4653]					)
  
       tf.debugging.assert_near(outputs.logits[0, :3]				,			lowerCamelCase__				,			atol=1e-4				,			rtol=1e-0_4					)
  
  
  
  
  
    @slow
    def 					UpperCamelCase__   (      self:		List[Any]					):
       UpperCamelCase_     =TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"					)
  
       UpperCamelCase_     =MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"					)
  
       UpperCamelCase_     =prepare_img()
       UpperCamelCase_     =image_processor(images=lowerCamelCase__				,			return_tensors="tf"					)
  
       # forward pass
       UpperCamelCase_     =model(inputs.pixel_values				,			training=lowerCamelCase__					)
       UpperCamelCase_     =outputs.logits
  
       # verify the logits
       UpperCamelCase_     =tf.TensorShape((1, 21, 32, 32)					)
       self.assertEqual(logits.shape				,			lowerCamelCase__					)
  
       UpperCamelCase_     =tf.constant(
           [
               [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
               [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
               [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
           ]					)
  
       tf.debugging.assert_near(logits[0, :3, :3, :3]				,			lowerCamelCase__				,			rtol=1e-4				,			atol=1e-4					)
  
style_context: 
  
  
  
  
  
  
  """simple docstring"""
  
  
  
  
  
  
  from datetime import date
  
  import requests
  
  A_			  =    "https://api.carbonintensity.org.uk/intensity"
  
  
  
  
  def 						_UpperCamelCase			(  ):
     UpperCamelCase_     =requests.get(A			).json()["data"][0]
     return last_half_hour["intensity"]["actual"]
  
  
  
  
  def 						_UpperCamelCase			(  A    ,       A			):
     return requests.get(f"""{BASE_URL}/{start}/{end}"""			).json()["data"]
  
  
  if __name__ == "__main__":
      for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
          print("from {from} to {to}: {intensity[actual]}".format(**entry))
      print(f'''{fetch_last_half_hour() = }''')
  