


import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_SCREAMING_SNAKE_CASE     :			Any        =							logging.get_logger(__name__)


_SCREAMING_SNAKE_CASE     :			str        =							{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all BART models at https://huggingface.co/models?filter=bart
_SCREAMING_SNAKE_CASE     :			Optional[Any]        =							{
    'vocab_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json',
    },
    'merges_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt',
    },
}

_SCREAMING_SNAKE_CASE     :			Optional[Any]        =							{
    'facebook/bart-base': 1_024,
    'facebook/bart-large': 1_024,
    'facebook/bart-large-mnli': 1_024,
    'facebook/bart-large-cnn': 1_024,
    'facebook/bart-large-xsum': 1_024,
    'yjernite/bart_eli5': 1_024,
}


@lru_cache()
def 							__lowerCAmelCase      (			):
 _lowercase:       Optional[Any]						=				(
     list(range(ord("!"      ) ,   ord("~"      ) + 1      )      ) + list(range(ord("¡"      ) ,   ord("¬"      ) + 1      )      ) + list(range(ord("®"      ) ,   ord("ÿ"      ) + 1      )      )
 )
 _lowercase:       int						=				bs[:]
 _lowercase:       Optional[int]						=				0
 for b in range(2**8      ):
  if b not in bs:
   bs.append(lowerCAmelCase_      )
   cs.append(2**8 + n      )
   n += 1
 _lowercase:       str						=				[chr(lowerCAmelCase_      ) for n in cs]
 return dict(zip(lowerCAmelCase_ ,   lowerCAmelCase_      )      )


def 							__lowerCAmelCase      (			__magic_name__      ):
 _lowercase:       Optional[int]						=				set()
 _lowercase:       Dict						=				word[0]
 for char in word[1:]:
  pairs.add((prev_char, char)      )
  _lowercase:       Union[str, Any]						=				char
 return pairs





