

"""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 CLIPImageProcessor, CLIPProcessor






@require_vision
class 			__a					(						unittest.TestCase       ):





       """simple docstring"""


       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				tempfile.mkdtemp()

        # fmt: off
        lowerCAmelCase__   :				Optional[int] 			=				["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
        lowerCAmelCase__   :				Tuple 			=				dict(zip(snake_case			,					range(len(snake_case   )   )   )   )
        lowerCAmelCase__   :				List[Any] 			=				["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
        lowerCAmelCase__   :				Tuple 			=				{"unk_token": "<unk>"}

        lowerCAmelCase__   :				str 			=				os.path.join(self.tmpdirname			,					VOCAB_FILES_NAMES["vocab_file"]   )
        lowerCAmelCase__   :				List[Any] 			=				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(snake_case   ) + "\n"   )
        with open(self.merges_file			,					"w"			,					encoding="utf-8"   ) as fp:
         fp.write("\n".join(snake_case   )   )

        lowerCAmelCase__   :				Optional[Any] 			=				{
            "do_resize": True,
            "size": 20,
            "do_center_crop": True,
            "crop_size": 18,
            "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],
        }
        lowerCAmelCase__   :				str 			=				os.path.join(self.tmpdirname			,					snake_case   )
        with open(self.image_processor_file			,					"w"			,					encoding="utf-8"   ) as fp:
         json.dump(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					**snake_case   ):





        """simple docstring"""

        return CLIPTokenizer.from_pretrained(self.tmpdirname			,					**snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					**snake_case   ):





        """simple docstring"""

        return CLIPTokenizerFast.from_pretrained(self.tmpdirname			,					**snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					**snake_case   ):





        """simple docstring"""

        return CLIPImageProcessor.from_pretrained(self.tmpdirname			,					**snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        shutil.rmtree(self.tmpdirname   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				[np.random.randint(255			,					size=(3, 30, 400)			,					dtype=np.uinta   )]

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

        return image_inputs






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				int 			=				self.get_tokenizer()
        lowerCAmelCase__   :				Union[str, Any] 			=				self.get_rust_tokenizer()
        lowerCAmelCase__   :				str 			=				self.get_image_processor()

        lowerCAmelCase__   :				Dict 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )
        processor_slow.save_pretrained(self.tmpdirname   )
        lowerCAmelCase__   :				Tuple 			=				CLIPProcessor.from_pretrained(self.tmpdirname			,					use_fast=snake_case   )

        lowerCAmelCase__   :				Tuple 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )
        processor_fast.save_pretrained(self.tmpdirname   )
        lowerCAmelCase__   :				Union[str, Any] 			=				CLIPProcessor.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			,					snake_case   )
        self.assertIsInstance(processor_fast.tokenizer			,					snake_case   )

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				CLIPProcessor(tokenizer=self.get_tokenizer()			,					image_processor=self.get_image_processor()   )
        processor.save_pretrained(self.tmpdirname   )

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

        lowerCAmelCase__   :				Union[str, Any] 			=				CLIPProcessor.from_pretrained(
            self.tmpdirname			,					bos_token="(BOS)"			,					eos_token="(EOS)"			,					do_normalize=snake_case			,					padding_value=1.0   )

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

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				self.get_image_processor()
        lowerCAmelCase__   :				Union[str, Any] 			=				self.get_tokenizer()

        lowerCAmelCase__   :				Dict 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				self.prepare_image_inputs()

        lowerCAmelCase__   :				List[str] 			=				image_processor(snake_case			,					return_tensors="np"   )
        lowerCAmelCase__   :				Dict 			=				processor(images=snake_case			,					return_tensors="np"   )

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				self.get_image_processor()
        lowerCAmelCase__   :				Optional[Any] 			=				self.get_tokenizer()

        lowerCAmelCase__   :				Optional[int] 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )

        lowerCAmelCase__   :				Tuple 			=				"lower newer"

        lowerCAmelCase__   :				List[Any] 			=				processor(text=snake_case   )

        lowerCAmelCase__   :				Tuple 			=				tokenizer(snake_case   )

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				self.get_image_processor()
        lowerCAmelCase__   :				Dict 			=				self.get_tokenizer()

        lowerCAmelCase__   :				List[str] 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )

        lowerCAmelCase__   :				Dict 			=				"lower newer"
        lowerCAmelCase__   :				str 			=				self.prepare_image_inputs()

        lowerCAmelCase__   :				str 			=				processor(text=snake_case			,					images=snake_case   )

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

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				self.get_image_processor()
        lowerCAmelCase__   :				str 			=				self.get_tokenizer()

        lowerCAmelCase__   :				List[Any] 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )

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

        lowerCAmelCase__   :				List[str] 			=				processor.batch_decode(snake_case   )
        lowerCAmelCase__   :				Optional[int] 			=				tokenizer.batch_decode(snake_case   )

        self.assertListEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Dict 			=				self.get_image_processor()
        lowerCAmelCase__   :				str 			=				self.get_tokenizer()

        lowerCAmelCase__   :				Optional[Any] 			=				CLIPProcessor(tokenizer=snake_case			,					image_processor=snake_case   )

        lowerCAmelCase__   :				Any 			=				"lower newer"
        lowerCAmelCase__   :				Optional[Any] 			=				self.prepare_image_inputs()

        lowerCAmelCase__   :				Optional[int] 			=				processor(text=snake_case			,					images=snake_case   )

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









"""simple docstring"""

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_UpperCamelCase		     =    logging.get_logger(__name__)

_UpperCamelCase		     =    {
    """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}






