






from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
					from PIL import Image

					from ..image_utils import load_image

if is_torch_available():
					from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
					from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
					from ..tf_utils import stable_softmax

__snake_case      :      Optional[int]             =       logging.get_logger(__name__)


@add_end_docstrings(__lowercase)
class       __SCREAMING_SNAKE_CASE   (				__lowercase):






						def __init__(		self       ,  **_UpperCamelCase				):






												"""simple docstring"""
												super().__init__(**_UpperCamelCase				)

												requires_backends(self       ,  'vision'				)
												self.check_model_type(
												    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
												    if self.framework == 'tf'
												    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING				)






						def __call__(		self       ,  _UpperCamelCase       ,  **_UpperCamelCase				):






												"""simple docstring"""
												return super().__call__(_UpperCamelCase       ,  **_UpperCamelCase				)






						def  UpperCamelCase__ (		self       ,  **_UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  {}
												if "candidate_labels" in kwargs:
																		lowerCAmelCase__        =  kwargs['candidate_labels']
												if "hypothesis_template" in kwargs:
																		lowerCAmelCase__        =  kwargs['hypothesis_template']

												return preprocess_params, {}, {}






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase=None       ,  _UpperCamelCase="This is a photo of {}."				):






												"""simple docstring"""
												lowerCAmelCase__        =  load_image(_UpperCamelCase				)
												lowerCAmelCase__        =  self.image_processor(images=[image]       ,  return_tensors=self.framework				)
												lowerCAmelCase__        =  candidate_labels
												lowerCAmelCase__        =  [hypothesis_template.format(_UpperCamelCase				) for x in candidate_labels]
												lowerCAmelCase__        =  self.tokenizer(_UpperCamelCase       ,  return_tensors=self.framework       ,  padding=_UpperCamelCase				)
												lowerCAmelCase__        =  [text_inputs]
												return inputs






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  model_inputs.pop('candidate_labels'				)
												lowerCAmelCase__        =  model_inputs.pop('text_inputs'				)
												if isinstance(text_inputs[0]       ,  _UpperCamelCase				):
																		lowerCAmelCase__        =  text_inputs[0]
												else:
																		# Batching case.
																		lowerCAmelCase__        =  text_inputs[0][0]

												lowerCAmelCase__        =  self.model(**_UpperCamelCase       ,  **_UpperCamelCase				)

												lowerCAmelCase__        =  {
												    'candidate_labels': candidate_labels,
												    'logits': outputs.logits_per_image,
												}
												return model_outputs







						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  model_outputs.pop('candidate_labels'				)
												lowerCAmelCase__        =  model_outputs['logits'][0]
												if self.framework == "pt":
																		lowerCAmelCase__        =  logits.softmax(dim=-1				).squeeze(-1				)
																		lowerCAmelCase__        =  probs.tolist()
																		if not isinstance(_UpperCamelCase       ,  _UpperCamelCase				):
																								lowerCAmelCase__        =  [scores]
												elif self.framework == "tf":
																		lowerCAmelCase__        =  stable_softmax(_UpperCamelCase       ,  axis=-1				)
																		lowerCAmelCase__        =  probs.numpy().tolist()
												else:
																		raise ValueError(F"Unsupported framework: {self.framework}"				)

												lowerCAmelCase__        =  [
												    {'score': score, 'label': candidate_label}
												    for score, candidate_label in sorted(zip(_UpperCamelCase       ,  _UpperCamelCase				)       ,  key=lambda _UpperCamelCase				: -x[0]				)
												]
												return result













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






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






												"""simple docstring"""
												lowerCAmelCase__        =  parent
												lowerCAmelCase__        =  batch_size
												lowerCAmelCase__        =  image_size
												lowerCAmelCase__        =  num_channels
												lowerCAmelCase__        =  embeddings_size
												lowerCAmelCase__        =  hidden_sizes
												lowerCAmelCase__        =  depths
												lowerCAmelCase__        =  is_training
												lowerCAmelCase__        =  use_labels
												lowerCAmelCase__        =  hidden_act
												lowerCAmelCase__        =  num_labels
												lowerCAmelCase__        =  scope
												lowerCAmelCase__        =  len(_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

												lowerCAmelCase__        =  None
												if self.use_labels:
																		lowerCAmelCase__        =  ids_tensor([self.batch_size]       ,  self.num_labels				)

												lowerCAmelCase__        =  self.get_config()

												return config, pixel_values, labels






						def  UpperCamelCase__ (		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  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFResNetModel(config=_UpperCamelCase				)
												lowerCAmelCase__        =  model(_UpperCamelCase				)
												# 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  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.num_labels
												lowerCAmelCase__        =  TFResNetForImageClassification(_UpperCamelCase				)
												lowerCAmelCase__        =  model(_UpperCamelCase       ,  labels=_UpperCamelCase				)
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)				)







						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.prepare_config_and_inputs()
												lowerCAmelCase__  ,    lowerCAmelCase__  ,    lowerCAmelCase__        =  config_and_inputs
												lowerCAmelCase__        =  {'pixel_values': pixel_values}
												return config, inputs_dict