class        A     (		__SCREAMING_SNAKE_CASE	):







     '''simple docstring'''







     lowerCamelCase :						Optional[Any]            =   VOCAB_FILES_NAMES
     lowerCamelCase :						Any            =   PRETRAINED_VOCAB_FILES_MAP
     lowerCamelCase :						Optional[int]            =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCamelCase :						str            =   ['''input_ids''', '''attention_mask''']

     def __init__(				self    :							List[Any]			,				_UpperCamelCase    :							Optional[int]			,				_UpperCamelCase    :							Dict			,				_UpperCamelCase    :							Optional[Any]="replace"			,				_UpperCamelCase    :							Optional[Any]="<s>"			,				_UpperCamelCase    :							Union[str, Any]="</s>"			,				_UpperCamelCase    :							List[Any]="</s>"			,				_UpperCamelCase    :							List[str]="<s>"			,				_UpperCamelCase    :							Any="<unk>"			,				_UpperCamelCase    :							Any="<pad>"			,				_UpperCamelCase    :							Any="<mask>"			,				_UpperCamelCase    :							Any=False			,				**_UpperCamelCase    :							Dict			,				):
      _lowercase:       int						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else bos_token
      _lowercase:       str						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else eos_token
      _lowercase:       str						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else sep_token
      _lowercase:       Union[str, Any]						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else cls_token
      _lowercase:       int						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else unk_token
      _lowercase:       Optional[Any]						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      _lowercase:       Any						=				AddedToken(__lowerCamelCase			,				lstrip=__lowerCamelCase			,				rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase			,				__lowerCamelCase) else mask_token

      super().__init__(
          errors=__lowerCamelCase			,				bos_token=__lowerCamelCase			,				eos_token=__lowerCamelCase			,				unk_token=__lowerCamelCase			,				sep_token=__lowerCamelCase			,				cls_token=__lowerCamelCase			,				pad_token=__lowerCamelCase			,				mask_token=__lowerCamelCase			,				add_prefix_space=__lowerCamelCase			,				**__lowerCamelCase			,				)

      with open(__lowerCamelCase			,				encoding="utf-8") as vocab_handle:
       _lowercase:       Optional[int]						=				json.load(__lowerCamelCase)
      _lowercase:       Any						=				{v: k for k, v in self.encoder.items()}
      _lowercase:       int						=				errors  # how to handle errors in decoding
      _lowercase:       List[str]						=				bytes_to_unicode()
      _lowercase:       Tuple						=				{v: k for k, v in self.byte_encoder.items()}
      with open(__lowerCamelCase			,				encoding="utf-8") as merges_handle:
       _lowercase:       Union[str, Any]						=				merges_handle.read().split("\n")[1:-1]
      _lowercase:       List[str]						=				[tuple(merge.split()) for merge in bpe_merges]
      _lowercase:       Any						=				dict(zip(__lowerCamelCase			,				range(len(__lowerCamelCase))))
      _lowercase:       Tuple						=				{}
      _lowercase:       Any						=				add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      _lowercase:       Optional[int]						=				re.compile(r"\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+")

     @property
     def 					UpperCAmelCase__       (				self    :							str):
      return len(self.encoder)

     def 					UpperCAmelCase__       (				self    :							str):
      return dict(self.encoder			,				**self.added_tokens_encoder)

     def 					UpperCAmelCase__       (				self    :							Union[str, Any]			,				_UpperCamelCase    :							Any):
      if token in self.cache:
       return self.cache[token]
      _lowercase:       str						=				tuple(__lowerCamelCase)
      _lowercase:       Union[str, Any]						=				get_pairs(__lowerCamelCase)

      if not pairs:
       return token

      while True:
       _lowercase:       Any						=				min(__lowerCamelCase			,				key=lambda _UpperCamelCase: self.bpe_ranks.get(__lowerCamelCase			,				float("inf")))
       if bigram not in self.bpe_ranks:
        break
       _lowercase					,	_lowercase:       Tuple						=				bigram
       _lowercase:       Optional[int]						=				[]
       _lowercase:       Union[str, Any]						=				0
       while i < len(__lowerCamelCase):
        try:
         _lowercase:       Tuple						=				word.index(__lowerCamelCase			,				__lowerCamelCase)
        except ValueError:
         new_word.extend(word[i:])
         break
        else:
         new_word.extend(word[i:j])
         _lowercase:       Any						=				j

        if word[i] == first and i < len(__lowerCamelCase) - 1 and word[i + 1] == second:
         new_word.append(first + second)
         i += 2
        else:
         new_word.append(word[i])
         i += 1
       _lowercase:       Dict						=				tuple(__lowerCamelCase)
       _lowercase:       str						=				new_word
       if len(__lowerCamelCase) == 1:
        break
       else:
        _lowercase:       Optional[Any]						=				get_pairs(__lowerCamelCase)
      _lowercase:       Union[str, Any]						=				" ".join(__lowerCamelCase)
      _lowercase:       Tuple						=				word
      return word

     def 					UpperCAmelCase__       (				self    :							str			,				_UpperCamelCase    :							List[Any]):
      _lowercase:       List[str]						=				[]
      for token in re.findall(self.pat			,				__lowerCamelCase):
       _lowercase:       Tuple						=				"".join(
           self.byte_encoder[b] for b in token.encode("utf-8"))  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
       bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase).split(" "))
      return bpe_tokens

     def 					UpperCAmelCase__       (				self    :							List[str]			,				_UpperCamelCase    :							List[str]):
      return self.encoder.get(__lowerCamelCase			,				self.encoder.get(self.unk_token))

     def 					UpperCAmelCase__       (				self    :							List[str]			,				_UpperCamelCase    :							Optional[Any]):
      return self.decoder.get(__lowerCamelCase)

     def 					UpperCAmelCase__       (				self    :							Optional[int]			,				_UpperCamelCase    :							Any):
      _lowercase:       str						=				"".join(__lowerCamelCase)
      _lowercase:       Optional[int]						=				bytearray([self.byte_decoder[c] for c in text]).decode("utf-8"			,				errors=self.errors)
      return text

     def 					UpperCAmelCase__       (				self    :							int			,				_UpperCamelCase    :							str			,				_UpperCamelCase    :							Optional[str] = None):
      if not os.path.isdir(__lowerCamelCase):
       logger.error(f"Vocabulary path ({save_directory}) should be a directory")
       return
      _lowercase:       Optional[int]						=				os.path.join(
          __lowerCamelCase			,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])
      _lowercase:       Optional[Any]						=				os.path.join(
          __lowerCamelCase			,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"])

      with open(__lowerCamelCase			,				"w"			,				encoding="utf-8") as f:
       f.write(json.dumps(self.encoder			,				indent=2			,				sort_keys=__lowerCamelCase			,				ensure_ascii=__lowerCamelCase) + "\n")

      _lowercase:       int						=				0
      with open(__lowerCamelCase			,				"w"			,				encoding="utf-8") as writer:
       writer.write("#version: 0.2\n")
       for bpe_tokens, token_index in sorted(self.bpe_ranks.items()			,				key=lambda _UpperCamelCase: kv[1]):
        if index != token_index:
         logger.warning(
             f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
             " Please check that the tokenizer is not corrupted!")
         _lowercase:       Optional[int]						=				token_index
        writer.write(" ".join(__lowerCamelCase) + "\n")
        index += 1

      return vocab_file, merge_file

     def 					UpperCAmelCase__       (				self    :							Tuple			,				_UpperCamelCase    :							List[int]			,				_UpperCamelCase    :							Optional[List[int]] = None):
      if token_ids_a is None:
       return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      _lowercase:       List[Any]						=				[self.cls_token_id]
      _lowercase:       List[str]						=				[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep

     def 					UpperCAmelCase__       (				self    :							Any			,				_UpperCamelCase    :							List[int]			,				_UpperCamelCase    :							Optional[List[int]] = None			,				_UpperCamelCase    :							bool = False):
      if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=__lowerCamelCase			,				token_ids_a=__lowerCamelCase			,				already_has_special_tokens=__lowerCamelCase)

      if token_ids_a is None:
       return [1] + ([0] * len(__lowerCamelCase)) + [1]
      return [1] + ([0] * len(__lowerCamelCase)) + [1, 1] + ([0] * len(__lowerCamelCase)) + [1]

     def 					UpperCAmelCase__       (				self    :							Optional[Any]			,				_UpperCamelCase    :							List[int]			,				_UpperCamelCase    :							Optional[List[int]] = None):
      _lowercase:       Tuple						=				[self.sep_token_id]
      _lowercase:       Union[str, Any]						=				[self.cls_token_id]

      if token_ids_a is None:
       return len(cls + token_ids_a + sep) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]






     def 					UpperCAmelCase__       (				self    :							Tuple			,				_UpperCamelCase    :							Optional[int]			,				_UpperCamelCase    :							List[str]=False			,				**_UpperCamelCase    :							Optional[Any]):
      _lowercase:       Dict						=				kwargs.pop("add_prefix_space"			,				self.add_prefix_space)
      if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase) > 0 and not text[0].isspace()):
       _lowercase:       Any						=				" " + text
      return (text, kwargs)






