


'''simple docstring'''
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase=3      ,      __lowercase=32      ,      __lowercase=3      ,      __lowercase=10      ,      __lowercase=[10, 20, 30, 40]      ,      __lowercase=[1, 1, 2, 1]      ,      __lowercase=True      ,      __lowercase=True      ,      __lowercase="relu"      ,      __lowercase=3      ,      __lowercase=None      ,      ):

  """simple docstring"""







  __A  :		Dict       =			parent
  __A  :		Tuple       =			batch_size
  __A  :		List[Any]       =			image_size
  __A  :		Optional[Any]       =			num_channels
  __A  :		int       =			embeddings_size
  __A  :		str       =			hidden_sizes
  __A  :		List[str]       =			depths
  __A  :		List[str]       =			is_training
  __A  :		Optional[int]       =			use_labels
  __A  :		int       =			hidden_act
  __A  :		Union[str, Any]       =			num_labels
  __A  :		List[Any]       =			scope
  __A  :		Union[str, Any]       =			len(lowerCAmelCase__						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		List[str]       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

  __A  :		Dict       =			self.get_config()

  return config, pixel_values, labels


 def  snake_case__   (      self						):

  """simple docstring"""







  return ResNetConfig(
      num_channels=self.num_channels      ,      embeddings_size=self.embeddings_size      ,      hidden_sizes=self.hidden_sizes      ,      depths=self.depths      ,      hidden_act=self.hidden_act      ,      num_labels=self.num_labels      ,      image_size=self.image_size      ,      )


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		List[str]       =			TFResNetModel(config=lowerCAmelCase__						)
  __A  :		List[Any]       =			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  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		int       =			self.num_labels
  __A  :		List[Any]       =			TFResNetForImageClassification(lowerCAmelCase__						)
  __A  :		List[str]       =			model(lowerCAmelCase__      ,      labels=lowerCAmelCase__						)
  self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.num_labels)						)







 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			self.prepare_config_and_inputs()
  __A     ,__A     ,__A  :		List[str]       =			config_and_inputs
  __A  :		str       =			{'pixel_values': pixel_values}
  return config, inputs_dict


