
import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
							import torch

							from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin







class 				lowercase		:




							def __init__(				self   ,A__   ,A__=None   ,A__=None   ,A__=None   ,A__="resnet50"   ,A__=3   ,A__=3_2   ,A__=3   ,A__=True   ,A__=True   ,):
												lowercase							=						parent
												lowercase							=						out_indices if out_indices is not None else [4]
												lowercase							=						stage_names
												lowercase							=						out_features
												lowercase							=						backbone
												lowercase							=						batch_size
												lowercase							=						image_size
												lowercase							=						num_channels
												lowercase							=						use_pretrained_backbone
												lowercase							=						is_training




							def  A__      (				self):
												lowercase							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
												lowercase							=						self.get_config()

												return config, pixel_values




							def  A__      (				self):
												return TimmBackboneConfig(
												    image_size=self.image_size   ,num_channels=self.num_channels   ,out_features=self.out_features   ,out_indices=self.out_indices   ,stage_names=self.stage_names   ,use_pretrained_backbone=self.use_pretrained_backbone   ,backbone=self.backbone   ,)




							def  A__      (				self   ,A__   ,A__):
												lowercase							=						TimmBackbone(config=A__)
												model.to(A__)
												model.eval()
												with torch.no_grad():
																	lowercase							=						model(A__)
												self.parent.assertEqual(
												    result.feature_map[-1].shape   ,(self.batch_size, model.channels[-1], 1_4, 1_4)   ,)





							def  A__      (				self):
												lowercase							=						self.prepare_config_and_inputs()
												lowercase	,						lowercase							=						config_and_inputs
												lowercase							=						{'''pixel_values''': pixel_values}
												return config, inputs_dict







@require_torch
@require_timm
class 				lowercase		(					SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  unittest.TestCase		):
							lowercase_       :       Union[str, Any]       					=(TimmBackbone,) if is_torch_available() else ()
							lowercase_       :       Optional[int]       					={'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
							lowercase_       :       str       					=False
							lowercase_       :       Dict       					=False
							lowercase_       :       str       					=False
							lowercase_       :       Union[str, Any]       					=False




							def  A__      (				self):
												lowercase							=						TimmBackboneModelTester(self)
												lowercase							=						ConfigTester(self   ,config_class=A__   ,has_text_modality=A__)




							def  A__      (				self):
												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):
												lowercase							=						'''resnet18'''
												lowercase							=						'''microsoft/resnet-18'''

												lowercase							=						AutoBackbone.from_pretrained(A__   ,use_timm_backbone=A__)
												lowercase							=						AutoBackbone.from_pretrained(A__)

												self.assertEqual(len(timm_model.out_features)   ,len(transformers_model.out_features))
												self.assertEqual(len(timm_model.stage_names)   ,len(transformers_model.stage_names))
												self.assertEqual(timm_model.channels   ,transformers_model.channels)
												# Out indices are set to the last layer by default. For timm models, we don't know
												# the number of layers in advance, so we set it to (-1,), whereas for transformers
												# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
												self.assertEqual(timm_model.out_indices   ,(-1,))
												self.assertEqual(transformers_model.out_indices   ,[len(timm_model.stage_names) - 1])

												lowercase							=						AutoBackbone.from_pretrained(A__   ,use_timm_backbone=A__   ,out_indices=[1, 2, 3])
												lowercase							=						AutoBackbone.from_pretrained(A__   ,out_indices=[1, 2, 3])

												self.assertEqual(timm_model.out_indices   ,transformers_model.out_indices)
												self.assertEqual(len(timm_model.out_features)   ,len(transformers_model.out_features))
												self.assertEqual(timm_model.channels   ,transformers_model.channels)




							@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone initialization is managed on the timm side''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
							def  A__      (				self):
												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t support output_attentions.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Safetensors is not supported by timm.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
							def  A__      (				self):
												pass




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase							=						['''pixel_values''']
																	self.assertListEqual(arg_names[:1]   ,A__)




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
												lowercase							=						True
												lowercase							=						self.has_attentions

												# no need to test all models as different heads yield the same functionality
												lowercase							=						self.all_model_classes[0]
												lowercase							=						model_class(A__)
												model.to(A__)

												lowercase							=						self._prepare_for_class(A__   ,A__)
												lowercase							=						model(**A__)
												lowercase							=						outputs[0][-1]

												# Encoder-/Decoder-only models
												lowercase							=						outputs.hidden_states[0]
												hidden_states.retain_grad()

												if self.has_attentions:
																	lowercase							=						outputs.attentions[0]
																	attentions.retain_grad()

												output.flatten()[0].backward(retain_graph=A__)

												self.assertIsNotNone(hidden_states.grad)

												if self.has_attentions:
																	self.assertIsNotNone(attentions.grad)





							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)

																	self.assertEqual(len(result.feature_maps)   ,len(config.out_indices))
																	self.assertEqual(len(model.channels)   ,len(config.out_indices))

																	# Check output of last stage is taken if out_features=None, out_indices=None
																	lowercase							=						copy.deepcopy(A__)
																	lowercase							=						None
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)

																	self.assertEqual(len(result.feature_maps)   ,1)
																	self.assertEqual(len(model.channels)   ,1)

																	# Check backbone can be initialized with fresh weights
																	lowercase							=						copy.deepcopy(A__)
																	lowercase							=						False
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)











