



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




    '''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.02,		lowerCamelCase__=["stage2", "stage3", "stage4"],		lowerCamelCase__=[2, 3, 4],		lowerCamelCase__=None,		):
        A			:	Optional[Any]										=       parent
        A			:	Optional[Any]										=       batch_size
        A			:	Tuple										=       image_size
        A			:	List[str]										=       num_channels
        A			:	Any										=       num_stages
        A			:	Optional[Any]										=       hidden_sizes
        A			:	Tuple										=       depths
        A			:	Any										=       is_training
        A			:	Dict										=       use_labels
        A			:	str										=       intermediate_size
        A			:	List[str]										=       hidden_act
        A			:	Any										=       num_labels
        A			:	str										=       initializer_range
        A			:	Union[str, Any]										=       out_features
        A			:	Dict										=       out_indices
        A			:	int										=       scope






    def       _lowerCAmelCase (	self		):
        A			:	Optional[int]										=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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






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






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        A			:	Optional[int]										=       ConvNextBackbone(config=lowerCamelCase__		)
        model.to(lowerCamelCase__		)
        model.eval()
        A			:	Any										=       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
        A			:	Tuple										=       None
        A			:	List[str]										=       ConvNextBackbone(config=lowerCamelCase__		)
        model.to(lowerCamelCase__		)
        model.eval()
        A			:	Any										=       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       _lowerCAmelCase (	self		):
        A			:	Union[str, Any]										=       self.prepare_config_and_inputs()
        A					,							A					,							A			:	str										=       config_and_inputs
        A			:	Optional[int]										=       {"""pixel_values""": pixel_values}
        return config, inputs_dict






@require_torch
class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__			,						SCREAMING_SNAKE_CASE__			,						unittest.TestCase   ):




    '''simple docstring'''






    __lowerCamelCase      :			Optional[Any] =				(
        (
            ConvNextModel,
            ConvNextForImageClassification,
            ConvNextBackbone,
        )
        if is_torch_available()
        else ()
    )
    __lowerCamelCase      :			Optional[int] =				(
        {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
        if is_torch_available()
        else {}
    )

    __lowerCamelCase      :			Optional[Any] =				True
    __lowerCamelCase      :			Optional[int] =				False
    __lowerCamelCase      :			Tuple =				False
    __lowerCamelCase      :			Union[str, Any] =				False
    __lowerCamelCase      :			List[str] =				False






    def       _lowerCAmelCase (	self		):
        A			:	List[str]										=       ConvNextModelTester(self		)
        A			:	str										=       ConfigTester(self,		config_class=lowerCamelCase__,		has_text_modality=lowerCamelCase__,		hidden_size=37		)






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






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






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






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






    def       _lowerCAmelCase (	self		):
        A					,							A			:	str										=       self.model_tester.prepare_config_and_inputs_for_common()

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

            A			:	int										=       ["""pixel_values"""]
            self.assertListEqual(arg_names[:1],		lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        A			:	Union[str, Any]										=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        def check_hidden_states_output(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
            A			:	Optional[int]										=       model_class(lowerCamelCase__		)
            model.to(lowerCamelCase__		)
            model.eval()

            with torch.no_grad():
                A			:	Any										=       model(**self._prepare_for_class(lowerCamelCase__,		lowerCamelCase__		)		)

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

            A			:	Union[str, Any]										=       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],		)

        A					,							A			:	Optional[Any]										=       self.model_tester.prepare_config_and_inputs_for_common()

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

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

            check_hidden_states_output(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        A			:	List[Any]										=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__		)






    @slow
    def       _lowerCAmelCase (	self		):
        for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A			:	int										=       ConvNextModel.from_pretrained(lowerCamelCase__		)
            self.assertIsNotNone(lowerCamelCase__		)




def      __UpperCamelCase     (  )	->  Any:



    """simple docstring"""






    A			:	List[str]										=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
    return image






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




    '''simple docstring'''






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






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

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

        # forward pass
        with torch.no_grad():
            A			:	Optional[int]										=       model(**lowerCamelCase__		)

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

        A			:	Tuple										=       torch.tensor([-0.0260, -0.4739, 0.1911]		).to(lowerCamelCase__		)

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






@require_torch
class SCREAMING_SNAKE_CASE__					(		unittest.TestCase			,						SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			Union[str, Any] =				(ConvNextBackbone,) if is_torch_available() else ()
    __lowerCamelCase      :			Optional[int] =				ConvNextConfig

    __lowerCamelCase      :			str =				False






    def       _lowerCAmelCase (	self		):
        A			:	int										=       ConvNextModelTester(self		)







import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
     from PIL import Image

     from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor






@require_vision
class SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self		):
        A			:	str										=       tempfile.mkdtemp()

        A			:	Any										=       [
            """[UNK]""",
            """[CLS]""",
            """[SEP]""",
            """[PAD]""",
            """[MASK]""",
            """的""",
            """价""",
            """格""",
            """是""",
            """15""",
            """便""",
            """alex""",
            """##andra""",
            """，""",
            """。""",
            """-""",
            """t""",
            """shirt""",
        ]
        A			:	Any										=       os.path.join(self.tmpdirname,		VOCAB_FILES_NAMES["""vocab_file"""]		)
        with open(self.vocab_file,		"""w""",		encoding="""utf-8"""		) as vocab_writer:
            vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

        A			:	Any										=       {
            """do_resize""": True,
            """size""": {"""height""": 224, """width""": 224},
            """do_center_crop""": True,
            """crop_size""": {"""height""": 18, """width""": 18},
            """do_normalize""": True,
            """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073],
            """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711],
            """do_convert_rgb""": True,
        }
        A			:	int										=       os.path.join(self.tmpdirname,		lowerCamelCase__		)
        with open(self.image_processor_file,		"""w""",		encoding="""utf-8"""		) as fp:
            json.dump(lowerCamelCase__,		lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		**lowerCamelCase__		):
        return BertTokenizer.from_pretrained(self.tmpdirname,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		**lowerCamelCase__		):
        return BertTokenizerFast.from_pretrained(self.tmpdirname,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		**lowerCamelCase__		):
        return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        shutil.rmtree(self.tmpdirname		)






    def       _lowerCAmelCase (	self		):
        A			:	Optional[int]										=       [np.random.randint(255,		size=(3, 30, 400),		dtype=np.uinta		)]

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

        return image_inputs






    def       _lowerCAmelCase (	self		):
        A			:	List[Any]										=       self.get_tokenizer()
        A			:	Dict										=       self.get_rust_tokenizer()
        A			:	List[Any]										=       self.get_image_processor()

        A			:	int										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)
        processor_slow.save_pretrained(self.tmpdirname		)
        A			:	Optional[Any]										=       ChineseCLIPProcessor.from_pretrained(self.tmpdirname,		use_fast=lowerCamelCase__		)

        A			:	str										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)
        processor_fast.save_pretrained(self.tmpdirname		)
        A			:	Tuple										=       ChineseCLIPProcessor.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,		lowerCamelCase__		)
        self.assertIsInstance(processor_fast.tokenizer,		lowerCamelCase__		)

        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,		lowerCamelCase__		)
        self.assertIsInstance(processor_fast.image_processor,		lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        A			:	str										=       ChineseCLIPProcessor(tokenizer=self.get_tokenizer(),		image_processor=self.get_image_processor()		)
        processor.save_pretrained(self.tmpdirname		)

        A			:	Optional[int]										=       self.get_tokenizer(cls_token="""(CLS)""",		sep_token="""(SEP)"""		)
        A			:	Optional[int]										=       self.get_image_processor(do_normalize=lowerCamelCase__		)

        A			:	Optional[int]										=       ChineseCLIPProcessor.from_pretrained(
            self.tmpdirname,		cls_token="""(CLS)""",		sep_token="""(SEP)""",		do_normalize=lowerCamelCase__		)

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

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






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       self.get_image_processor()
        A			:	List[str]										=       self.get_tokenizer()

        A			:	List[str]										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)

        A			:	Any										=       self.prepare_image_inputs()

        A			:	Union[str, Any]										=       image_processor(lowerCamelCase__,		return_tensors="""np"""		)
        A			:	str										=       processor(images=lowerCamelCase__,		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       _lowerCAmelCase (	self		):
        A			:	List[str]										=       self.get_image_processor()
        A			:	Tuple										=       self.get_tokenizer()

        A			:	str										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)

        A			:	Any										=       """Alexandra，T-shirt的价格是15便士。"""

        A			:	Optional[Any]										=       processor(text=lowerCamelCase__		)

        A			:	int										=       tokenizer(lowerCamelCase__		)

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






    def       _lowerCAmelCase (	self		):
        A			:	Dict										=       self.get_image_processor()
        A			:	List[str]										=       self.get_tokenizer()

        A			:	int										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)

        A			:	str										=       """Alexandra，T-shirt的价格是15便士。"""
        A			:	Dict										=       self.prepare_image_inputs()

        A			:	Optional[int]										=       processor(text=lowerCamelCase__,		images=lowerCamelCase__		)

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

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






    def       _lowerCAmelCase (	self		):
        A			:	Union[str, Any]										=       self.get_image_processor()
        A			:	List[str]										=       self.get_tokenizer()

        A			:	List[str]										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)

        A			:	int										=       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

        A			:	List[Any]										=       processor.batch_decode(lowerCamelCase__		)
        A			:	str										=       tokenizer.batch_decode(lowerCamelCase__		)

        self.assertListEqual(lowerCamelCase__,		lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        A			:	List[str]										=       self.get_image_processor()
        A			:	List[str]										=       self.get_tokenizer()

        A			:	Any										=       ChineseCLIPProcessor(tokenizer=lowerCamelCase__,		image_processor=lowerCamelCase__		)

        A			:	List[Any]										=       """Alexandra，T-shirt的价格是15便士。"""
        A			:	Optional[Any]										=       self.prepare_image_inputs()

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

        self.assertListEqual(list(inputs.keys()		),		processor.model_input_names		)


