import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class 					_lowercase    :






    '''simple docstring'''




    def __init__(    self       ,						lowerCamelCase__       ,						lowerCamelCase__=13       ,						lowerCamelCase__=32       ,						lowerCamelCase__=3       ,						lowerCamelCase__=4       ,						lowerCamelCase__=[10, 20, 30, 40]       ,						lowerCamelCase__=[2, 2, 3, 2]       ,						lowerCamelCase__=True       ,						lowerCamelCase__=True       ,						lowerCamelCase__=37       ,						lowerCamelCase__="gelu"       ,						lowerCamelCase__=10       ,						lowerCamelCase__=0.0_2       ,						lowerCamelCase__=["stage2", "stage3", "stage4"]       ,						lowerCamelCase__=[2, 3, 4]       ,						lowerCamelCase__=None       ,						):
       lowerCAmelCase_:							Any       =	parent
       lowerCAmelCase_:							Optional[int]       =	batch_size
       lowerCAmelCase_:							List[str]       =	image_size
       lowerCAmelCase_:							Union[str, Any]       =	num_channels
       lowerCAmelCase_:							Dict       =	num_stages
       lowerCAmelCase_:							Tuple       =	hidden_sizes
       lowerCAmelCase_:							Optional[Any]       =	depths
       lowerCAmelCase_:							List[Any]       =	is_training
       lowerCAmelCase_:							List[Any]       =	use_labels
       lowerCAmelCase_:							List[str]       =	intermediate_size
       lowerCAmelCase_:							Union[str, Any]       =	hidden_act
       lowerCAmelCase_:							Union[str, Any]       =	num_labels
       lowerCAmelCase_:							List[str]       =	initializer_range
       lowerCAmelCase_:							Tuple       =	out_features
       lowerCAmelCase_:							List[Any]       =	out_indices
       lowerCAmelCase_:							Any       =	scope




    def      _a    (    self ):
       lowerCAmelCase_:							Optional[Any]       =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

       lowerCAmelCase_:							Optional[int]       =	self.get_config()
       return config, pixel_values, labels




    def      _a    (    self ):
       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=lowerCamelCase__       ,						initializer_range=self.initializer_range       ,						out_features=self.out_features       ,						out_indices=self.out_indices       ,						num_labels=self.num_labels       ,						)




    def      _a    (    self       ,						lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ ):
       lowerCAmelCase_:							List[Any]       =	ConvNextModel(config=lowerCamelCase__ )
       model.to(lowerCamelCase__ )
       model.eval()
       lowerCAmelCase_:							str       =	model(lowerCamelCase__ )
       # 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       ,						lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ ):
       lowerCAmelCase_:							List[str]       =	ConvNextForImageClassification(lowerCamelCase__ )
       model.to(lowerCamelCase__ )
       model.eval()
       lowerCAmelCase_:							List[Any]       =	model(lowerCamelCase__       ,						labels=lowerCamelCase__ )
       self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.num_labels) )




    def      _a    (    self       ,						lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ ):
       lowerCAmelCase_:							List[str]       =	ConvNextBackbone(config=lowerCamelCase__ )
       model.to(lowerCamelCase__ )
       model.eval()
       lowerCAmelCase_:							int       =	model(lowerCamelCase__ )

       # verify hidden states
       self.parent.assertEqual(len(result.feature_maps )       ,						len(config.out_features ) )
       self.parent.assertListEqual(list(result.feature_maps[0].shape )       ,						[self.batch_size, self.hidden_sizes[1], 4, 4] )

       # verify channels
       self.parent.assertEqual(len(model.channels )       ,						len(config.out_features ) )
       self.parent.assertListEqual(model.channels       ,						config.hidden_sizes[1:] )

       # verify backbone works with out_features=None
       lowerCAmelCase_:							Optional[int]       =	None
       lowerCAmelCase_:							Union[str, Any]       =	ConvNextBackbone(config=lowerCamelCase__ )
       model.to(lowerCamelCase__ )
       model.eval()
       lowerCAmelCase_:							int       =	model(lowerCamelCase__ )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps )       ,						1 )
       self.parent.assertListEqual(list(result.feature_maps[0].shape )       ,						[self.batch_size, self.hidden_sizes[-1], 1, 1] )

       # verify channels
       self.parent.assertEqual(len(model.channels )       ,						1 )
       self.parent.assertListEqual(model.channels       ,						[config.hidden_sizes[-1]] )




    def      _a    (    self ):
       lowerCAmelCase_:							int       =	self.prepare_config_and_inputs()
       lowerCAmelCase_  ,	lowerCAmelCase_  ,	lowerCAmelCase_:							List[str]       =	config_and_inputs
       lowerCAmelCase_:							List[Any]       =	{"pixel_values": pixel_values}
       return config, inputs_dict