'''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    UpperCAmelCase	(       unittest.TestCase				):
 def      UpperCAmelCase_							(				self      :Optional[Any]							)->							Tuple:
     A__				=			tempfile.mkdtemp()

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

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

     A__				=			{
         "do_resize": True,
         "size": 20,
         "do_center_crop": True,
         "crop_size": 18,
         "do_normalize": True,
         "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
         "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
     }
     A__				=			os.path.join(self.tmpdirname						,       lowercase_							)
     with open(self.image_processor_file						,       "w"						,       encoding="utf-8"							) as fp:
         json.dump(lowercase_						,       lowercase_							)
 def      UpperCAmelCase_							(				self      :Any						,       **lowercase_      :Union[str, Any]							)->							Tuple:
     return CLIPTokenizer.from_pretrained(self.tmpdirname						,       **lowercase_							)
 def      UpperCAmelCase_							(				self      :Any						,       **lowercase_      :Tuple							)->							Dict:
     return CLIPTokenizerFast.from_pretrained(self.tmpdirname						,       **lowercase_							)
 def      UpperCAmelCase_							(				self      :Dict						,       **lowercase_      :Union[str, Any]							)->							Any:
     return CLIPImageProcessor.from_pretrained(self.tmpdirname						,       **lowercase_							)
 def      UpperCAmelCase_							(				self      :List[str]							)->							int:
     shutil.rmtree(self.tmpdirname							)
 def      UpperCAmelCase_							(				self      :Optional[int]							)->							Optional[int]:
     A__				=			[np.random.randint(2_55						,       size=(3, 30, 4_00)						,       dtype=np.uinta							)]

     A__				=			[Image.fromarray(np.moveaxis(lowercase_						,       0						,       -1							)							) for x in image_inputs]

     return image_inputs
 def      UpperCAmelCase_							(				self      :int							)->							List[Any]:
     A__				=			self.get_tokenizer()
     A__				=			self.get_rust_tokenizer()
     A__				=			self.get_image_processor()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)
     processor_slow.save_pretrained(self.tmpdirname							)
     A__				=			CLIPProcessor.from_pretrained(self.tmpdirname						,       use_fast=lowercase_							)

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)
     processor_fast.save_pretrained(self.tmpdirname							)
     A__				=			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						,       lowercase_							)
     self.assertIsInstance(processor_fast.tokenizer						,       lowercase_							)

     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						,       lowercase_							)
     self.assertIsInstance(processor_fast.image_processor						,       lowercase_							)
 def      UpperCAmelCase_							(				self      :Optional[Any]							)->							Optional[int]:
     A__				=			CLIPProcessor(tokenizer=self.get_tokenizer()						,       image_processor=self.get_image_processor()							)
     processor.save_pretrained(self.tmpdirname							)

     A__				=			self.get_tokenizer(bos_token="(BOS)"						,       eos_token="(EOS)"							)
     A__				=			self.get_image_processor(do_normalize=lowercase_						,       padding_value=1.0							)

     A__				=			CLIPProcessor.from_pretrained(
         self.tmpdirname						,       bos_token="(BOS)"						,       eos_token="(EOS)"						,       do_normalize=lowercase_						,       padding_value=1.0							)

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

     self.assertEqual(processor.image_processor.to_json_string()						,       image_processor_add_kwargs.to_json_string()							)
     self.assertIsInstance(processor.image_processor						,       lowercase_							)
 def      UpperCAmelCase_							(				self      :List[Any]							)->							Tuple:
     A__				=			self.get_image_processor()
     A__				=			self.get_tokenizer()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)

     A__				=			self.prepare_image_inputs()

     A__				=			image_processor(lowercase_						,       return_tensors="np"							)
     A__				=			processor(images=lowercase_						,       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      UpperCAmelCase_							(				self      :Optional[int]							)->							Dict:
     A__				=			self.get_image_processor()
     A__				=			self.get_tokenizer()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)

     A__				=			"lower newer"

     A__				=			processor(text=lowercase_							)

     A__				=			tokenizer(lowercase_							)

     for key in encoded_tok.keys():
         self.assertListEqual(encoded_tok[key]						,       encoded_processor[key]							)
 def      UpperCAmelCase_							(				self      :str							)->							Any:
     A__				=			self.get_image_processor()
     A__				=			self.get_tokenizer()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)

     A__				=			"lower newer"
     A__				=			self.prepare_image_inputs()

     A__				=			processor(text=lowercase_						,       images=lowercase_							)

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

     # test if it raises when no input is passed
     with pytest.raises(lowercase_							):
         processor()
 def      UpperCAmelCase_							(				self      :Tuple							)->							Tuple:
     A__				=			self.get_image_processor()
     A__				=			self.get_tokenizer()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)

     A__				=			[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

     A__				=			processor.batch_decode(lowercase_							)
     A__				=			tokenizer.batch_decode(lowercase_							)

     self.assertListEqual(lowercase_						,       lowercase_							)



 def      UpperCAmelCase_							(				self      :List[Any]							)->							Dict:
     A__				=			self.get_image_processor()
     A__				=			self.get_tokenizer()

     A__				=			CLIPProcessor(tokenizer=lowercase_						,       image_processor=lowercase_							)

     A__				=			"lower newer"
     A__				=			self.prepare_image_inputs()

     A__				=			processor(text=lowercase_						,       images=lowercase_							)

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



