


'''simple docstring'''


import inspect
import unittest

from transformers import MobileNetVaConfig
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_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
     from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor



class 						__lowerCAmelCase		(				__SCREAMING_SNAKE_CASE     ):


  '''simple docstring'''







  def 							_a				(				self			:							Tuple			):

        '''simple docstring'''




        A_    :	Dict							 =					self.config_class(**self.inputs_dict			)
        self.parent.assertTrue(hasattr(UpperCamelCase__						,"""tf_padding"""			)			)
        self.parent.assertTrue(hasattr(UpperCamelCase__						,"""depth_multiplier"""			)			)







class 						__lowerCAmelCase		:


  '''simple docstring'''







  def __init__(				self			:							Union[str, Any]						,_a			:							str						,_a			:							List[str]=13						,_a			:							List[str]=3						,_a			:							List[Any]=32						,_a			:							Optional[int]=0.25						,_a			:							int=8						,_a			:							Dict=8						,_a			:							int=6						,_a			:							Union[str, Any]=32						,_a			:							Dict=True						,_a			:							Union[str, Any]=True						,_a			:							List[str]=True						,_a			:							Any="relu6"						,_a			:							Tuple=1280						,_a			:							int=0.1						,_a			:							Optional[Any]=0.02						,_a			:							Any=True						,_a			:							Dict=True						,_a			:							int=10						,_a			:							Dict=None						,):

        '''simple docstring'''




        A_    :	Union[str, Any]							 =					parent
        A_    :	List[str]							 =					batch_size
        A_    :	Tuple							 =					num_channels
        A_    :	Tuple							 =					image_size
        A_    :	Optional[int]							 =					depth_multiplier
        A_    :	Optional[int]							 =					depth_divisible_by
        A_    :	Any							 =					min_depth
        A_    :	Dict							 =					expand_ratio
        A_    :	Any							 =					tf_padding
        A_    :	int							 =					output_stride
        A_    :	Dict							 =					first_layer_is_expansion
        A_    :	Tuple							 =					finegrained_output
        A_    :	Union[str, Any]							 =					hidden_act
        A_    :	Optional[int]							 =					last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier			)
        A_    :	int							 =					classifier_dropout_prob
        A_    :	int							 =					use_labels
        A_    :	Optional[int]							 =					is_training
        A_    :	str							 =					num_labels
        A_    :	Optional[int]							 =					initializer_range
        A_    :	Optional[int]							 =					scope






  def 							_a				(				self			:							List[str]			):

        '''simple docstring'''




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

        A_    :	str							 =					None
        A_    :	int							 =					None
        if self.use_labels:
              A_    :	str							 =					ids_tensor([self.batch_size]						,self.num_labels			)
              A_    :	List[str]							 =					ids_tensor([self.batch_size, self.image_size, self.image_size]						,self.num_labels			)

        A_    :	Union[str, Any]							 =					self.get_config()

        return config, pixel_values, labels, pixel_labels






  def 							_a				(				self			:							Optional[int]			):

        '''simple docstring'''




        return MobileNetVaConfig(
            num_channels=self.num_channels						,image_size=self.image_size						,depth_multiplier=self.depth_multiplier						,depth_divisible_by=self.depth_divisible_by						,min_depth=self.min_depth						,expand_ratio=self.expand_ratio						,output_stride=self.output_stride						,first_layer_is_expansion=self.first_layer_is_expansion						,finegrained_output=self.finegrained_output						,hidden_act=self.hidden_act						,tf_padding=self.tf_padding						,classifier_dropout_prob=self.classifier_dropout_prob						,initializer_range=self.initializer_range						,)






  def 							_a				(				self			:							int						,_a			:							Optional[Any]						,_a			:							Dict						,_a			:							List[Any]						,_a			:							Dict			):

        '''simple docstring'''




        A_    :	Any							 =					MobileNetVaModel(config=UpperCamelCase__			)
        model.to(UpperCamelCase__			)
        model.eval()
        A_    :	Dict							 =					model(UpperCamelCase__			)
        self.parent.assertEqual(
            result.last_hidden_state.shape						,(
                self.batch_size,
                self.last_hidden_size,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )						,)
        self.parent.assertEqual(
            result.pooler_output.shape						,(self.batch_size, self.last_hidden_size)						,)






  def 							_a				(				self			:							Optional[int]						,_a			:							Optional[Any]						,_a			:							List[Any]						,_a			:							Optional[Any]						,_a			:							Tuple			):

        '''simple docstring'''




        A_    :	Optional[Any]							 =					self.num_labels
        A_    :	Optional[int]							 =					MobileNetVaForImageClassification(UpperCamelCase__			)
        model.to(UpperCamelCase__			)
        model.eval()
        A_    :	Union[str, Any]							 =					model(UpperCamelCase__						,labels=UpperCamelCase__			)
        self.parent.assertEqual(result.logits.shape						,(self.batch_size, self.num_labels)			)






  def 							_a				(				self			:							List[str]						,_a			:							int						,_a			:							Optional[Any]						,_a			:							List[str]						,_a			:							List[str]			):

        '''simple docstring'''




        A_    :	Optional[int]							 =					self.num_labels
        A_    :	List[Any]							 =					MobileNetVaForSemanticSegmentation(UpperCamelCase__			)
        model.to(UpperCamelCase__			)
        model.eval()
        A_    :	List[Any]							 =					model(UpperCamelCase__			)
        self.parent.assertEqual(
            result.logits.shape						,(
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )						,)
        A_    :	int							 =					model(UpperCamelCase__						,labels=UpperCamelCase__			)
        self.parent.assertEqual(
            result.logits.shape						,(
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )						,)






  def 							_a				(				self			:							Dict			):

        '''simple docstring'''




        A_    :	Dict							 =					self.prepare_config_and_inputs()
        A_    :	List[str]							 =					config_and_inputs
        A_    :	Optional[Any]							 =					{'''pixel_values''': pixel_values}
        return config, inputs_dict







