



"""simple docstring"""




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



      def __init__(	self	:      Union[str, Any]	,      A	:      Optional[Any]	,      A	:      Dict=1_3	,      A	:      Any=3_2	,      A	:      Optional[Any]=3	,      A	:      int=4	,      A	:      Any=[1_0, 2_0, 3_0, 4_0]	,      A	:      int=[2, 2, 3, 2]	,      A	:      List[Any]=True	,      A	:      str=True	,      A	:      Optional[Any]=3_7	,      A	:      List[str]="gelu"	,      A	:      List[Any]=1_0	,      A	:      Dict=0.02	,      A	:      List[str]=["stage2", "stage3", "stage4"]	,      A	:      List[str]=[2, 3, 4]	,      A	:      List[str]=None	,      ):
           _UpperCAmelCase     :      Dict														=       parent
           _UpperCAmelCase     :      List[str]														=       batch_size
           _UpperCAmelCase     :      int														=       image_size
           _UpperCAmelCase     :      List[Any]														=       num_channels
           _UpperCAmelCase     :      Any														=       num_stages
           _UpperCAmelCase     :      str														=       hidden_sizes
           _UpperCAmelCase     :      Optional[int]														=       depths
           _UpperCAmelCase     :      Union[str, Any]														=       is_training
           _UpperCAmelCase     :      Any														=       use_labels
           _UpperCAmelCase     :      Tuple														=       intermediate_size
           _UpperCAmelCase     :      Optional[Any]														=       hidden_act
           _UpperCAmelCase     :      Tuple														=       num_labels
           _UpperCAmelCase     :      List[Any]														=       initializer_range
           _UpperCAmelCase     :      List[Any]														=       out_features
           _UpperCAmelCase     :      Tuple														=       out_indices
           _UpperCAmelCase     :      Optional[Any]														=       scope



      def 		snake_case_   (	self	:      Tuple		):
           _UpperCAmelCase     :      Dict														=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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



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



      def 		snake_case_   (	self	:      int	,      A	:      str	,      A	:      List[str]	,      A	:      Optional[Any]		):
           _UpperCAmelCase     :      List[Any]														=       ConvNextModel(config=A		)
           model.to(A		)
           model.eval()
           _UpperCAmelCase     :      List[str]														=       model(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 // 3_2, self.image_size // 3_2)	,      )



      def 		snake_case_   (	self	:      Optional[Any]	,      A	:      List[str]	,      A	:      Optional[int]	,      A	:      List[str]		):
           _UpperCAmelCase     :      Dict														=       ConvNextForImageClassification(A		)
           model.to(A		)
           model.eval()
           _UpperCAmelCase     :      Union[str, Any]														=       model(A	,      labels=A		)
           self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)		)



      def 		snake_case_   (	self	:      int	,      A	:      Any	,      A	:      Tuple	,      A	:      Dict		):
           _UpperCAmelCase     :      Tuple														=       ConvNextBackbone(config=A		)
           model.to(A		)
           model.eval()
           _UpperCAmelCase     :      Tuple														=       model(A		)

           # 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
           _UpperCAmelCase     :      Dict														=       None
           _UpperCAmelCase     :      Dict														=       ConvNextBackbone(config=A		)
           model.to(A		)
           model.eval()
           _UpperCAmelCase     :      Optional[Any]														=       model(A		)

           # 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 		snake_case_   (	self	:      Tuple		):
           _UpperCAmelCase     :      Dict														=       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_torch
