





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor

class    lowerCAmelCase							:
 def __init__(      self  :      str			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      List[str]=3			,     UpperCAmelCase  :      Dict=32			,     UpperCAmelCase  :      List[Any]=3			,     UpperCAmelCase  :      Tuple=10			,     UpperCAmelCase  :      Union[str, Any]=[10, 20, 30, 40]			,     UpperCAmelCase  :      Union[str, Any]=[1, 1, 2, 1]			,     UpperCAmelCase  :      Optional[Any]=True			,     UpperCAmelCase  :      List[str]=True			,     UpperCAmelCase  :      List[Any]="relu"			,     UpperCAmelCase  :      Any=3			,     UpperCAmelCase  :      Optional[int]=None			,     )			->	Dict:
     lowerCamelCase__    :      Tuple					 =		parent
     lowerCamelCase__    :      Optional[Any]					 =		batch_size
     lowerCamelCase__    :      Optional[int]					 =		image_size
     lowerCamelCase__    :      List[str]					 =		num_channels
     lowerCamelCase__    :      Tuple					 =		embeddings_size
     lowerCamelCase__    :      Dict					 =		hidden_sizes
     lowerCamelCase__    :      List[Any]					 =		depths
     lowerCamelCase__    :      Any					 =		is_training
     lowerCamelCase__    :      Optional[int]					 =		use_labels
     lowerCamelCase__    :      Tuple					 =		hidden_act
     lowerCamelCase__    :      Union[str, Any]					 =		num_labels
     lowerCamelCase__    :      Optional[int]					 =		scope
     lowerCamelCase__    :      int					 =		len(UpperCAmelCase	)
 def      A_	(      self  :      Optional[Any]	)			->	Tuple:
     lowerCamelCase__    :      List[str]					 =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

     lowerCamelCase__    :      List[str]					 =		self.get_config()

     return config, pixel_values, labels
 def      A_	(      self  :      Dict	)			->	Tuple:
     return ResNetConfig(
         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			,     image_size=self.image_size			,     )
 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Optional[Any]			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      Optional[Any]	)			->	Any:
     lowerCamelCase__    :      List[str]					 =		TFResNetModel(config=UpperCAmelCase	)
     lowerCamelCase__    :      Optional[int]					 =		model(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      A_	(      self  :      Optional[Any]			,     UpperCAmelCase  :      Union[str, Any]			,     UpperCAmelCase  :      Any			,     UpperCAmelCase  :      List[Any]	)			->	Optional[int]:
     lowerCamelCase__    :      Dict					 =		self.num_labels
     lowerCamelCase__    :      List[str]					 =		TFResNetForImageClassification(UpperCAmelCase	)
     lowerCamelCase__    :      Any					 =		model(UpperCAmelCase			,     labels=UpperCAmelCase	)
     self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)	)







 def      A_	(      self  :      List[Any]	)			->	Union[str, Any]:
     lowerCamelCase__    :      str					 =		self.prepare_config_and_inputs()
     lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		config_and_inputs
     lowerCamelCase__    :      Tuple					 =		{'pixel_values': pixel_values}
     return config, inputs_dict


