
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 				_lowerCamelCase :





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=3_2						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=1_0						,						__SCREAMING_SNAKE_CASE=[1_0, 2_0, 3_0, 4_0]						,						__SCREAMING_SNAKE_CASE=[1, 1, 2, 1]						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE="relu"						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=None						,						)  ->   str:




           """simple docstring"""







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






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   int					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

           UpperCamelCase__    :   List[str]					=				None
           if self.use_labels:
                 UpperCamelCase__    :   List[Any]					=				ids_tensor([self.batch_size]						,						self.num_labels  )

           UpperCamelCase__    :   Dict					=				self.get_config()
           return config, pixel_values, labels






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """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    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   List[str]:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				TFRegNetModel(config=__SCREAMING_SNAKE_CASE  )
           UpperCamelCase__    :   Union[str, Any]					=				model(__SCREAMING_SNAKE_CASE						,						training=__SCREAMING_SNAKE_CASE  )
           # 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 // 3_2, self.image_size // 3_2)						,						)






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				self.num_labels
           UpperCamelCase__    :   Tuple					=				TFRegNetForImageClassification(__SCREAMING_SNAKE_CASE  )
           UpperCamelCase__    :   Tuple					=				model(__SCREAMING_SNAKE_CASE						,						labels=__SCREAMING_SNAKE_CASE						,						training=__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[str]:




           """simple docstring"""







           UpperCamelCase__    :   str					=				self.prepare_config_and_inputs()
           UpperCamelCase__				,UpperCamelCase__				,UpperCamelCase__    :   List[str]					=				config_and_inputs
           UpperCamelCase__    :   List[str]					=				{'''pixel_values''': pixel_values}
           return config, inputs_dict




@require_tf
class 				_lowerCamelCase (      UpperCamelCase_	,							UpperCamelCase_	,							unittest.TestCase ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		   =  (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE_		   =  (
         {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
         if is_tf_available()
         else {}
     )

     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           UpperCamelCase__    :   List[str]					=				TFRegNetModelTester(self  )
           UpperCamelCase__    :   Any					=				ConfigTester(self						,						config_class=__SCREAMING_SNAKE_CASE						,						has_text_modality=__SCREAMING_SNAKE_CASE  )






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




           """simple docstring"""







           return






     @unittest.skip(reason='''RegNet does not use inputs_embeds'''  )
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   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    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           super().test_keras_fit()






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




           """simple docstring"""







           pass






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







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

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

                 UpperCamelCase__    :   List[Any]					=				['''pixel_values''']
                 self.assertListEqual(arg_names[:1]						,						__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           def check_hidden_states_output(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  ):
                 UpperCamelCase__    :   List[str]					=				model_class(__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   Union[str, Any]					=				model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )						,						training=__SCREAMING_SNAKE_CASE  )

                 UpperCamelCase__    :   Optional[Any]					=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 UpperCamelCase__    :   Optional[Any]					=				self.model_tester.num_stages
                 self.assertEqual(len(__SCREAMING_SNAKE_CASE  )						,						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]						,						)

           UpperCamelCase__				,UpperCamelCase__    :   Tuple					=				self.model_tester.prepare_config_and_inputs_for_common()
           UpperCamelCase__    :   Union[str, Any]					=				['''basic''', '''bottleneck''']
           for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                       UpperCamelCase__    :   str					=				layer_type
                       UpperCamelCase__    :   Tuple					=				True
                       check_hidden_states_output(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )

                       # check that output_hidden_states also work using config
                       del inputs_dict["output_hidden_states"]
                       UpperCamelCase__    :   List[str]					=				True

                       check_hidden_states_output(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[str]:




           """simple docstring"""







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

           def check_equivalence(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE={}  ):
                 UpperCamelCase__    :   Any					=				model(__SCREAMING_SNAKE_CASE						,						return_dict=__SCREAMING_SNAKE_CASE						,						**__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   int					=				model(__SCREAMING_SNAKE_CASE						,						return_dict=__SCREAMING_SNAKE_CASE						,						**__SCREAMING_SNAKE_CASE  ).to_tuple()

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

                       recursive_check(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )

           for model_class in self.all_model_classes:
                 UpperCamelCase__    :   Union[str, Any]					=				model_class(__SCREAMING_SNAKE_CASE  )

                 UpperCamelCase__    :   List[str]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   str					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )
                 check_equivalence(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )

                 UpperCamelCase__    :   Union[str, Any]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   List[str]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 check_equivalence(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )

                 UpperCamelCase__    :   List[Any]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   Union[str, Any]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )
                 check_equivalence(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						{'''output_hidden_states''': True}  )

                 UpperCamelCase__    :   str					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   int					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 check_equivalence(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						{'''output_hidden_states''': True}  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   List[str]					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE  )






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 UpperCamelCase__    :   List[str]					=				TFRegNetModel.from_pretrained(__SCREAMING_SNAKE_CASE  )
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE  )


def 							SCREAMING_SNAKE_CASE_      (			):
      UpperCamelCase__    :   Optional[Any]					=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
      return image




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





     """simple docstring"""







     @cached_property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Dict:




           """simple docstring"""







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






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           UpperCamelCase__    :   int					=				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

           UpperCamelCase__    :   int					=				self.default_image_processor
           UpperCamelCase__    :   Dict					=				prepare_img()
           UpperCamelCase__    :   Optional[Any]					=				image_processor(images=__SCREAMING_SNAKE_CASE						,						return_tensors='''tf'''  )

           # forward pass
           UpperCamelCase__    :   Union[str, Any]					=				model(**__SCREAMING_SNAKE_CASE						,						training=__SCREAMING_SNAKE_CASE  )

           # verify the logits
           UpperCamelCase__    :   int					=				tf.TensorShape((1, 1_0_0_0)  )
           self.assertEqual(outputs.logits.shape						,						__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   Optional[Any]					=				tf.constant([-0.4180, -1.5051, -3.4836]  )

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




from argparse import ArgumentParser

from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand


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


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		):
      if not path:
            return "pipe"

      for ext in PipelineDataFormat.SUPPORTED_FORMATS:
            if path.endswith(UpperCamelCase__		):
                  return ext

      raise Exception(
          f'''Unable to determine file format from file extension {path}. '''
          f'''Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}'''		)


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		):
      UpperCamelCase__    :   Tuple					=				pipeline(
          task=args.task ,		model=args.model if args.model else None ,		config=args.config ,		tokenizer=args.tokenizer ,		device=args.device ,		)
      UpperCamelCase__    :   Any					=				try_infer_format_from_ext(args.input		) if args.format == '''infer''' else args.format
      UpperCamelCase__    :   Tuple					=				PipelineDataFormat.from_str(
          format=UpperCamelCase__ ,		output_path=args.output ,		input_path=args.input ,		column=args.column if args.column else nlp.default_input_names ,		overwrite=args.overwrite ,		)
      return RunCommand(UpperCamelCase__ ,		UpperCamelCase__		)




class 				_lowerCamelCase (      UpperCamelCase_ ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				nlp
           UpperCamelCase__    :   Dict					=				reader






     @staticmethod
     def    __SCREAMING_SNAKE_CASE			(							__SCREAMING_SNAKE_CASE  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				parser.add_parser('''run'''						,						help='''Run a pipeline through the CLI'''  )
           run_parser.add_argument('''--task'''						,						choices=get_supported_tasks()						,						help='''Task to run'''  )
           run_parser.add_argument('''--input'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Path to the file to use for inference'''  )
           run_parser.add_argument('''--output'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Path to the file that will be used post to write results.'''  )
           run_parser.add_argument('''--model'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Name or path to the model to instantiate.'''  )
           run_parser.add_argument('''--config'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Name or path to the model\'s config to instantiate.'''  )
           run_parser.add_argument(
               '''--tokenizer'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Name of the tokenizer to use. (default: same as the model name)'''  )
           run_parser.add_argument(
               '''--column'''						,						type=__SCREAMING_SNAKE_CASE						,						help='''Name of the column to use as input. (For multi columns input as QA use column1,columns2)'''						,						)
           run_parser.add_argument(
               '''--format'''						,						type=__SCREAMING_SNAKE_CASE						,						default='''infer'''						,						choices=PipelineDataFormat.SUPPORTED_FORMATS						,						help='''Input format to read from'''						,						)
           run_parser.add_argument(
               '''--device'''						,						type=__SCREAMING_SNAKE_CASE						,						default=-1						,						help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)'''						,						)
           run_parser.add_argument('''--overwrite'''						,						action='''store_true'''						,						help='''Allow overwriting the output file.'''  )
           run_parser.set_defaults(func=__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   Optional[Any]					=				self._nlp, []

           for entry in self._reader:
                 UpperCamelCase__    :   List[str]					=				nlp(**__SCREAMING_SNAKE_CASE  ) if self._reader.is_multi_columns else nlp(__SCREAMING_SNAKE_CASE  )
                 if isinstance(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  ):
                       outputs.append(__SCREAMING_SNAKE_CASE  )
                 else:
                       outputs += output

        # Saving data
           if self._nlp.binary_output:
                 UpperCamelCase__    :   Union[str, Any]					=				self._reader.save_binary(__SCREAMING_SNAKE_CASE  )
                 logger.warning(F'''Current pipeline requires output to be in binary format, saving at {binary_path}'''  )
           else:
                 self._reader.save(__SCREAMING_SNAKE_CASE  )