class 			__a					(						__magic_name__       ,	__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      Optional[Any]    =						'focalnet'






       def __init__(   self			,					snake_case=224			,					snake_case=4			,					snake_case=3			,					snake_case=96			,					snake_case=False			,					snake_case=[192, 384, 768, 768]			,					snake_case=[2, 2, 6, 2]			,					snake_case=[2, 2, 2, 2]			,					snake_case=[3, 3, 3, 3]			,					snake_case="gelu"			,					snake_case=4.0			,					snake_case=0.0			,					snake_case=0.1			,					snake_case=False			,					snake_case=1e-4			,					snake_case=False			,					snake_case=False			,					snake_case=False			,					snake_case=0.02			,					snake_case=1e-5			,					snake_case=32			,					snake_case=None			,					snake_case=None			,					**snake_case			,					):





        """simple docstring"""

        super().__init__(**snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				image_size
        lowerCAmelCase__   :				Union[str, Any] 			=				patch_size
        lowerCAmelCase__   :				List[str] 			=				num_channels
        lowerCAmelCase__   :				List[str] 			=				embed_dim
        lowerCAmelCase__   :				List[Any] 			=				use_conv_embed
        lowerCAmelCase__   :				List[str] 			=				hidden_sizes
        lowerCAmelCase__   :				List[Any] 			=				depths
        lowerCAmelCase__   :				Union[str, Any] 			=				focal_levels
        lowerCAmelCase__   :				Union[str, Any] 			=				focal_windows
        lowerCAmelCase__   :				int 			=				hidden_act
        lowerCAmelCase__   :				List[Any] 			=				mlp_ratio
        lowerCAmelCase__   :				str 			=				hidden_dropout_prob
        lowerCAmelCase__   :				Union[str, Any] 			=				drop_path_rate
        lowerCAmelCase__   :				Tuple 			=				use_layerscale
        lowerCAmelCase__   :				Tuple 			=				layerscale_value
        lowerCAmelCase__   :				str 			=				use_post_layernorm
        lowerCAmelCase__   :				str 			=				use_post_layernorm_in_modulation
        lowerCAmelCase__   :				Union[str, Any] 			=				normalize_modulator
        lowerCAmelCase__   :				Optional[int] 			=				initializer_range
        lowerCAmelCase__   :				List[Any] 			=				layer_norm_eps
        lowerCAmelCase__   :				str 			=				encoder_stride
        lowerCAmelCase__   :				Union[str, Any] 			=				["stem"] + [F"""stage{idx}""" for idx in range(1			,					len(self.depths   ) + 1   )]
        lowerCAmelCase__			,						lowerCAmelCase__   :				Union[str, Any] 			=				get_aligned_output_features_output_indices(
            out_features=snake_case			,					out_indices=snake_case			,					stage_names=self.stage_names   )






