



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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 tensorflow as tf

						from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor



class   UpperCAmelCase_    :







							def __init__(   self,			__a,			__a=3,			__a=32,			__a=3,			__a=10,			__a=[10, 20, 30, 40],			__a=[1, 1, 2, 1],			__a=True,			__a=True,			__a="relu",			__a=3,			__a=None,			):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    parent
														_lowerCAmelCase     :							Optional[Any]    =    batch_size
														_lowerCAmelCase     :							Optional[Any]    =    image_size
														_lowerCAmelCase     :							str    =    num_channels
														_lowerCAmelCase     :							List[Any]    =    embeddings_size
														_lowerCAmelCase     :							Dict    =    hidden_sizes
														_lowerCAmelCase     :							Tuple    =    depths
														_lowerCAmelCase     :							Any    =    is_training
														_lowerCAmelCase     :							Tuple    =    use_labels
														_lowerCAmelCase     :							Union[str, Any]    =    hidden_act
														_lowerCAmelCase     :							List[Any]    =    num_labels
														_lowerCAmelCase     :							Any    =    scope
														_lowerCAmelCase     :							int    =    len(__a)







							def    snake_case__      (   self):

														'''simple docstring'''

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

														_lowerCAmelCase     :							Tuple    =    None
														if self.use_labels:
																					_lowerCAmelCase     :							Tuple    =    ids_tensor([self.batch_size],			self.num_labels)

														_lowerCAmelCase     :							int    =    self.get_config()
														return config, pixel_values, labels







							def    snake_case__      (   self):

														'''simple docstring'''

														return RegNetConfig(
														    num_channels=self.num_channels,			embeddings_size=self.embeddings_size,			hidden_sizes=self.hidden_sizes,			depths=self.depths,			hidden_act=self.hidden_act,			num_labels=self.num_labels,			)







							def    snake_case__      (   self,			__a,			__a,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Union[str, Any]    =    TFRegNetModel(config=__a)
														_lowerCAmelCase     :							Any    =    model(__a,			training=__a)
														# expected last hidden states: B, C, H // 32, W // 32
														self.parent.assertEqual(
														    result.last_hidden_state.shape,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),			)







							def    snake_case__      (   self,			__a,			__a,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    self.num_labels
														_lowerCAmelCase     :							Optional[Any]    =    TFRegNetForImageClassification(__a)
														_lowerCAmelCase     :							Optional[Any]    =    model(__a,			labels=__a,			training=__a)
														self.parent.assertEqual(result.logits.shape,			(self.batch_size, self.num_labels))







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    self.prepare_config_and_inputs()
														_lowerCAmelCase   ,    _lowerCAmelCase   ,    _lowerCAmelCase     :							Optional[Any]    =    config_and_inputs
														_lowerCAmelCase     :							Union[str, Any]    =    {"pixel_values": pixel_values}
														return config, inputs_dict



@require_tf
class   UpperCAmelCase_    (       a   ,					a   ,					unittest.TestCase):
							lowerCamelCase__   			=		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
							lowerCamelCase__   			=		(
							    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							lowerCamelCase__   			=		False
							lowerCamelCase__   			=		False
							lowerCamelCase__   			=		False
							lowerCamelCase__   			=		False
							lowerCamelCase__   			=		False







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							List[str]    =    TFRegNetModelTester(self)
														_lowerCAmelCase     :							Optional[Any]    =    ConfigTester(self,			config_class=__a,			has_text_modality=__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														return







							@unittest.skip(reason="RegNet does not use inputs_embeds")
							def    snake_case__      (   self):

														'''simple docstring'''

														pass







							@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    snake_case__      (   self):

														'''simple docstring'''

														super().test_keras_fit()







							@unittest.skip(reason="RegNet does not support input and output embeddings")
							def    snake_case__      (   self):

														'''simple docstring'''

														pass







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase   ,    _lowerCAmelCase     :							Optional[Any]    =    self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					_lowerCAmelCase     :							List[Any]    =    model_class(__a)
																					_lowerCAmelCase     :							Dict    =    inspect.signature(model.call)
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					_lowerCAmelCase     :							str    =    [*signature.parameters.keys()]

																					_lowerCAmelCase     :							List[Any]    =    ["pixel_values"]
																					self.assertListEqual(arg_names[:1],			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														def check_hidden_states_output(__a,			__a,			__a):
																					_lowerCAmelCase     :							Any    =    model_class(__a)
																					_lowerCAmelCase     :							Optional[int]    =    model(**self._prepare_for_class(__a,			__a),			training=__a)

																					_lowerCAmelCase     :							Any    =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																					_lowerCAmelCase     :							Optional[int]    =    self.model_tester.num_stages
																					self.assertEqual(len(__a),			expected_num_stages + 1)

																					# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
																					self.assertListEqual(
																					    list(hidden_states[0].shape[-2:]),			[self.model_tester.image_size // 2, self.model_tester.image_size // 2],			)

														_lowerCAmelCase   ,    _lowerCAmelCase     :							Dict    =    self.model_tester.prepare_config_and_inputs_for_common()
														_lowerCAmelCase     :							str    =    ["basic", "bottleneck"]
														for model_class in self.all_model_classes:
																					for layer_type in layers_type:
																												_lowerCAmelCase     :							str    =    layer_type
																												_lowerCAmelCase     :							Optional[Any]    =    True
																												check_hidden_states_output(__a,			__a,			__a)

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

																												check_hidden_states_output(__a,			__a,			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase   ,    _lowerCAmelCase     :							int    =    self.model_tester.prepare_config_and_inputs_for_common()

														def check_equivalence(__a,			__a,			__a,			__a={}):
																					_lowerCAmelCase     :							Union[str, Any]    =    model(__a,			return_dict=__a,			**__a)
																					_lowerCAmelCase     :							Any    =    model(__a,			return_dict=__a,			**__a).to_tuple()

																					def recursive_check(__a,			__a):
																												if isinstance(__a,			(List, Tuple)):
																																			for tuple_iterable_value, dict_iterable_value in zip(__a,			__a):
																																										recursive_check(__a,			__a)
																												elif tuple_object is None:
																																			return
																												else:
																																			self.assertTrue(
																																			    all(tf.equal(__a,			__a)),			msg=(
																																			        "Tuple and dict output are not equal. Difference:"
																																			        f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"
																																			    ),			)

																												recursive_check(__a,			__a)

														for model_class in self.all_model_classes:
																					_lowerCAmelCase     :							str    =    model_class(__a)

																					_lowerCAmelCase     :							int    =    self._prepare_for_class(__a,			__a)
																					_lowerCAmelCase     :							int    =    self._prepare_for_class(__a,			__a)
																					check_equivalence(__a,			__a,			__a)

																					_lowerCAmelCase     :							Any    =    self._prepare_for_class(__a,			__a,			return_labels=__a)
																					_lowerCAmelCase     :							Optional[int]    =    self._prepare_for_class(__a,			__a,			return_labels=__a)
																					check_equivalence(__a,			__a,			__a)

																					_lowerCAmelCase     :							List[str]    =    self._prepare_for_class(__a,			__a)
																					_lowerCAmelCase     :							List[Any]    =    self._prepare_for_class(__a,			__a)
																					check_equivalence(__a,			__a,			__a,			{"output_hidden_states": True})

																					_lowerCAmelCase     :							Tuple    =    self._prepare_for_class(__a,			__a,			return_labels=__a)
																					_lowerCAmelCase     :							List[Any]    =    self._prepare_for_class(__a,			__a,			return_labels=__a)
																					check_equivalence(__a,			__a,			__a,			{"output_hidden_states": True})







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*__a)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_lowerCAmelCase     :							int    =    TFRegNetModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)






def 				A				(					):





							'''simple docstring'''




							_lowerCAmelCase     :							int    =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							return image



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







							@cached_property
							def    snake_case__      (   self):

														'''simple docstring'''

														return (
														    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
														    if is_vision_available()
														    else None
														)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

														_lowerCAmelCase     :							Optional[Any]    =    self.default_image_processor
														_lowerCAmelCase     :							Dict    =    prepare_img()
														_lowerCAmelCase     :							List[Any]    =    image_processor(images=__a,			return_tensors="tf")

														# forward pass
														_lowerCAmelCase     :							Optional[int]    =    model(**__a,			training=__a)

														# verify the logits
														_lowerCAmelCase     :							Dict    =    tf.TensorShape((1, 1000))
														self.assertEqual(outputs.logits.shape,			__a)

														_lowerCAmelCase     :							int    =    tf.constant([-0.4_180, -1.5_051, -3.4_836])

														tf.debugging.assert_near(outputs.logits[0, :3],			__a,			atol=1E-4)

"""simple docstring"""







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:
       __SCREAMING_SNAKE_CASE    	=None


__SCREAMING_SNAKE_CASE    	=logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE    	={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}

__SCREAMING_SNAKE_CASE    	={
    "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",
    },
}

__SCREAMING_SNAKE_CASE    	={
    "facebook/mbart-large-en-ro": 1024,
    "facebook/mbart-large-cc25": 1024,
}

# fmt: off
__SCREAMING_SNAKE_CASE    	=["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		(			lowercase_  ):
   lowercase							=  VOCAB_FILES_NAMES
   lowercase							=  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   lowercase							=  PRETRAINED_VOCAB_FILES_MAP
   lowercase							=  ['input_ids', 'attention_mask']
   lowercase							=  MBartTokenizer

   lowercase							=  []
   lowercase							=  []
   def __init__(			self     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,__UpperCamelCase="<s>"     ,__UpperCamelCase="</s>"     ,__UpperCamelCase="</s>"     ,__UpperCamelCase="<s>"     ,__UpperCamelCase="<unk>"     ,__UpperCamelCase="<pad>"     ,__UpperCamelCase="<mask>"     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,**__UpperCamelCase     ,)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				str													=	AddedToken(__UpperCamelCase     ,lstrip=__UpperCamelCase     ,rstrip=__UpperCamelCase			) if isinstance(__UpperCamelCase     ,__UpperCamelCase			) else mask_token

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

        lowercase_	:				str													=	vocab_file
        lowercase_	:				Optional[Any]													=	False if not self.vocab_file else True

        lowercase_	:				List[str]													=	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}			)
        lowercase_	:				List[Any]													=	{
            lang_code: self.convert_tokens_to_ids(__UpperCamelCase			) for lang_code in FAIRSEQ_LANGUAGE_CODES
        }

        lowercase_	:				Dict													=	src_lang if src_lang is not None else 'en_XX'
        lowercase_	:				Union[str, Any]													=	self.convert_tokens_to_ids(self._src_lang			)
        lowercase_	:				int													=	tgt_lang
        self.set_src_lang_special_tokens(self._src_lang			)
   @property
   def 			_UpperCAmelCase   (			self			)	->      str:


        '''simple docstring'''


        return self._src_lang
   @src_lang.setter
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      None:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	new_src_lang
        self.set_src_lang_special_tokens(self._src_lang			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase = None			)	->      List[int]:


        '''simple docstring'''


        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     ,__UpperCamelCase     ,__UpperCamelCase = None			)	->      List[int]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	[self.sep_token_id]
        lowercase_	:				str													=	[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     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,**__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        if src_lang is None or tgt_lang is None:
             raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model'			)
        lowercase_	:				Dict													=	src_lang
        lowercase_	:				List[Any]													=	self(__UpperCamelCase     ,add_special_tokens=__UpperCamelCase     ,return_tensors=__UpperCamelCase     ,**__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	self.convert_tokens_to_ids(__UpperCamelCase			)
        lowercase_	:				Dict													=	tgt_lang_id
        return inputs
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase = "en_XX"     ,__UpperCamelCase = None     ,__UpperCamelCase = "ro_RO"     ,**__UpperCamelCase     ,)	->      BatchEncoding:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	src_lang
        lowercase_	:				List[Any]													=	tgt_lang
        return super().prepare_seqaseq_batch(__UpperCamelCase     ,__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        return self.set_src_lang_special_tokens(self.src_lang			)
   def 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        return self.set_tgt_lang_special_tokens(self.tgt_lang			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      None:


        '''simple docstring'''


        lowercase_	:				Any													=	self.convert_tokens_to_ids(__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	[]
        lowercase_	:				int													=	[self.eos_token_id, self.cur_lang_code]

        lowercase_	:				Any													=	self.convert_ids_to_tokens(self.prefix_tokens			)
        lowercase_	:				int													=	self.convert_ids_to_tokens(self.suffix_tokens			)

        lowercase_	:				Union[str, Any]													=	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     ,__UpperCamelCase			)	->      None:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	self.convert_tokens_to_ids(__UpperCamelCase			)
        lowercase_	:				str													=	[]
        lowercase_	:				Dict													=	[self.eos_token_id, self.cur_lang_code]

        lowercase_	:				str													=	self.convert_ids_to_tokens(self.prefix_tokens			)
        lowercase_	:				List[Any]													=	self.convert_ids_to_tokens(self.suffix_tokens			)

        lowercase_	:				int													=	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     ,__UpperCamelCase     ,__UpperCamelCase = None			)	->      Tuple[str]:


        '''simple docstring'''


        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(__UpperCamelCase			):
             logger.error(f'''Vocabulary path ({save_directory}) should be a directory.'''			)
             return
        lowercase_	:				Tuple													=	os.path.join(
            __UpperCamelCase     ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']			)

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

        return (out_vocab_file,)