class       UpperCAmelCase_    (							_UpperCamelCase			,     _UpperCamelCase			,     unittest.TestCase		):
      __SCREAMING_SNAKE_CASE		:  List[Any]						=					(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      __SCREAMING_SNAKE_CASE		:  List[Any]						=					(
          {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      __SCREAMING_SNAKE_CASE		:  Union[str, Any]						=					True
      __SCREAMING_SNAKE_CASE		:  List[str]						=					False
      __SCREAMING_SNAKE_CASE		:  Optional[Any]						=					False
      __SCREAMING_SNAKE_CASE		:  Any						=					False
      __SCREAMING_SNAKE_CASE		:  str						=					False



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase     :      Union[str, Any]														=       ConvNextModelTester(self		)
           _UpperCAmelCase     :      List[str]														=       ConfigTester(self	,      config_class=A	,      has_text_modality=A	,      hidden_size=3_7		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           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 		snake_case_   (	self	:      Union[str, Any]		):
           return



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



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



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



      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Union[str, Any]														=       self.model_tester.prepare_config_and_inputs_for_common()

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

                _UpperCAmelCase     :      Optional[Any]														=       ["pixel_values"]
                self.assertListEqual(arg_names[:1]	,      A		)



      def 		snake_case_   (	self	:      Dict		):
           _UpperCAmelCase     :      Union[str, Any]														=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*A		)



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      List[str]														=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*A		)



      def 		snake_case_   (	self	:      Dict		):
           def check_hidden_states_output(A	:      List[str]	,      A	:      Optional[int]	,      A	:      Union[str, Any]		):
                _UpperCAmelCase     :      Optional[int]														=       model_class(A		)
                model.to(A		)
                model.eval()

                with torch.no_grad():
                     _UpperCAmelCase     :      Optional[int]														=       model(**self._prepare_for_class(A	,      A		)		)

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

                _UpperCAmelCase     :      Dict														=       self.model_tester.num_stages
                self.assertEqual(len(A		)	,      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]	,      )

           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                _UpperCAmelCase     :      Dict														=       True
                check_hidden_states_output(A	,      A	,      A		)

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                _UpperCAmelCase     :      Tuple														=       True

                check_hidden_states_output(A	,      A	,      A		)



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      Tuple														=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*A		)



      @slow
      def 		snake_case_   (	self	:      List[str]		):
           for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _UpperCAmelCase     :      Optional[int]														=       ConvNextModel.from_pretrained(A		)
                self.assertIsNotNone(A		)







def 		__snake_case		( )    ->  Tuple:





     '''simple docstring'''

     _UpperCAmelCase     :      Union[str, Any]														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
     return image






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



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



      @slow
      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase     :      Tuple														=       ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"		).to(A		)

           _UpperCAmelCase     :      Optional[int]														=       self.default_image_processor
           _UpperCAmelCase     :      Tuple														=       prepare_img()
           _UpperCAmelCase     :      Optional[Any]														=       image_processor(images=A	,      return_tensors="pt"		).to(A		)

           # forward pass
           with torch.no_grad():
                _UpperCAmelCase     :      int														=       model(**A		)

           # verify the logits
           _UpperCAmelCase     :      List[str]														=       torch.Size((1, 1_0_0_0)		)
           self.assertEqual(outputs.logits.shape	,      A		)

           _UpperCAmelCase     :      Dict														=       torch.tensor([-0.0_260, -0.4_739, 0.1_911]		).to(A		)

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







@require_torch
class       UpperCAmelCase_    (							unittest.TestCase			,     _UpperCamelCase		):
      __SCREAMING_SNAKE_CASE		:  int						=					(ConvNextBackbone,) if is_torch_available() else ()
      __SCREAMING_SNAKE_CASE		:  int						=					ConvNextConfig

      __SCREAMING_SNAKE_CASE		:  Dict						=					False



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      Union[str, Any]														=       ConvNextModelTester(self		)





"""simple docstring"""




import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
 from PIL import Image

 from transformers import CLIPSegProcessor, ViTImageProcessor