@require_tf
class       __SCREAMING_SNAKE_CASE   (				__lowercase						,   __lowercase						,   unittest.TestCase):
						_SCREAMING_SNAKE_CASE		:    Any						=   (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
						_SCREAMING_SNAKE_CASE		:    List[str]						=   (
						    {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

						_SCREAMING_SNAKE_CASE		:    Union[str, Any]						=   False
						_SCREAMING_SNAKE_CASE		:    int						=   False
						_SCREAMING_SNAKE_CASE		:    Optional[int]						=   False
						_SCREAMING_SNAKE_CASE		:    List[str]						=   False
						_SCREAMING_SNAKE_CASE		:    Optional[Any]						=   False






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFResNetModelTester(self				)
												lowerCAmelCase__        =  ConfigTester(self       ,  config_class=_UpperCamelCase       ,  has_text_modality=_UpperCamelCase				)






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






												"""simple docstring"""
												return






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






												"""simple docstring"""
												pass






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






												"""simple docstring"""
												pass






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__  ,    lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs_for_common()

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

																		lowerCAmelCase__        =  ['pixel_values']
																		self.assertListEqual(arg_names[:1]       ,  _UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												def check_hidden_states_output(_UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):
																		lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																		lowerCAmelCase__        =  model(**self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)				)

																		lowerCAmelCase__        =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																		lowerCAmelCase__        =  self.model_tester.num_stages
																		self.assertEqual(len(_UpperCamelCase				)       ,  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]       ,  )

												lowerCAmelCase__  ,    lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs_for_common()
												lowerCAmelCase__        =  ['basic', 'bottleneck']
												for model_class in self.all_model_classes:
																		for layer_type in layers_type:
																								lowerCAmelCase__        =  layer_type
																								lowerCAmelCase__        =  True
																								check_hidden_states_output(_UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				)

																								# check that output_hidden_states also work using config
																								del inputs_dict["output_hidden_states"]
																								lowerCAmelCase__        =  True

																								check_hidden_states_output(_UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase				)







						@slow
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowerCAmelCase__        =  TFResNetModel.from_pretrained(_UpperCamelCase				)
																		self.assertIsNotNone(_UpperCamelCase				)







def 		_UpperCamelCase				(      )					->				List[str]:

						"""simple docstring"""



						lowerCAmelCase__        =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image


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






						@cached_property
						def  UpperCamelCase__ (		self				):






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







						@slow
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

												lowerCAmelCase__        =  self.default_image_processor
												lowerCAmelCase__        =  prepare_img()
												lowerCAmelCase__        =  image_processor(images=_UpperCamelCase       ,  return_tensors='tf'				)

												# forward pass
												lowerCAmelCase__        =  model(**_UpperCamelCase				)

												# verify the logits
												lowerCAmelCase__        =  tf.TensorShape((1, 10_00)				)
												self.assertEqual(outputs.logits.shape       ,  _UpperCamelCase				)

												lowerCAmelCase__        =  tf.constant([-11.10_69, -9.78_77, -8.37_77]				)

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