@require_torch
class 					_lowercase    (     UpperCAmelCase__ ,  UpperCAmelCase__ ,  unittest.TestCase			):






    '''simple docstring'''
    SCREAMING_SNAKE_CASE:				Optional[Any]          =    (
        (
            ConvNextModel,
            ConvNextForImageClassification,
            ConvNextBackbone,
        )
        if is_torch_available()
        else ()
    )
    SCREAMING_SNAKE_CASE:				Dict          =    (
        {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
        if is_torch_available()
        else {}
    )

    SCREAMING_SNAKE_CASE:				Any          =    True
    SCREAMING_SNAKE_CASE:				List[str]          =    False
    SCREAMING_SNAKE_CASE:				Optional[Any]          =    False
    SCREAMING_SNAKE_CASE:				List[str]          =    False
    SCREAMING_SNAKE_CASE:				Optional[Any]          =    False




    def      _a    (    self ):
       lowerCAmelCase_:							Any       =	ConvNextModelTester(self )
       lowerCAmelCase_:							str       =	ConfigTester(self       ,						config_class=lowerCamelCase__       ,						has_text_modality=lowerCamelCase__       ,						hidden_size=37 )




    def      _a    (    self ):
       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 ):
       return




    @unittest.skip(reason="ConvNext does not use inputs_embeds" )
    def      _a    (    self ):
       pass




    @unittest.skip(reason="ConvNext does not support input and output embeddings" )
    def      _a    (    self ):
       pass




    @unittest.skip(reason="ConvNext does not use feedforward chunking" )
    def      _a    (    self ):
       pass




    def      _a    (    self ):
       lowerCAmelCase_  ,	lowerCAmelCase_:							Union[str, Any]       =	self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase_:							List[str]       =	["pixel_values"]
          self.assertListEqual(arg_names[:1]       ,						lowerCamelCase__ )




    def      _a    (    self ):
       lowerCAmelCase_:							Dict       =	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase__ )




    def      _a    (    self ):
       lowerCAmelCase_:							Any       =	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*lowerCamelCase__ )




    def      _a    (    self ):
       def check_hidden_states_output(lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ ):
          lowerCAmelCase_:							List[str]       =	model_class(lowerCamelCase__ )
          model.to(lowerCamelCase__ )
          model.eval()

          with torch.no_grad():
             lowerCAmelCase_:							int       =	model(**self._prepare_for_class(lowerCamelCase__       ,						lowerCamelCase__ ) )

          lowerCAmelCase_:							Tuple       =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowerCAmelCase_:							Optional[int]       =	self.model_tester.num_stages
          self.assertEqual(len(lowerCamelCase__ )       ,						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]       ,						)

       lowerCAmelCase_  ,	lowerCAmelCase_:							str       =	self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowerCAmelCase_:							Optional[int]       =	True
          check_hidden_states_output(lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowerCAmelCase_:							Union[str, Any]       =	True

          check_hidden_states_output(lowerCamelCase__       ,						lowerCamelCase__       ,						lowerCamelCase__ )




    def      _a    (    self ):
       lowerCAmelCase_:							Tuple       =	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ )




    @slow
    def      _a    (    self ):
       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_:							Union[str, Any]       =	ConvNextModel.from_pretrained(lowerCamelCase__ )
          self.assertIsNotNone(lowerCamelCase__ )





