




'''simple docstring'''







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
    from PIL import Image

    from transformers import ConvNextImageProcessor

class   _snake_case:






 def __init__(self					:     List[Any]						,		a					:     Optional[int]						,		a					:     List[str]=13						,		a					:     Union[str, Any]=32						,		a					:     Any=3						,		a					:     Optional[Any]=4						,		a					:     Union[str, Any]=[10, 20, 30, 40]						,		a					:     Optional[Any]=[2, 2, 3, 2]						,		a					:     Tuple=True						,		a					:     Tuple=True						,		a					:     Optional[Any]=37						,		a					:     List[str]="gelu"						,		a					:     Any=10						,		a					:     List[str]=0.02						,		a					:     Tuple=3						,		a					:     str=None						,		)					->      Optional[int]:






    """simple docstring"""


    A__         =    parent
    A__         =    batch_size
    A__         =    image_size
    A__         =    num_channels
    A__         =    num_stages
    A__         =    hidden_sizes
    A__         =    depths
    A__         =    is_training
    A__         =    use_labels
    A__         =    intermediate_size
    A__         =    hidden_act
    A__         =    type_sequence_label_size
    A__         =    initializer_range
    A__         =    scope






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






    """simple docstring"""


    A__         =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

    A__         =    None
    if self.use_labels:
       A__         =    ids_tensor([self.batch_size]						,		self.type_sequence_label_size						)

    A__         =    self.get_config()

    return config, pixel_values, labels






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






    """simple docstring"""


    return ConvNextConfig(
        num_channels=self.num_channels						,		hidden_sizes=self.hidden_sizes						,		depths=self.depths						,		num_stages=self.num_stages						,		hidden_act=self.hidden_act						,		is_decoder=UpperCAmelCase_						,		initializer_range=self.initializer_range						,		)






 def 	_UpperCamelCase   (self					:     Optional[int]						,		a					:     str						,		a					:     Union[str, Any]						,		a					:     Optional[int]						)					->      Any:






    """simple docstring"""


    A__         =    TFConvNextModel(config=UpperCAmelCase_						)
    A__         =    model(UpperCAmelCase_						,		training=UpperCAmelCase_						)
    # 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 	_UpperCamelCase   (self					:     Optional[Any]						,		a					:     Tuple						,		a					:     List[Any]						,		a					:     Dict						)					->      str:






    """simple docstring"""


    A__         =    self.type_sequence_label_size
    A__         =    TFConvNextForImageClassification(UpperCAmelCase_						)
    A__         =    model(UpperCAmelCase_						,		labels=UpperCAmelCase_						,		training=UpperCAmelCase_						)
    self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.type_sequence_label_size)						)






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






    """simple docstring"""


    A__         =    self.prepare_config_and_inputs()
    A__         =    config_and_inputs
    A__         =    {'pixel_values': pixel_values}
    return config, inputs_dict




