




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_      (   A       ):




							'''simple docstring'''



							def    _UpperCAmelCase     (					self       :	Any			)			->					int:
										SCREAMING_SNAKE_CASE           =					self.config_class(**self.inputs_dict			)
										self.parent.assertTrue(hasattr(a       ,     """tf_padding"""			)			)
										self.parent.assertTrue(hasattr(a       ,     """depth_multiplier"""			)			)





class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	Union[str, Any]       ,     a       :	Any       ,     a       :	int=13       ,     a       :	Optional[int]=3       ,     a       :	Optional[int]=32       ,     a       :	Union[str, Any]=0.25       ,     a       :	List[str]=8       ,     a       :	Any=True       ,     a       :	Optional[int]=1_024       ,     a       :	List[Any]=32       ,     a       :	int="relu6"       ,     a       :	Dict=0.1       ,     a       :	Dict=0.02       ,     a       :	int=True       ,     a       :	List[str]=True       ,     a       :	Optional[Any]=10       ,     a       :	Tuple=None       ,     )			->					Union[str, Any]:
										SCREAMING_SNAKE_CASE           =					parent
										SCREAMING_SNAKE_CASE           =					batch_size
										SCREAMING_SNAKE_CASE           =					num_channels
										SCREAMING_SNAKE_CASE           =					image_size
										SCREAMING_SNAKE_CASE           =					depth_multiplier
										SCREAMING_SNAKE_CASE           =					min_depth
										SCREAMING_SNAKE_CASE           =					tf_padding
										SCREAMING_SNAKE_CASE           =					int(last_hidden_size * depth_multiplier			)
										SCREAMING_SNAKE_CASE           =					output_stride
										SCREAMING_SNAKE_CASE           =					hidden_act
										SCREAMING_SNAKE_CASE           =					classifier_dropout_prob
										SCREAMING_SNAKE_CASE           =					use_labels
										SCREAMING_SNAKE_CASE           =					is_training
										SCREAMING_SNAKE_CASE           =					num_labels
										SCREAMING_SNAKE_CASE           =					initializer_range
										SCREAMING_SNAKE_CASE           =					scope





							def    _UpperCAmelCase     (					self       :	Tuple			)			->					str:
										SCREAMING_SNAKE_CASE           =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

										SCREAMING_SNAKE_CASE           =					self.get_config()

										return config, pixel_values, labels, pixel_labels





							def    _UpperCAmelCase     (					self       :	Optional[int]			)			->					List[str]:
										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       :	List[Any]       ,     a       :	Optional[Any]       ,     a       :	List[str]       ,     a       :	str       ,     a       :	Optional[int]			)			->					Any:
										SCREAMING_SNAKE_CASE           =					MobileNetVaModel(config=a			)
										model.to(a			)
										model.eval()
										SCREAMING_SNAKE_CASE           =					model(a			)
										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       :	int       ,     a       :	Optional[Any]       ,     a       :	Tuple       ,     a       :	Union[str, Any]       ,     a       :	int			)			->					Tuple:
										SCREAMING_SNAKE_CASE           =					self.num_labels
										SCREAMING_SNAKE_CASE           =					MobileNetVaForImageClassification(a			)
										model.to(a			)
										model.eval()
										SCREAMING_SNAKE_CASE           =					model(a       ,     labels=a			)
										self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)			)







							def    _UpperCAmelCase     (					self       :	Dict			)			->					Optional[int]:
										SCREAMING_SNAKE_CASE           =					self.prepare_config_and_inputs()
										SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					config_and_inputs
										SCREAMING_SNAKE_CASE           =					{"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_torch
class 			UpperCAmelCase_      (   A		,      A		,      unittest.TestCase       ):




							'''simple docstring'''



							a__						  =     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
							a__						  =     (
							    {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							a__						  =     False
							a__						  =     False
							a__						  =     False
							a__						  =     False





							def    _UpperCAmelCase     (					self       :	List[Any]			)			->					Dict:
										SCREAMING_SNAKE_CASE           =					MobileNetVaModelTester(self			)
										SCREAMING_SNAKE_CASE           =					MobileNetVaConfigTester(self       ,     config_class=a       ,     has_text_modality=a			)





							def    _UpperCAmelCase     (					self       :	str			)			->					Optional[int]:
										self.config_tester.run_common_tests()





							@unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""			)
							def    _UpperCAmelCase     (					self       :	Optional[int]			)			->					Union[str, Any]:
										pass





							@unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""			)
							def    _UpperCAmelCase     (					self       :	Union[str, Any]			)			->					List[str]:
										pass





							@unittest.skip(reason="""MobileNetV1 does not output attentions"""			)
							def    _UpperCAmelCase     (					self       :	int			)			->					Dict:
										pass





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					Union[str, Any]:
										SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs_for_common()

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

													SCREAMING_SNAKE_CASE           =					["""pixel_values"""]
													self.assertListEqual(arg_names[:1]       ,     a			)





							def    _UpperCAmelCase     (					self       :	Any			)			->					List[str]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*a			)





							def    _UpperCAmelCase     (					self       :	List[str]			)			->					Union[str, Any]:
										def check_hidden_states_output(a       :	Optional[int]       ,     a       :	Union[str, Any]       ,     a       :	Union[str, Any]			):
													SCREAMING_SNAKE_CASE           =					model_class(a			)
													model.to(a			)
													model.eval()

													with torch.no_grad():
																SCREAMING_SNAKE_CASE           =					model(**self._prepare_for_class(a       ,     a			)			)

													SCREAMING_SNAKE_CASE           =					outputs.hidden_states

													SCREAMING_SNAKE_CASE           =					26
													self.assertEqual(len(a			)       ,     a			)

										SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE           =					True
													check_hidden_states_output(a       ,     a       ,     a			)

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

													check_hidden_states_output(a       ,     a       ,     a			)





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*a			)







							@slow
							def    _UpperCAmelCase     (					self       :	Union[str, Any]			)			->					Optional[Any]:
										for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													SCREAMING_SNAKE_CASE           =					MobileNetVaModel.from_pretrained(a			)
													self.assertIsNotNone(a			)