@require_tf
class    lowerCAmelCase							(					__UpperCamelCase,  __UpperCamelCase,  unittest.TestCase			):
 UpperCAmelCase__													=		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 UpperCAmelCase__													=		(
     {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 UpperCAmelCase__													=		False
 UpperCAmelCase__													=		False
 UpperCAmelCase__													=		False
 UpperCAmelCase__													=		False
 UpperCAmelCase__													=		False
 def      A_	(      self  :      Tuple	)			->	int:
     lowerCamelCase__    :      Optional[Any]					 =		TFResNetModelTester(self	)
     lowerCamelCase__    :      Tuple					 =		ConfigTester(self			,     config_class=UpperCAmelCase			,     has_text_modality=UpperCAmelCase	)
 def      A_	(      self  :      int	)			->	List[str]:
     self.create_and_test_config_common_properties()
     self.config_tester.create_and_test_config_to_json_string()
     self.config_tester.create_and_test_config_to_json_file()
     self.config_tester.create_and_test_config_from_and_save_pretrained()
     self.config_tester.create_and_test_config_with_num_labels()
     self.config_tester.check_config_can_be_init_without_params()
     self.config_tester.check_config_arguments_init()
 def      A_	(      self  :      List[Any]	)			->	Optional[int]:
     return
 @unittest.skip(reason='ResNet does not use inputs_embeds'	)
 def      A_	(      self  :      Optional[Any]	)			->	Optional[int]:
     pass
 @unittest.skip(reason='ResNet does not support input and output embeddings'	)
 def      A_	(      self  :      List[Any]	)			->	str:
     pass
 def      A_	(      self  :      List[str]	)			->	int:
     lowerCamelCase__ ,							lowerCamelCase__    :      List[Any]					 =		self.model_tester.prepare_config_and_inputs_for_common()

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

         lowerCamelCase__    :      Dict					 =		['pixel_values']
         self.assertListEqual(arg_names[:1]			,     UpperCAmelCase	)
 def      A_	(      self  :      Union[str, Any]	)			->	Optional[Any]:
     lowerCamelCase__    :      List[str]					 =		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase	)
 def      A_	(      self  :      str	)			->	int:
     def check_hidden_states_output(UpperCAmelCase  :      Any			,     UpperCAmelCase  :      List[Any]			,     UpperCAmelCase  :      Optional[Any]	):
         lowerCamelCase__    :      Union[str, Any]					 =		model_class(UpperCAmelCase	)
         lowerCamelCase__    :      Dict					 =		model(**self._prepare_for_class(UpperCAmelCase			,     UpperCAmelCase	)	)

         lowerCamelCase__    :      List[str]					 =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         lowerCamelCase__    :      str					 =		self.model_tester.num_stages
         self.assertEqual(len(UpperCAmelCase	)			,     expected_num_stages + 1	)

         # ResNet'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]			,     )

     lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		self.model_tester.prepare_config_and_inputs_for_common()
     lowerCamelCase__    :      Optional[Any]					 =		['basic', 'bottleneck']
     for model_class in self.all_model_classes:
         for layer_type in layers_type:
             lowerCamelCase__    :      int					 =		layer_type
             lowerCamelCase__    :      int					 =		True
             check_hidden_states_output(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)

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

             check_hidden_states_output(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)
 def      A_	(      self  :      List[str]	)			->	List[str]:
     lowerCamelCase__    :      Any					 =		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase	)







 @slow
 def      A_	(      self  :      List[str]	)			->	Tuple:
     for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCamelCase__    :      int					 =		TFResNetModel.from_pretrained(UpperCAmelCase	)
         self.assertIsNotNone(UpperCAmelCase	)


def        SCREAMING_SNAKE_CASE      (       )			->     Optional[Any]:
    lowerCamelCase__    :      Optional[Any]					 =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
    return image


@require_tf
@require_vision
class    lowerCAmelCase							(					unittest.TestCase			):
 @cached_property
 def      A_	(      self  :      int	)			->	List[str]:
     return (
         AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
         if is_vision_available()
         else None
     )







 @slow
 def      A_	(      self  :      List[str]	)			->	Dict:
     lowerCamelCase__    :      Union[str, Any]					 =		TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

     lowerCamelCase__    :      str					 =		self.default_image_processor
     lowerCamelCase__    :      Tuple					 =		prepare_img()
     lowerCamelCase__    :      Optional[int]					 =		image_processor(images=UpperCAmelCase			,     return_tensors='tf'	)

     # forward pass
     lowerCamelCase__    :      Union[str, Any]					 =		model(**UpperCAmelCase	)

     # verify the logits
     lowerCamelCase__    :      Union[str, Any]					 =		tf.TensorShape((1, 1000)	)
     self.assertEqual(outputs.logits.shape			,     UpperCAmelCase	)

     lowerCamelCase__    :      Any					 =		tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]	)

     self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,     UpperCAmelCase			,     atol=1e-4	)	)












def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase )			->     set:
    lowerCamelCase__    :      Optional[Any]					 =		set()
    # edges = list of graph's edges
    lowerCamelCase__    :      List[str]					 =		get_edges(_UpperCAmelCase )

    # While there are still elements in edges list, take an arbitrary edge
    # (from_node, to_node) and add his extremity to chosen_vertices and then
    # remove all arcs adjacent to the from_node and to_node
    while edges:
        lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		edges.pop()
        chosen_vertices.add(_UpperCAmelCase )
        chosen_vertices.add(_UpperCAmelCase )
        for edge in edges.copy():
            if from_node in edge or to_node in edge:
                edges.discard(_UpperCAmelCase )
    return chosen_vertices


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase )			->     set:
    lowerCamelCase__    :      Union[str, Any]					 =		set()
    for from_node, to_nodes in graph.items():
        for to_node in to_nodes:
            edges.add((from_node, to_node) )
    return edges


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
    # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")