@require_torch
class 						__lowerCAmelCase		(				__SCREAMING_SNAKE_CASE	,			__SCREAMING_SNAKE_CASE	,			unittest.TestCase     ):


  '''simple docstring'''







  a_	       =				(
      (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  a_	       =				(
      {
          """feature-extraction""": MobileNetVaModel,
          """image-classification""": MobileNetVaForImageClassification,
          """image-segmentation""": MobileNetVaForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  a_	       =				False
  a_	       =				False
  a_	       =				False
  a_	       =				False






  def 							_a				(				self			:							Tuple			):

        '''simple docstring'''




        A_    :	List[Any]							 =					MobileNetVaModelTester(self			)
        A_    :	List[str]							 =					MobileNetVaConfigTester(self						,config_class=UpperCamelCase__						,has_text_modality=UpperCamelCase__			)






  def 							_a				(				self			:							Dict			):

        '''simple docstring'''




        self.config_tester.run_common_tests()






  @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds"""			)
  def 							_a				(				self			:							Any			):

        '''simple docstring'''




        pass






  @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings"""			)
  def 							_a				(				self			:							Any			):

        '''simple docstring'''




        pass






  @unittest.skip(reason="""MobileNetV2 does not output attentions"""			)
  def 							_a				(				self			:							Any			):

        '''simple docstring'''




        pass






  def 							_a				(				self			:							int			):

        '''simple docstring'''




        A_    :	Any							 =					self.model_tester.prepare_config_and_inputs_for_common()

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

              A_    :	List[str]							 =					['''pixel_values''']
              self.assertListEqual(arg_names[:1]						,UpperCamelCase__			)






  def 							_a				(				self			:							List[Any]			):

        '''simple docstring'''




        A_    :	List[str]							 =					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCamelCase__			)






  def 							_a				(				self			:							List[str]			):

        '''simple docstring'''




        def check_hidden_states_output(_a			:							Any						,_a			:							Optional[int]						,_a			:							Dict			):
              A_    :	Union[str, Any]							 =					model_class(UpperCamelCase__			)
              model.to(UpperCamelCase__			)
              model.eval()

              with torch.no_grad():
                    A_    :	List[str]							 =					model(**self._prepare_for_class(UpperCamelCase__						,UpperCamelCase__			)			)

              A_    :	str							 =					outputs.hidden_states

              A_    :	Optional[int]							 =					16
              self.assertEqual(len(UpperCamelCase__			)						,UpperCamelCase__			)

        A_    :	int							 =					self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              A_    :	int							 =					True
              check_hidden_states_output(UpperCamelCase__						,UpperCamelCase__						,UpperCamelCase__			)

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

              check_hidden_states_output(UpperCamelCase__						,UpperCamelCase__						,UpperCamelCase__			)






  def 							_a				(				self			:							str			):

        '''simple docstring'''




        A_    :	Union[str, Any]							 =					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__			)






  def 							_a				(				self			:							Optional[int]			):

        '''simple docstring'''




        A_    :	Optional[Any]							 =					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__			)






  @slow
  def 							_a				(				self			:							Tuple			):

        '''simple docstring'''




        for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              A_    :	str							 =					MobileNetVaModel.from_pretrained(UpperCamelCase__			)
              self.assertIsNotNone(UpperCamelCase__			)