@require_tf
class 						_lowerCamelCase					(    _snake_case    ,		_snake_case    ,		unittest.TestCase				):




 '''simple docstring'''
 __lowercase				:		Optional[int]    							=      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 __lowercase				:		Tuple    							=      (
     {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 __lowercase				:		List[Any]    							=      False
 __lowercase				:		List[Any]    							=      False
 __lowercase				:		Tuple    							=      False
 __lowercase				:		Any    							=      False
 __lowercase				:		List[Any]    							=      False


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			TFResNetModelTester(self						)
  __A  :		int       =			ConfigTester(self      ,      config_class=lowerCAmelCase__      ,      has_text_modality=lowerCAmelCase__						)


 def  snake_case__   (      self						):

  """simple docstring"""







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

  """simple docstring"""







  return


 @unittest.skip(reason='ResNet does not use inputs_embeds'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 @unittest.skip(reason='ResNet does not support input and output embeddings'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 def  snake_case__   (      self						):

  """simple docstring"""







  __A     ,__A  :		Optional[int]       =			self.model_tester.prepare_config_and_inputs_for_common()

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

   __A  :		Union[str, Any]       =			['pixel_values']
   self.assertListEqual(arg_names[:1]      ,      lowerCAmelCase__						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Tuple       =			self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*lowerCAmelCase__						)


 def  snake_case__   (      self						):

  """simple docstring"""







  def check_hidden_states_output(__lowercase      ,      __lowercase      ,      __lowercase						):
   __A  :		Union[str, Any]       =			model_class(lowerCAmelCase__						)
   __A  :		Dict       =			model(**self._prepare_for_class(lowerCAmelCase__      ,      lowerCAmelCase__						)						)

   __A  :		Dict       =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

   __A  :		Optional[Any]       =			self.model_tester.num_stages
   self.assertEqual(len(lowerCAmelCase__						)      ,      expected_num_stages + 1						)

   # ResNet'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[int]       =			self.model_tester.prepare_config_and_inputs_for_common()
  __A  :		Dict       =			['basic', 'bottleneck']
  for model_class in self.all_model_classes:
   for layer_type in layers_type:
    __A  :		List[str]       =			layer_type
    __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  :		List[str]       =			True

    check_hidden_states_output(lowerCAmelCase__      ,      lowerCAmelCase__      ,      lowerCAmelCase__						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		str       =			self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__						)







 @slow
 def  snake_case__   (      self						):

  """simple docstring"""







  for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   __A  :		Tuple       =			TFResNetModel.from_pretrained(lowerCAmelCase__						)
   self.assertIsNotNone(lowerCAmelCase__						)


def 			_lowercase       (				):
 __A  :		Tuple       =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
 return image


@require_tf
@require_vision
class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 @cached_property
 def  snake_case__   (      self						):

  """simple docstring"""







  return (
      AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
      if is_vision_available()
      else None
  )







 @slow
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[Any]       =			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

  __A  :		str       =			self.default_image_processor
  __A  :		str       =			prepare_img()
  __A  :		Any       =			image_processor(images=lowerCAmelCase__      ,      return_tensors='tf'						)

  # forward pass
  __A  :		Tuple       =			model(**lowerCAmelCase__						)

  # verify the logits
  __A  :		List[str]       =			tf.TensorShape((1, 1_000)						)
  self.assertEqual(outputs.logits.shape      ,      lowerCAmelCase__						)

  __A  :		int       =			tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]						)

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










'''simple docstring'''
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
 from PIL import Image

 from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast

@require_vision
class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			tempfile.mkdtemp()

  __A  :		List[Any]       =			BlipImageProcessor()
  __A  :		List[str]       =			BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel'						)

  __A  :		Union[str, Any]       =			BlipProcessor(__lowercase      ,      __lowercase						)

  processor.save_pretrained(self.tmpdirname						)


 def  snake_case__   (      self      ,      **__lowercase						):

  """simple docstring"""







  return AutoProcessor.from_pretrained(self.tmpdirname      ,      **__lowercase						).tokenizer


 def  snake_case__   (      self      ,      **__lowercase						):

  """simple docstring"""







  return AutoProcessor.from_pretrained(self.tmpdirname      ,      **__lowercase						).image_processor


 def  snake_case__   (      self						):

  """simple docstring"""







  shutil.rmtree(self.tmpdirname						)


 def  snake_case__   (      self						):

  """simple docstring"""







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

  __A  :		Union[str, Any]       =			[Image.fromarray(np.moveaxis(__lowercase      ,      0      ,      -1						)						) for x in image_inputs]

  return image_inputs


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			BlipProcessor(tokenizer=self.get_tokenizer()      ,      image_processor=self.get_image_processor()						)
  processor.save_pretrained(self.tmpdirname						)

  __A  :		Optional[int]       =			self.get_tokenizer(bos_token='(BOS)'      ,      eos_token='(EOS)'						)
  __A  :		Optional[Any]       =			self.get_image_processor(do_normalize=__lowercase      ,      padding_value=1.0						)

  __A  :		List[str]       =			BlipProcessor.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  snake_case__   (      self						):

  """simple docstring"""







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

  __A  :		Dict       =			BlipProcessor(tokenizer=__lowercase      ,      image_processor=__lowercase						)

  __A  :		Dict       =			self.prepare_image_inputs()

  __A  :		str       =			image_processor(__lowercase      ,      return_tensors='np'						)
  __A  :		List[Any]       =			processor(images=__lowercase      ,      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						):

  """simple docstring"""







  __A  :		int       =			self.get_image_processor()
  __A  :		List[str]       =			self.get_tokenizer()

  __A  :		str       =			BlipProcessor(tokenizer=__lowercase      ,      image_processor=__lowercase						)

  __A  :		List[Any]       =			'lower newer'

  __A  :		Any       =			processor(text=__lowercase						)

  __A  :		int       =			tokenizer(__lowercase      ,      return_token_type_ids=__lowercase						)

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


 def  snake_case__   (      self						):

  """simple docstring"""







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

  __A  :		Any       =			BlipProcessor(tokenizer=__lowercase      ,      image_processor=__lowercase						)

  __A  :		List[Any]       =			'lower newer'
  __A  :		List[str]       =			self.prepare_image_inputs()

  __A  :		Optional[Any]       =			processor(text=__lowercase      ,      images=__lowercase						)

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

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


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			self.get_image_processor()
  __A  :		Optional[int]       =			self.get_tokenizer()

  __A  :		List[str]       =			BlipProcessor(tokenizer=__lowercase      ,      image_processor=__lowercase						)

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

  __A  :		Tuple       =			processor.batch_decode(__lowercase						)
  __A  :		Tuple       =			tokenizer.batch_decode(__lowercase						)

  self.assertListEqual(__lowercase      ,      __lowercase						)







 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			self.get_image_processor()
  __A  :		Any       =			self.get_tokenizer()

  __A  :		Any       =			BlipProcessor(tokenizer=__lowercase      ,      image_processor=__lowercase						)

  __A  :		Optional[int]       =			'lower newer'
  __A  :		List[str]       =			self.prepare_image_inputs()

  __A  :		int       =			processor(text=__lowercase      ,      images=__lowercase						)

  # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
  self.assertListEqual(list(inputs.keys()						)      ,      ['pixel_values', 'input_ids', 'attention_mask']						)