"""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, MobileNetVaModel
     from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      self.config_class(**self.inputs_dict				)
     self.parent.assertTrue(hasattr(__lowerCamelCase							,       '''tf_padding'''				)				)
     self.parent.assertTrue(hasattr(__lowerCamelCase							,       '''depth_multiplier'''				)				)



class     UpperCAmelCase    :



   def __init__(       self    :	List[str]							,       __lowerCamelCase    :	List[str]							,       __lowerCamelCase    :	Tuple=1_3							,       __lowerCamelCase    :	List[Any]=3							,       __lowerCamelCase    :	List[str]=3_2							,       __lowerCamelCase    :	Dict=0.2_5							,       __lowerCamelCase    :	Optional[Any]=8							,       __lowerCamelCase    :	Dict=True							,       __lowerCamelCase    :	List[Any]=1_0_2_4							,       __lowerCamelCase    :	Union[str, Any]=3_2							,       __lowerCamelCase    :	int="relu6"							,       __lowerCamelCase    :	Optional[int]=0.1							,       __lowerCamelCase    :	Tuple=0.0_2							,       __lowerCamelCase    :	Tuple=True							,       __lowerCamelCase    :	Dict=True							,       __lowerCamelCase    :	Union[str, Any]=1_0							,       __lowerCamelCase    :	Optional[Any]=None							,       ):



     """simple docstring"""
     _snake_case   	=      parent
     _snake_case   	=      batch_size
     _snake_case   	=      num_channels
     _snake_case   	=      image_size
     _snake_case   	=      depth_multiplier
     _snake_case   	=      min_depth
     _snake_case   	=      tf_padding
     _snake_case   	=      int(last_hidden_size * depth_multiplier				)
     _snake_case   	=      output_stride
     _snake_case   	=      hidden_act
     _snake_case   	=      classifier_dropout_prob
     _snake_case   	=      use_labels
     _snake_case   	=      is_training
     _snake_case   	=      num_labels
     _snake_case   	=      initializer_range
     _snake_case   	=      scope



   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

     _snake_case   	=      None
     _snake_case   	=      None
     if self.use_labels:
       _snake_case   	=      ids_tensor([self.batch_size]							,       self.num_labels				)
       _snake_case   	=      ids_tensor([self.batch_size, self.image_size, self.image_size]							,       self.num_labels				)

     _snake_case   	=      self.get_config()

     return config, pixel_values, labels, pixel_labels



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     return MobileNetVaConfig(
         num_channels=self.num_channels							,       image_size=self.image_size							,       depth_multiplier=self.depth_multiplier							,       min_depth=self.min_depth							,       tf_padding=self.tf_padding							,       hidden_act=self.hidden_act							,       classifier_dropout_prob=self.classifier_dropout_prob							,       initializer_range=self.initializer_range							,       )



   def    __UpperCAmelCase    (       self    :	Dict							,       __lowerCamelCase    :	Optional[int]							,       __lowerCamelCase    :	List[str]							,       __lowerCamelCase    :	Optional[int]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      MobileNetVaModel(config=__lowerCamelCase				)
     model.to(__lowerCamelCase				)
     model.eval()
     _snake_case   	=      model(__lowerCamelCase				)
     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,
         )							,       )



   def    __UpperCAmelCase    (       self    :	str							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	Union[str, Any]				):



     """simple docstring"""
     _snake_case   	=      self.num_labels
     _snake_case   	=      MobileNetVaForImageClassification(__lowerCamelCase				)
     model.to(__lowerCamelCase				)
     model.eval()
     _snake_case   	=      model(__lowerCamelCase							,       labels=__lowerCamelCase				)
     self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_labels)				)





   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     _snake_case	,     _snake_case	,     _snake_case	,     _snake_case   	=      config_and_inputs
     _snake_case   	=      {'''pixel_values''': pixel_values}
     return config, inputs_dict



@require_torch
class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,unittest.TestCase  ):
   A__		:	List[Any]           =  (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   A__		:	Optional[int]           =  (
       {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   A__		:	List[str]           =  False
   A__		:	Tuple           =  False
   A__		:	List[Any]           =  False
   A__		:	List[str]           =  False



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case   	=      MobileNetVaModelTester(self				)
     _snake_case   	=      MobileNetVaConfigTester(self							,       config_class=__lowerCamelCase							,       has_text_modality=__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     self.config_tester.run_common_tests()



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



     """simple docstring"""
     pass



   @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings'''				)
   def    __UpperCAmelCase    (       self    :	Union[str, Any]				):



     """simple docstring"""
     pass



   @unittest.skip(reason='''MobileNetV1 does not output attentions'''				)
   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     pass



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.model_tester.prepare_config_and_inputs_for_common()

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

       _snake_case   	=      ['''pixel_values''']
       self.assertListEqual(arg_names[:1]							,       __lowerCamelCase				)



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



     """simple docstring"""
     _snake_case   	=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     def check_hidden_states_output(__lowerCamelCase    :	Any							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Union[str, Any]				):
       _snake_case   	=      model_class(__lowerCamelCase				)
       model.to(__lowerCamelCase				)
       model.eval()

       with torch.no_grad():
         _snake_case   	=      model(**self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)				)

       _snake_case   	=      outputs.hidden_states

       _snake_case   	=      2_6
       self.assertEqual(len(__lowerCamelCase				)							,       __lowerCamelCase				)

     _snake_case	,     _snake_case   	=      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       _snake_case   	=      True
       check_hidden_states_output(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase				)

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

       check_hidden_states_output(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase				)





   @slow
   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _snake_case   	=      MobileNetVaModel.from_pretrained(__lowerCamelCase				)
       self.assertIsNotNone(__lowerCamelCase				)




def 			snake_case		(		)						->				int:
  _snake_case   	=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
  return image







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



   @cached_property
   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     return (
         MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224'''				) if is_vision_available() else None
     )





   @slow
   def    __UpperCAmelCase    (       self    :	Optional[int]				):



     """simple docstring"""
     _snake_case   	=      MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''				).to(__lowerCamelCase				)

     _snake_case   	=      self.default_image_processor
     _snake_case   	=      prepare_img()
     _snake_case   	=      image_processor(images=__lowerCamelCase							,       return_tensors='''pt'''				).to(__lowerCamelCase				)

     # forward pass
     with torch.no_grad():
       _snake_case   	=      model(**__lowerCamelCase				)

     # verify the logits
     _snake_case   	=      torch.Size((1, 1_0_0_1)				)
     self.assertEqual(outputs.logits.shape							,       __lowerCamelCase				)

     _snake_case   	=      torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]				).to(__lowerCamelCase				)

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