@require_tf
class   _snake_case( UpperCAmelCase					,   UpperCAmelCase					,   unittest.TestCase			):
 __snake_case:       List[str]									=				(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
 __snake_case:       Optional[Any]									=				(
     {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
     if is_tf_available()
     else {}
 )

 __snake_case:       Optional[int]									=				False
 __snake_case:       List[Any]									=				False
 __snake_case:       Any									=				False
 __snake_case:       str									=				False
 __snake_case:       str									=				False






 def 	_UpperCamelCase   (self					:     Dict						)					->      Dict:






    """simple docstring"""


    A__         =    TFConvNextModelTester(self						)
    A__         =    ConfigTester(
        self						,		config_class=UpperCAmelCase_						,		has_text_modality=UpperCAmelCase_						,		hidden_size=37						,		)






 @unittest.skip(reason='ConvNext does not use inputs_embeds'						)
 def 	_UpperCamelCase   (self					:     List[str]						)					->      Any:






    """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 	_UpperCamelCase   (self					:     Optional[Any]						)					->      Any:






    """simple docstring"""


    super().test_keras_fit()






 @unittest.skip(reason='ConvNext does not support input and output embeddings'						)
 def 	_UpperCamelCase   (self					:     List[str]						)					->      Optional[Any]:






    """simple docstring"""


    pass






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






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs_for_common()

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

       A__         =    ['pixel_values']
       self.assertListEqual(arg_names[:1]						,		UpperCAmelCase_						)






 def 	_UpperCamelCase   (self					:     Any						)					->      Tuple:






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCAmelCase_						)






 @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.'						,		)
 def 	_UpperCamelCase   (self					:     List[str]						)					->      Optional[int]:






    """simple docstring"""


    super().test_dataset_conversion()






 def 	_UpperCamelCase   (self					:     int						)					->      Dict:






    """simple docstring"""


    def check_hidden_states_output(a					:     Tuple						,		a					:     Union[str, Any]						,		a					:     List[str]						):
       A__         =    model_class(UpperCAmelCase_						)

       A__         =    model(**self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						)						)
       A__         =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

       A__         =    self.model_tester.num_stages
       self.assertEqual(len(UpperCAmelCase_						)						,		expected_num_stages + 1						)

       # ConvNext'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 // 4, self.model_tester.image_size // 4]						,		)

    A__         =    self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       A__         =    True
       check_hidden_states_output(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						)

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

       check_hidden_states_output(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						)






 def 	_UpperCamelCase   (self					:     List[str]						)					->      Optional[int]:






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs_for_common()

    def check_equivalence(a					:     str						,		a					:     Tuple						,		a					:     List[str]						,		a					:     Union[str, Any]={}						):
       A__         =    model(UpperCAmelCase_						,		return_dict=UpperCAmelCase_						,		**UpperCAmelCase_						)
       A__         =    model(UpperCAmelCase_						,		return_dict=UpperCAmelCase_						,		**UpperCAmelCase_						).to_tuple()

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

          recursive_check(UpperCAmelCase_						,		UpperCAmelCase_						)

    for model_class in self.all_model_classes:
       A__         =    model_class(UpperCAmelCase_						)

       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						)
       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						)
       check_equivalence(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						)

       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						,		return_labels=UpperCAmelCase_						)
       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						,		return_labels=UpperCAmelCase_						)
       check_equivalence(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						)

       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						)
       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						)
       check_equivalence(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						,		{'output_hidden_states': True}						)

       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						,		return_labels=UpperCAmelCase_						)
       A__         =    self._prepare_for_class(UpperCAmelCase_						,		UpperCAmelCase_						,		return_labels=UpperCAmelCase_						)
       check_equivalence(UpperCAmelCase_						,		UpperCAmelCase_						,		UpperCAmelCase_						,		{'output_hidden_states': True}						)






 def 	_UpperCamelCase   (self					:     int						)					->      Any:






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_						)






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






    """simple docstring"""


    A__         =    TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'						)
    self.assertIsNotNone(UpperCAmelCase_						)







def 	_A			(   ):
   A__         =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
   return image







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






 @cached_property
 def 	_UpperCamelCase   (self					:     Optional[int]						)					->      List[Any]:






    """simple docstring"""


    return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'						) if is_vision_available() else None






 @slow
 def 	_UpperCamelCase   (self					:     int						)					->      Tuple:






    """simple docstring"""


    A__         =    TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'						)

    A__         =    self.default_image_processor
    A__         =    prepare_img()
    A__         =    image_processor(images=UpperCAmelCase_						,		return_tensors='tf'						)

    # forward pass
    A__         =    model(**UpperCAmelCase_						)

    # verify the logits
    A__         =    tf.TensorShape((1, 10_00)						)
    self.assertEqual(outputs.logits.shape						,		UpperCAmelCase_						)

    A__         =    tf.constant([-0.0260, -0.4739, 0.1911]						)

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








'''simple docstring'''







import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


lowerCAmelCase_    	=							logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
lowerCAmelCase_    	=							direct_transformers_import(Path(__file__).parent)


lowerCAmelCase_    	=							{
    '''AutoTokenizer''': '''PreTrainedTokenizerBase''',
    '''AutoFeatureExtractor''': '''FeatureExtractionMixin''',
    '''AutoImageProcessor''': '''ImageProcessingMixin''',
}

class   _snake_case( UpperCAmelCase			):
 __snake_case:       str									=				['''feature_extractor''', '''tokenizer''']
 # Names need to be attr_class for attr in attributes
 __snake_case:       Optional[Any]									=				None
 __snake_case:       List[str]									=				None
 __snake_case:       Any									=				None






 def __init__(self					:     List[Any]						,		*a					:     Union[str, Any]						,		**a					:     Optional[int]						)					->      Any:






    """simple docstring"""


    for key in kwargs:
       if key not in self.attributes:
          raise TypeError(f"""Unexpected keyword argument {key}."""						)
    for arg, attribute_name in zip(a						,		self.attributes						):
       if attribute_name in kwargs:
          raise TypeError(f"""Got multiple values for argument {attribute_name}."""						)
       else:
          A__         =    arg

    if len(a						) != len(self.attributes						):
       raise ValueError(
           f"""This processor requires {len(self.attributes						)} arguments: {", ".join(self.attributes						)}. Got """
           f"""{len(a						)} arguments instead."""						)

    # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
    for attribute_name, arg in kwargs.items():
       A__         =    getattr(self						,		f"""{attribute_name}_class"""						)
       # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
       A__         =    AUTO_TO_BASE_CLASS_MAPPING.get(a						,		a						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) for n in class_name if n is not None						)
       else:
          A__         =    getattr(a						,		a						)

       if not isinstance(a						,		a						):
          raise ValueError(
              f"""Received a {type(a						).__name__} for argument {attribute_name}, but a {class_name} was expected."""						)

       setattr(self						,		a						,		a						)






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






    """simple docstring"""


    A__         =    [f"""- {name}: {repr(getattr(self						,		a						)						)}""" for name in self.attributes]
    A__         =    '\n'.join(a						)
    return f"""{self.__class__.__name__}:\n{attributes_repr}"""






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     Tuple						,		a					:     bool = False						,		**a					:     int						)					->      List[str]:






    """simple docstring"""


    os.makedirs(a						,		exist_ok=a						)

    if push_to_hub:
       A__         =    kwargs.pop('commit_message'						,		a						)
       A__         =    kwargs.pop('repo_id'						,		save_directory.split(os.path.sep						)[-1]						)
       A__         =    self._create_repo(a						,		**a						)
       A__         =    self._get_files_timestamps(a						)
    # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
    # loaded from the Hub.
    if self._auto_class is not None:
       A__         =    [getattr(self						,		a						) for attribute_name in self.attributes]
       A__         =    [(a.init_kwargs if isinstance(a						,		a						) else a) for a in attrs]
       custom_object_save(self						,		a						,		config=a						)

    for attribute_name in self.attributes:
       A__         =    getattr(self						,		a						)
       # Include the processor class in the attribute config so this processor can then be reloaded with the
       # `AutoProcessor` API.
       if hasattr(a						,		'_set_processor_class'						):
          attribute._set_processor_class(self.__class__.__name__						)
       attribute.save_pretrained(a						)

    if self._auto_class is not None:
       # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
       for attribute_name in self.attributes:
          A__         =    getattr(self						,		a						)
          if isinstance(a						,		a						):
             del attribute.init_kwargs["auto_map"]

    if push_to_hub:
       self._upload_modified_files(
           a						,		a						,		a						,		commit_message=a						,		token=kwargs.get('use_auth_token'						)						,		)






 @classmethod
 def 	_UpperCamelCase   (cls					:     int						,		a					:     Union[str, os.PathLike]						,		a					:     Optional[Union[str, os.PathLike]] = None						,		a					:     bool = False						,		a					:     bool = False						,		a					:     Optional[Union[str, bool]] = None						,		a					:     str = "main"						,		**a					:     Union[str, Any]						,		)					->      Optional[Any]:






    """simple docstring"""


    A__         =    cache_dir
    A__         =    force_download
    A__         =    local_files_only
    A__         =    revision

    A__         =    kwargs.pop('use_auth_token'						,		a						)
    if use_auth_token is not None:
       warnings.warn(
           'The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.'						,		a						)
       if token is not None:
          raise ValueError(
              '`token` and `use_auth_token` are both specified. Please set only the argument `token`.'						)
       A__         =    use_auth_token

    if token is not None:
       # change to `token` in a follow-up PR
       A__         =    token

    A__         =    cls._get_arguments_from_pretrained(a						,		**a						)
    return cls(*a						)






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[int]						,		a					:     Union[str, Any]="AutoProcessor"						)					->      Any:






    """simple docstring"""


    if not isinstance(a						,		a						):
       A__         =    auto_class.__name__

    import transformers.models.auto as auto_module

    if not hasattr(a						,		a						):
       raise ValueError(f"""{auto_class} is not a valid auto class."""						)

    A__         =    auto_class






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[Any]						,		a					:     Optional[Any]						,		**a					:     Tuple						)					->      int:






    """simple docstring"""


    A__         =    []
    for attribute_name in cls.attributes:
       A__         =    getattr(cls						,		f"""{attribute_name}_class"""						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) if n is not None else None for n in class_name						)
          A__         =    kwargs.get('use_fast'						,		a						)
          if use_fast and classes[1] is not None:
             A__         =    classes[1]
          else:
             A__         =    classes[0]
       else:
          A__         =    getattr(a						,		a						)

       args.append(attribute_class.from_pretrained(a						,		**a						)						)
    return args






 @property
 def 	_UpperCamelCase   (self					:     str						)					->      List[str]:






    """simple docstring"""


    A__         =    getattr(self						,		self.attributes[0]						)
    return getattr(a						,		'model_input_names'						,		a						)




lowerCAmelCase_    	=							copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
    lowerCAmelCase_    	=							ProcessorMixin.push_to_hub.__doc__.format(
        object='''processor''', object_class='''AutoProcessor''', object_files='''processor files'''
    )