def   lowerCamelCase       (   ):
      A_    :	Dict							 =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
      return image






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


  '''simple docstring'''







  @cached_property
  def 							_a				(				self			:							str			):

        '''simple docstring'''




        return (
            MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224"""			) if is_vision_available() else None
        )






  @slow
  def 							_a				(				self			:							Dict			):

        '''simple docstring'''




        A_    :	Tuple							 =					MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224"""			).to(UpperCamelCase__			)

        A_    :	str							 =					self.default_image_processor
        A_    :	List[str]							 =					prepare_img()
        A_    :	Optional[Any]							 =					image_processor(images=UpperCamelCase__						,return_tensors="""pt"""			).to(UpperCamelCase__			)

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

        # verify the logits
        A_    :	Optional[Any]							 =					torch.Size((1, 1001)			)
        self.assertEqual(outputs.logits.shape						,UpperCamelCase__			)

        A_    :	Any							 =					torch.tensor([0.2445, -1.1993, 0.1905]			).to(UpperCamelCase__			)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]						,UpperCamelCase__						,atol=1e-4			)			)






  @slow
  def 							_a				(				self			:							Tuple			):

        '''simple docstring'''




        A_    :	Union[str, Any]							 =					MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""			)
        A_    :	Any							 =					model.to(UpperCamelCase__			)

        A_    :	Tuple							 =					MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""			)

        A_    :	Dict							 =					prepare_img()
        A_    :	List[Any]							 =					image_processor(images=UpperCamelCase__						,return_tensors="""pt"""			).to(UpperCamelCase__			)

        # forward pass
        with torch.no_grad():
              A_    :	List[Any]							 =					model(**UpperCamelCase__			)
        A_    :	Tuple							 =					outputs.logits

        # verify the logits
        A_    :	Any							 =					torch.Size((1, 21, 65, 65)			)
        self.assertEqual(logits.shape						,UpperCamelCase__			)

        A_    :	Optional[Any]							 =					torch.tensor(
            [
                [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
            ]						,device=UpperCamelCase__						,)

        self.assertTrue(torch.allclose(logits[0, :3, :3, :3]						,UpperCamelCase__						,atol=1e-4			)			)


'''simple docstring'''
import os
from collections.abc import Iterator




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__ = "."			)  ->							Iterator[str]:


		'''simple docstring'''


		for dir_path, dir_names, filenames in os.walk(SCREAMING_SNAKE_CASE__			):
				snake_case  :       Optional[Any]     			=						[d for d in dir_names if d != '''scripts''' and d[0] not in '''._''']
				for filename in filenames:
						if filename == "__init__.py":
								continue
						if os.path.splitext(SCREAMING_SNAKE_CASE__			)[1] in (".py", ".ipynb"):
								yield os.path.join(SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__			).lstrip('''./'''			)




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__			)  ->							List[str]:


		'''simple docstring'''


		return F'{i * "  "}*' if i else "\n##"




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__			)  ->							str:


		'''simple docstring'''


		snake_case  :       Union[str, Any]     			=						old_path.split(os.sep			)
		for i, new_part in enumerate(new_path.split(os.sep			)			):
				if (i + 1 > len(SCREAMING_SNAKE_CASE__			) or old_parts[i] != new_part) and new_part:
						print(F'{md_prefix(SCREAMING_SNAKE_CASE__			)} {new_part.replace("_" ,       " "			).title()}'			)
		return new_path




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__ = "."			)  ->							None:


		'''simple docstring'''


		snake_case  :       List[Any]     			=						''''''
		for filepath in sorted(good_file_paths(SCREAMING_SNAKE_CASE__			)			):
				snake_case			,snake_case  :       Optional[Any]     			=						os.path.split(SCREAMING_SNAKE_CASE__			)
				if filepath != old_path:
						snake_case  :       Dict     			=						print_path(SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__			)
				snake_case  :       int     			=						(filepath.count(os.sep			) + 1) if filepath else 0
				snake_case  :       int     			=						F'{filepath}/{filename}'.replace(''' ''' ,       '''%20'''			)
				snake_case  :       int     			=						os.path.splitext(filename.replace('''_''' ,       ''' '''			).title()			)[0]
				print(F'{md_prefix(SCREAMING_SNAKE_CASE__			)} [{filename}]({url})'			)


if __name__ == "__main__":
						print_directory_md(".")