@require_vision
class       UpperCAmelCase_    (							unittest.TestCase		):



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Tuple														=       tempfile.mkdtemp()

           # fmt: off
           _UpperCAmelCase     :      List[str]														=       ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
           # fmt: on
           _UpperCAmelCase     :      Tuple														=       dict(zip(A	,      range(len(A		)		)		)		)
           _UpperCAmelCase     :      Any														=       ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
           _UpperCAmelCase     :      Optional[Any]														=       {"unk_token": "<unk>"}

           _UpperCAmelCase     :      List[Any]														=       os.path.join(self.tmpdirname	,      VOCAB_FILES_NAMES["vocab_file"]		)
           _UpperCAmelCase     :      int														=       os.path.join(self.tmpdirname	,      VOCAB_FILES_NAMES["merges_file"]		)
           with open(self.vocab_file	,      "w"	,      encoding="utf-8"		) as fp:
                fp.write(json.dumps(A		) + "\n"		)
           with open(self.merges_file	,      "w"	,      encoding="utf-8"		) as fp:
                fp.write("\n".join(A		)		)

           _UpperCAmelCase     :      List[Any]														=       {
               "do_resize": True,
               "size": 2_0,
               "do_center_crop": True,
               "crop_size": 1_8,
               "do_normalize": True,
               "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073],
               "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711],
           }
           _UpperCAmelCase     :      Tuple														=       os.path.join(self.tmpdirname	,      A		)
           with open(self.image_processor_file	,      "w"	,      encoding="utf-8"		) as fp:
                json.dump(A	,      A		)



      def 		snake_case_   (	self	:      int	,      **A	:      Any		):
           return CLIPTokenizer.from_pretrained(self.tmpdirname	,      **A		)



      def 		snake_case_   (	self	:      List[str]	,      **A	:      Tuple		):
           return CLIPTokenizerFast.from_pretrained(self.tmpdirname	,      **A		)



      def 		snake_case_   (	self	:      Any	,      **A	:      Optional[Any]		):
           return ViTImageProcessor.from_pretrained(self.tmpdirname	,      **A		)



      def 		snake_case_   (	self	:      Dict		):
           shutil.rmtree(self.tmpdirname		)



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase     :      int														=       [np.random.randint(2_5_5	,      size=(3, 3_0, 4_0_0)	,      dtype=np.uinta		)]

           _UpperCAmelCase     :      str														=       [Image.fromarray(np.moveaxis(A	,      0	,      -1		)		) for x in image_inputs]

           return image_inputs



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase     :      str														=       self.get_tokenizer()
           _UpperCAmelCase     :      int														=       self.get_rust_tokenizer()
           _UpperCAmelCase     :      List[str]														=       self.get_image_processor()

           _UpperCAmelCase     :      Union[str, Any]														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)
           processor_slow.save_pretrained(self.tmpdirname		)
           _UpperCAmelCase     :      Dict														=       CLIPSegProcessor.from_pretrained(self.tmpdirname	,      use_fast=A		)

           _UpperCAmelCase     :      Any														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)
           processor_fast.save_pretrained(self.tmpdirname		)
           _UpperCAmelCase     :      int														=       CLIPSegProcessor.from_pretrained(self.tmpdirname		)

           self.assertEqual(processor_slow.tokenizer.get_vocab()	,      tokenizer_slow.get_vocab()		)
           self.assertEqual(processor_fast.tokenizer.get_vocab()	,      tokenizer_fast.get_vocab()		)
           self.assertEqual(tokenizer_slow.get_vocab()	,      tokenizer_fast.get_vocab()		)
           self.assertIsInstance(processor_slow.tokenizer	,      A		)
           self.assertIsInstance(processor_fast.tokenizer	,      A		)

           self.assertEqual(processor_slow.image_processor.to_json_string()	,      image_processor.to_json_string()		)
           self.assertEqual(processor_fast.image_processor.to_json_string()	,      image_processor.to_json_string()		)
           self.assertIsInstance(processor_slow.image_processor	,      A		)
           self.assertIsInstance(processor_fast.image_processor	,      A		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Union[str, Any]														=       CLIPSegProcessor(tokenizer=self.get_tokenizer()	,      image_processor=self.get_image_processor()		)
           processor.save_pretrained(self.tmpdirname		)

           _UpperCAmelCase     :      List[str]														=       self.get_tokenizer(bos_token="(BOS)"	,      eos_token="(EOS)"		)
           _UpperCAmelCase     :      int														=       self.get_image_processor(do_normalize=A	,      padding_value=1.0		)

           _UpperCAmelCase     :      Optional[Any]														=       CLIPSegProcessor.from_pretrained(
               self.tmpdirname	,      bos_token="(BOS)"	,      eos_token="(EOS)"	,      do_normalize=A	,      padding_value=1.0		)

           self.assertEqual(processor.tokenizer.get_vocab()	,      tokenizer_add_kwargs.get_vocab()		)
           self.assertIsInstance(processor.tokenizer	,      A		)

           self.assertEqual(processor.image_processor.to_json_string()	,      image_processor_add_kwargs.to_json_string()		)
           self.assertIsInstance(processor.image_processor	,      A		)



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      Any														=       self.get_image_processor()
           _UpperCAmelCase     :      Optional[int]														=       self.get_tokenizer()

           _UpperCAmelCase     :      Dict														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)

           _UpperCAmelCase     :      Dict														=       self.prepare_image_inputs()

           _UpperCAmelCase     :      int														=       image_processor(A	,      return_tensors="np"		)
           _UpperCAmelCase     :      int														=       processor(images=A	,      return_tensors="np"		)

           for key in input_feat_extract.keys():
                self.assertAlmostEqual(input_feat_extract[key].sum()	,      input_processor[key].sum()	,      delta=1e-2		)



      def 		snake_case_   (	self	:      Dict		):
           _UpperCAmelCase     :      List[Any]														=       self.get_image_processor()
           _UpperCAmelCase     :      Dict														=       self.get_tokenizer()

           _UpperCAmelCase     :      Optional[Any]														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)

           _UpperCAmelCase     :      Tuple														=       "lower newer"

           _UpperCAmelCase     :      Any														=       processor(text=A		)

           _UpperCAmelCase     :      int														=       tokenizer(A		)

           for key in encoded_tok.keys():
                self.assertListEqual(encoded_tok[key]	,      encoded_processor[key]		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      List[str]														=       self.get_image_processor()
           _UpperCAmelCase     :      Union[str, Any]														=       self.get_tokenizer()

           _UpperCAmelCase     :      Tuple														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)

           _UpperCAmelCase     :      List[Any]														=       "lower newer"
           _UpperCAmelCase     :      List[Any]														=       self.prepare_image_inputs()

           _UpperCAmelCase     :      str														=       processor(text=A	,      images=A		)

           self.assertListEqual(list(inputs.keys()		)	,      ["input_ids", "attention_mask", "pixel_values"]		)

           # test if it raises when no input is passed
           with pytest.raises(A		):
                processor()



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Dict														=       self.get_image_processor()
           _UpperCAmelCase     :      Optional[int]														=       self.get_tokenizer()

           _UpperCAmelCase     :      str														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)

           _UpperCAmelCase     :      List[Any]														=       self.prepare_image_inputs()
           _UpperCAmelCase     :      int														=       self.prepare_image_inputs()

           _UpperCAmelCase     :      Any														=       processor(images=A	,      visual_prompt=A		)

           self.assertListEqual(list(inputs.keys()		)	,      ["pixel_values", "conditional_pixel_values"]		)

           # test if it raises when no input is passed
           with pytest.raises(A		):
                processor()



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Dict														=       self.get_image_processor()
           _UpperCAmelCase     :      Optional[Any]														=       self.get_tokenizer()

           _UpperCAmelCase     :      Optional[Any]														=       CLIPSegProcessor(tokenizer=A	,      image_processor=A		)

           _UpperCAmelCase     :      str														=       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

           _UpperCAmelCase     :      Union[str, Any]														=       processor.batch_decode(A		)
           _UpperCAmelCase     :      List[Any]														=       tokenizer.batch_decode(A		)

           self.assertListEqual(A	,      A		)