def 		snake_case__	(		):
   lowerCAmelCase_:							List[Any]       =	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
   return image

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






    '''simple docstring'''




    @cached_property
    def      _a    (    self ):
       return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224" ) if is_vision_available() else None




    @slow
    def      _a    (    self ):
       lowerCAmelCase_:							Optional[Any]       =	ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224" ).to(lowerCamelCase__ )

       lowerCAmelCase_:							Optional[Any]       =	self.default_image_processor
       lowerCAmelCase_:							Tuple       =	prepare_img()
       lowerCAmelCase_:							List[str]       =	image_processor(images=lowerCamelCase__       ,						return_tensors="pt" ).to(lowerCamelCase__ )

       # forward pass
       with torch.no_grad():
          lowerCAmelCase_:							Tuple       =	model(**lowerCamelCase__ )

       # verify the logits
       lowerCAmelCase_:							Optional[Any]       =	torch.Size((1, 1_000) )
       self.assertEqual(outputs.logits.shape       ,						lowerCamelCase__ )

       lowerCAmelCase_:							Tuple       =	torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1] ).to(lowerCamelCase__ )

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





@require_torch
class 					_lowercase    (     unittest.TestCase ,  UpperCAmelCase__			):






    '''simple docstring'''
    SCREAMING_SNAKE_CASE:				Union[str, Any]          =    (ConvNextBackbone,) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE:				List[Any]          =    ConvNextConfig

    SCREAMING_SNAKE_CASE:				Optional[int]          =    False




    def      _a    (    self ):
       lowerCAmelCase_:							Union[str, Any]       =	ConvNextModelTester(self )
from __future__ import annotations
def 		snake_case__	(		lowercase							,				lowercase					):
   print(F'''Vertex\tShortest Distance from vertex {src}'''					)
   for i, d in enumerate(lowercase					):
      print(F'''{i}\t\t{d}'''					)
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   for j in range(lowercase					):
      lowerCAmelCase_  ,	lowerCAmelCase_  ,	lowerCAmelCase_:							List[str]       =	(graph[j][k] for k in ["src", "dst", "weight"])
      if distance[u] != float("inf"					) and distance[u] + w < distance[v]:
         return True
   return False
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							int       =	[float("inf"					)] * vertex_count
   lowerCAmelCase_:							Dict       =	0.0

   for _ in range(vertex_count - 1					):
      for j in range(lowercase					):
         lowerCAmelCase_  ,	lowerCAmelCase_  ,	lowerCAmelCase_:							Any       =	(graph[j][k] for k in ["src", "dst", "weight"])

         if distance[u] != float("inf"					) and distance[u] + w < distance[v]:
            lowerCAmelCase_:							List[str]       =	distance[u] + w

   lowerCAmelCase_:							str       =	check_negative_cycle(lowercase							,				lowercase							,				lowercase					)
   if negative_cycle_exists:
      raise Exception("Negative cycle found"					)

   return distance


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 a  :      List[str]            =    int(input("""Enter number of vertices: """).strip())
 a  :      Any            =    int(input("""Enter number of edges: """).strip())

 a  :      list[dict[str, int]]            =    [{} for _ in range(E)]

 for i in range(E):
  print("""Edge """, i + 1)
  a     , a     , a  :      Optional[int]            =    (
      int(x)
      for x in input("""Enter source, destination, weight: """).strip().split(""" """)
  )
  a  :      Optional[int]            =    {"""src""": src, """dst""": dest, """weight""": weight}

 a  :      List[Any]            =    int(input("""\nEnter shortest path source:""").strip())
 a  :      Tuple            =    bellman_ford(graph, V, E, source)
 print_distance(shortest_distance, 0)