





import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List

from ..utils import logging
from . import BaseTransformersCLICommand


try:
     from cookiecutter.main import cookiecutter

     __A             =       True
except ImportError:
     __A             =       False

__A             =       logging.get_logger(__name__)  # pylint: disable=invalid-name





def   lowerCAmelCase_				( __a	)  ->	str:







  """simple docstring"""





  return AddNewModelCommand(args.testing			,					args.testing_file			,					path=args.path	)






class      _SCREAMING_SNAKE_CASE		(			UpperCamelCase_					):







 '''simple docstring'''

 @staticmethod
 def 							SCREAMING_SNAKE_CASE_      (UpperCAmelCase_       :     List[str]) ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=parser.add_parser("add-new-model")
   add_new_model_parser.add_argument("--testing" ,				action="store_true" ,				help="If in testing mode.")
   add_new_model_parser.add_argument("--testing_file" ,				type=__a ,				help="Configuration file on which to run.")
   add_new_model_parser.add_argument(
       "--path" ,				type=__a ,				help="Path to cookiecutter. Should only be used for testing purposes.")
   add_new_model_parser.set_defaults(func=__a)

 def __init__(self       :     Union[str, Any] ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Tuple ,				UpperCAmelCase_       :     str=None ,				*UpperCAmelCase_       :     Optional[int]) ->int:



   '''simple docstring'''



   lowerCamelCase__:   Optional[int]    						=testing
   lowerCamelCase__:   List[str]    						=testing_file
   lowerCamelCase__:   Optional[Any]    						=path







 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Any:



   '''simple docstring'''



   warnings.warn(
       "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. "
       "It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality "
       "checks, you should use `transformers-cli add-new-model-like` instead.")
   if not _has_cookiecutter:
     raise ImportError(
         "Model creation dependencies are required to use the `add_new_model` command. Install them by running "
         "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n")
   # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
   lowerCamelCase__:   Any    						=[directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]]
   if len(__a) > 0:
     raise ValueError(
         "Several directories starting with `cookiecutter-template-` in current working directory. "
         "Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
         "change your working directory.")

   lowerCamelCase__:   Union[str, Any]    						=(
       Path(__a).parent.parent.parent.parent if self._path is None else Path(self._path).parent.parent
   )
   lowerCamelCase__:   str    						=path_to_transformer_root / 'templates' / 'adding_a_new_model'

   # Execute cookiecutter
   if not self._testing:
     cookiecutter(str(__a))
   else:
     with open(self._testing_file ,				"r") as configuration_file:
       lowerCamelCase__:   List[Any]    						=json.load(__a)

     cookiecutter(
         str(path_to_cookiecutter if self._path is None else self._path) ,				no_input=__a ,				extra_context=__a ,				)

   lowerCamelCase__:   Union[str, Any]    						=[directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0]

   # Retrieve configuration
   with open(directory + "/configuration.json" ,				"r") as configuration_file:
     lowerCamelCase__:   List[str]    						=json.load(__a)

   lowerCamelCase__:   Optional[Any]    						=configuration['lowercase_modelname']
   lowerCamelCase__:   List[Any]    						=configuration['generate_tensorflow_pytorch_and_flax']
   os.remove(F"""{directory}/configuration.json""")

   lowerCamelCase__:   str    						='PyTorch' in generate_tensorflow_pytorch_and_flax
   lowerCamelCase__:   str    						='TensorFlow' in generate_tensorflow_pytorch_and_flax
   lowerCamelCase__:   Any    						='Flax' in generate_tensorflow_pytorch_and_flax

   lowerCamelCase__:   Optional[Any]    						=F"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}"""
   os.makedirs(__a ,				exist_ok=__a)
   os.makedirs(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}""" ,				exist_ok=__a)

   # Tests require submodules as they have parent imports
   with open(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py""" ,				"w"):
     pass

   shutil.move(
       F"""{directory}/__init__.py""" ,				F"""{model_dir}/__init__.py""" ,				)
   shutil.move(
       F"""{directory}/configuration_{lowercase_model_name}.py""" ,				F"""{model_dir}/configuration_{lowercase_model_name}.py""" ,				)

   def remove_copy_lines(UpperCAmelCase_       :     List[Any]):
     with open(__a ,				"r") as f:
       lowerCamelCase__:   Optional[int]    						=f.readlines()
     with open(__a ,				"w") as f:
       for line in lines:
         if "# Copied from transformers." not in line:
           f.write(__a)

   if output_pytorch:
     if not self._testing:
       remove_copy_lines(F"""{directory}/modeling_{lowercase_model_name}.py""")

     shutil.move(
         F"""{directory}/modeling_{lowercase_model_name}.py""" ,				F"""{model_dir}/modeling_{lowercase_model_name}.py""" ,				)

     shutil.move(
         F"""{directory}/test_modeling_{lowercase_model_name}.py""" ,				F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py""" ,				)
   else:
     os.remove(F"""{directory}/modeling_{lowercase_model_name}.py""")
     os.remove(F"""{directory}/test_modeling_{lowercase_model_name}.py""")

   if output_tensorflow:
     if not self._testing:
       remove_copy_lines(F"""{directory}/modeling_tf_{lowercase_model_name}.py""")

     shutil.move(
         F"""{directory}/modeling_tf_{lowercase_model_name}.py""" ,				F"""{model_dir}/modeling_tf_{lowercase_model_name}.py""" ,				)

     shutil.move(
         F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" ,				F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py""" ,				)
   else:
     os.remove(F"""{directory}/modeling_tf_{lowercase_model_name}.py""")
     os.remove(F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""")

   if output_flax:
     if not self._testing:
       remove_copy_lines(F"""{directory}/modeling_flax_{lowercase_model_name}.py""")

     shutil.move(
         F"""{directory}/modeling_flax_{lowercase_model_name}.py""" ,				F"""{model_dir}/modeling_flax_{lowercase_model_name}.py""" ,				)

     shutil.move(
         F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" ,				F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py""" ,				)
   else:
     os.remove(F"""{directory}/modeling_flax_{lowercase_model_name}.py""")
     os.remove(F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""")

   shutil.move(
       F"""{directory}/{lowercase_model_name}.md""" ,				F"""{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md""" ,				)

   shutil.move(
       F"""{directory}/tokenization_{lowercase_model_name}.py""" ,				F"""{model_dir}/tokenization_{lowercase_model_name}.py""" ,				)

   shutil.move(
       F"""{directory}/tokenization_fast_{lowercase_model_name}.py""" ,				F"""{model_dir}/tokenization_{lowercase_model_name}_fast.py""" ,				)

   from os import fdopen, remove
   from shutil import copymode, move
   from tempfile import mkstemp

   def replace(UpperCAmelCase_       :     Tuple ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     int):
     # Create temp file
     lowerCamelCase__:   Any    						=mkstemp()
     lowerCamelCase__:   Any    						=False
     with fdopen(__a ,				"w") as new_file:
       with open(__a) as old_file:
         for line in old_file:
           new_file.write(__a)
           if line_to_copy_below in line:
             lowerCamelCase__:   Union[str, Any]    						=True
             for line_to_copy in lines_to_copy:
               new_file.write(__a)

     if not line_found:
       raise ValueError(F"""Line {line_to_copy_below} was not found in file.""")

     # Copy the file permissions from the old file to the new file
     copymode(__a ,				__a)
     # Remove original file
     remove(__a)
     # Move new file
     move(__a ,				__a)

   def skip_units(UpperCAmelCase_       :     Optional[Any]):
     return (
         ("generating PyTorch" in line and not output_pytorch)
         or ("generating TensorFlow" in line and not output_tensorflow)
         or ("generating Flax" in line and not output_flax)
     )

   def replace_in_files(UpperCAmelCase_       :     Union[str, Any]):
     with open(__a) as datafile:
       lowerCamelCase__:   Optional[Any]    						=[]
       lowerCamelCase__:   Optional[int]    						=False
       lowerCamelCase__:   List[Any]    						=False
       for line in datafile:
         if "# To replace in: " in line and "##" not in line:
           lowerCamelCase__:   Optional[int]    						=line.split("\"")[1]
           lowerCamelCase__:   Dict    						=skip_units(__a)
         elif "# Below: " in line and "##" not in line:
           lowerCamelCase__:   Optional[Any]    						=line.split("\"")[1]
           lowerCamelCase__:   Union[str, Any]    						=skip_units(__a)
         elif "# End." in line and "##" not in line:
           if not skip_file and not skip_snippet:
             replace(__a ,				__a ,				__a)

           lowerCamelCase__:   List[Any]    						=[]
         elif "# Replace with" in line and "##" not in line:
           lowerCamelCase__:   List[str]    						=[]
         elif "##" not in line:
           lines_to_copy.append(__a)

     remove(__a)

   replace_in_files(F"""{directory}/to_replace_{lowercase_model_name}.py""")
   os.rmdir(__a)











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      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->Tuple:



   '''simple docstring'''



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



class      _SCREAMING_SNAKE_CASE		:







 '''simple docstring'''

 def __init__(self       :     int ,				UpperCAmelCase_       :     List[str] ,				UpperCAmelCase_       :     List[Any]=13 ,				UpperCAmelCase_       :     Optional[Any]=3 ,				UpperCAmelCase_       :     Optional[Any]=32 ,				UpperCAmelCase_       :     Any=0.25 ,				UpperCAmelCase_       :     int=8 ,				UpperCAmelCase_       :     Any=8 ,				UpperCAmelCase_       :     Any=6 ,				UpperCAmelCase_       :     str=32 ,				UpperCAmelCase_       :     Any=True ,				UpperCAmelCase_       :     Any=True ,				UpperCAmelCase_       :     List[Any]=True ,				UpperCAmelCase_       :     Dict="relu6" ,				UpperCAmelCase_       :     Optional[int]=1_280 ,				UpperCAmelCase_       :     List[str]=0.1 ,				UpperCAmelCase_       :     Tuple=0.02 ,				UpperCAmelCase_       :     Optional[Any]=True ,				UpperCAmelCase_       :     Tuple=True ,				UpperCAmelCase_       :     Optional[Any]=10 ,				UpperCAmelCase_       :     Optional[int]=None ,				) ->Dict:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->str:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

   lowerCamelCase__:   Any    						=self.get_config()

   return config, pixel_values, labels, pixel_labels

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->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 							SCREAMING_SNAKE_CASE_      (self       :     int ,				UpperCAmelCase_       :     Union[str, Any] ,				UpperCAmelCase_       :     Optional[int] ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     List[str]) ->int:



   '''simple docstring'''



   lowerCamelCase__:   List[str]    						=MobileNetVaModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   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 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     List[Any] ,				UpperCAmelCase_       :     Any ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Tuple) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   int    						=self.num_labels
   lowerCamelCase__:   Optional[int]    						=MobileNetVaForImageClassification(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Tuple    						=model(UpperCAmelCase_ ,				labels=UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels))

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     Union[str, Any] ,				UpperCAmelCase_       :     Tuple ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     List[Any]) ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=self.num_labels
   lowerCamelCase__:   List[str]    						=MobileNetVaForSemanticSegmentation(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   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,
       ) ,				)
   lowerCamelCase__:   List[str]    						=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 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Any    						=self.prepare_config_and_inputs()
   lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__:   Tuple    						=config_and_inputs
   lowerCamelCase__:   Tuple    						={"pixel_values": pixel_values}
   return config, inputs_dict



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







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

 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=MobileNetVaModelTester(self)
   lowerCamelCase__:   Union[str, Any]    						=MobileNetVaConfigTester(self ,				config_class=UpperCAmelCase_ ,				has_text_modality=UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->int:



   '''simple docstring'''



   self.config_tester.run_common_tests()

 @unittest.skip(reason="MobileNetV2 does not use inputs_embeds")
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->Any:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileNetV2 does not support input and output embeddings")
 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->str:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileNetV2 does not output attentions")
 def 							SCREAMING_SNAKE_CASE_      (self       :     Union[str, Any]) ->List[Any]:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_      (self       :     str) ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__						,      lowerCamelCase__:   Tuple    						=self.model_tester.prepare_config_and_inputs_for_common()

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

     lowerCamelCase__:   Union[str, Any]    						=["pixel_values"]
     self.assertListEqual(arg_names[:1] ,				UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Optional[int]    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Any:



   '''simple docstring'''



   def check_hidden_states_output(UpperCAmelCase_       :     List[str] ,				UpperCAmelCase_       :     Optional[Any] ,				UpperCAmelCase_       :     str):
     lowerCamelCase__:   List[str]    						=model_class(UpperCAmelCase_)
     model.to(UpperCAmelCase_)
     model.eval()

     with torch.no_grad():
       lowerCamelCase__:   Any    						=model(**self._prepare_for_class(UpperCAmelCase_ ,				UpperCAmelCase_))

     lowerCamelCase__:   Optional[Any]    						=outputs.hidden_states

     lowerCamelCase__:   List[str]    						=16
     self.assertEqual(len(UpperCAmelCase_) ,				UpperCAmelCase_)

   lowerCamelCase__						,      lowerCamelCase__:   Dict    						=self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     lowerCamelCase__:   Union[str, Any]    						=True
     check_hidden_states_output(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     lowerCamelCase__:   Optional[int]    						=True

     check_hidden_states_output(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Tuple    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   int    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_)







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Union[str, Any]:



   '''simple docstring'''



   for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__:   Optional[int]    						=MobileNetVaModel.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)





def   lowerCAmelCase_				( )  ->	List[str]:







  """simple docstring"""





  lowerCamelCase__:   List[Any]    						=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
  return image






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







 '''simple docstring'''

 @cached_property
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->List[str]:



   '''simple docstring'''



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

 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224").to(UpperCAmelCase_)

   lowerCamelCase__:   Dict    						=self.default_image_processor
   lowerCamelCase__:   str    						=prepare_img()
   lowerCamelCase__:   int    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:   str    						=model(**UpperCAmelCase_)

   # verify the logits
   lowerCamelCase__:   Optional[Any]    						=torch.Size((1, 1_001))
   self.assertEqual(outputs.logits.shape ,				UpperCAmelCase_)

   lowerCamelCase__:   List[str]    						=torch.tensor([0.2445, -1.1993, 0.1905]).to(UpperCAmelCase_)

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







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:   List[Any]    						=MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")
   lowerCamelCase__:   str    						=model.to(UpperCAmelCase_)

   lowerCamelCase__:   List[Any]    						=MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")

   lowerCamelCase__:   int    						=prepare_img()
   lowerCamelCase__:   int    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:   str    						=model(**UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=outputs.logits

   # verify the logits
   lowerCamelCase__:   Optional[int]    						=torch.Size((1, 21, 65, 65))
   self.assertEqual(logits.shape ,				UpperCAmelCase_)

   lowerCamelCase__:   Union[str, 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))