def 					lowerCamelCase_    (    ):
			'''simple docstring'''
			SCREAMING_SNAKE_CASE           =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
			return image




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




							'''simple docstring'''



							@cached_property
							def    _UpperCAmelCase     (					self       :	List[str]			)			->					Optional[Any]:
										return (
										    MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224"""			) if is_vision_available() else None
										)







							@slow
							def    _UpperCAmelCase     (					self       :	Any			)			->					List[Any]:
										SCREAMING_SNAKE_CASE           =					MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""			).to(a			)

										SCREAMING_SNAKE_CASE           =					self.default_image_processor
										SCREAMING_SNAKE_CASE           =					prepare_img()
										SCREAMING_SNAKE_CASE           =					image_processor(images=a       ,     return_tensors="""pt"""			).to(a			)

										# forward pass
										with torch.no_grad():
													SCREAMING_SNAKE_CASE           =					model(**a			)

										# verify the logits
										SCREAMING_SNAKE_CASE           =					torch.Size((1, 1_001)			)
										self.assertEqual(outputs.logits.shape       ,     a			)

										SCREAMING_SNAKE_CASE           =					torch.tensor([-4.1739, -1.1233, 3.1205]			).to(a			)

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












import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
		from .tokenization_mbart import MBartTokenizer
else:
		__A						:							Tuple							=  None


__A						:							Any							=  logging.get_logger(__name__)


__A						:							Union[str, Any]							=  {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""}

__A						:							List[Any]							=  {
    """vocab_file""": {
        """facebook/mbart-large-en-ro""": (
            """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"""
        ),
        """facebook/mbart-large-cc25""": (
            """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"""
        ),
    },
    """tokenizer_file""": {
        """facebook/mbart-large-en-ro""": """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json""",
        """facebook/mbart-large-cc25""": """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json""",
    },
}

__A						:							int							=  {
    """facebook/mbart-large-en-ro""": 1_0_2_4,
    """facebook/mbart-large-cc25""": 1_0_2_4,
}

# fmt: off
__A						:							List[Any]							=  ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""]




class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     VOCAB_FILES_NAMES
							a__						  =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							a__						  =     PRETRAINED_VOCAB_FILES_MAP
							a__						  =     ['''input_ids''', '''attention_mask''']
							a__						  =     MBartTokenizer

							a__						  =     []
							a__						  =     []





							def __init__(					self       :	str       ,     a       :	List[Any]=None       ,     a       :	Optional[int]=None       ,     a       :	str="<s>"       ,     a       :	Tuple="</s>"       ,     a       :	Optional[int]="</s>"       ,     a       :	int="<s>"       ,     a       :	List[str]="<unk>"       ,     a       :	Tuple="<pad>"       ,     a       :	Dict="<mask>"       ,     a       :	Optional[Any]=None       ,     a       :	List[Any]=None       ,     a       :	Any=None       ,     **a       :	Optional[Any]       ,     )			->					Any:
										# Mask token behave like a normal word, i.e. include the space before it
										SCREAMING_SNAKE_CASE           =					AddedToken(a       ,     lstrip=a       ,     rstrip=a			) if isinstance(a       ,     a			) else mask_token

										super().__init__(
										    vocab_file=a       ,     tokenizer_file=a       ,     bos_token=a       ,     eos_token=a       ,     sep_token=a       ,     cls_token=a       ,     unk_token=a       ,     pad_token=a       ,     mask_token=a       ,     src_lang=a       ,     tgt_lang=a       ,     additional_special_tokens=a       ,     **a       ,     )

										SCREAMING_SNAKE_CASE           =					vocab_file
										SCREAMING_SNAKE_CASE           =					False if not self.vocab_file else True

										SCREAMING_SNAKE_CASE           =					FAIRSEQ_LANGUAGE_CODES.copy()

										if additional_special_tokens is not None:
													# Only add those special tokens if they are not already there.
													_additional_special_tokens.extend(
													    [t for t in additional_special_tokens if t not in _additional_special_tokens]			)

										self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}			)
										SCREAMING_SNAKE_CASE           =					{
										    lang_code: self.convert_tokens_to_ids(a			) for lang_code in FAIRSEQ_LANGUAGE_CODES
										}

										SCREAMING_SNAKE_CASE           =					src_lang if src_lang is not None else """en_XX"""
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(self._src_lang			)
										SCREAMING_SNAKE_CASE           =					tgt_lang
										self.set_src_lang_special_tokens(self._src_lang			)





							@property
							def    _UpperCAmelCase     (					self       :	int			)			->					str:
										return self._src_lang





							@src_lang.setter
							def    _UpperCAmelCase     (					self       :	List[Any]       ,     a       :	str			)			->					None:
										SCREAMING_SNAKE_CASE           =					new_src_lang
										self.set_src_lang_special_tokens(self._src_lang			)





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	List[int]       ,     a       :	Optional[List[int]] = None			)			->					List[int]:
										if token_ids_a is None:
													return self.prefix_tokens + token_ids_a + self.suffix_tokens
										# We don't expect to process pairs, but leave the pair logic for API consistency
										return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens





							def    _UpperCAmelCase     (					self       :	Tuple       ,     a       :	List[int]       ,     a       :	Optional[List[int]] = None			)			->					List[int]:
										SCREAMING_SNAKE_CASE           =					[self.sep_token_id]
										SCREAMING_SNAKE_CASE           =					[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       :	Optional[Any]       ,     a       :	Optional[int]       ,     a       :	str       ,     a       :	Optional[str]       ,     a       :	Optional[str]       ,     **a       :	Optional[Any]			)			->					Optional[Any]:
										if src_lang is None or tgt_lang is None:
													raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""			)
										SCREAMING_SNAKE_CASE           =					src_lang
										SCREAMING_SNAKE_CASE           =					self(a       ,     add_special_tokens=a       ,     return_tensors=a       ,     **a			)
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					tgt_lang_id
										return inputs





							def    _UpperCAmelCase     (					self       :	str       ,     a       :	List[str]       ,     a       :	str = "en_XX"       ,     a       :	Optional[List[str]] = None       ,     a       :	str = "ro_RO"       ,     **a       :	List[str]       ,     )			->					BatchEncoding:
										SCREAMING_SNAKE_CASE           =					src_lang
										SCREAMING_SNAKE_CASE           =					tgt_lang
										return super().prepare_seqaseq_batch(a       ,     a       ,     **a			)





							def    _UpperCAmelCase     (					self       :	Optional[Any]			)			->					str:
										return self.set_src_lang_special_tokens(self.src_lang			)





							def    _UpperCAmelCase     (					self       :	str			)			->					List[str]:
										return self.set_tgt_lang_special_tokens(self.tgt_lang			)





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	List[str]			)			->					None:
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					[]
										SCREAMING_SNAKE_CASE           =					[self.eos_token_id, self.cur_lang_code]

										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.prefix_tokens			)
										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.suffix_tokens			)

										SCREAMING_SNAKE_CASE           =					processors.TemplateProcessing(
										    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,     pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,     self.prefix_tokens + self.suffix_tokens			)			)       ,     )





							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	str			)			->					None:
										SCREAMING_SNAKE_CASE           =					self.convert_tokens_to_ids(a			)
										SCREAMING_SNAKE_CASE           =					[]
										SCREAMING_SNAKE_CASE           =					[self.eos_token_id, self.cur_lang_code]

										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.prefix_tokens			)
										SCREAMING_SNAKE_CASE           =					self.convert_ids_to_tokens(self.suffix_tokens			)

										SCREAMING_SNAKE_CASE           =					processors.TemplateProcessing(
										    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,     pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,     self.prefix_tokens + self.suffix_tokens			)			)       ,     )







							def    _UpperCAmelCase     (					self       :	Dict       ,     a       :	str       ,     a       :	Optional[str] = None			)			->					Tuple[str]:
										if not self.can_save_slow_tokenizer:
													raise ValueError(
													    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
													    """tokenizer."""			)

										if not os.path.isdir(a			):
													logger.error(f"""Vocabulary path ({save_directory}) should be a directory."""			)
													return
										SCREAMING_SNAKE_CASE           =					os.path.join(
										    a       ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]			)

										if os.path.abspath(self.vocab_file			) != os.path.abspath(a			):
													copyfile(self.vocab_file       ,     a			)

										return (out_vocab_file,)






