





"""simple docstring"""





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

      def __init__(     self  :Union[str, Any]		,				_lowerCamelCase  :Dict		,				_lowerCamelCase  :int=1_3		,				_lowerCamelCase  :Optional[int]=3_2		,				_lowerCamelCase  :List[Any]=3		,				_lowerCamelCase  :List[Any]=4		,				_lowerCamelCase  :List[Any]=[1_0, 2_0, 3_0, 4_0]		,				_lowerCamelCase  :Any=[2, 2, 3, 2]		,				_lowerCamelCase  :int=True		,				_lowerCamelCase  :List[Any]=True		,				_lowerCamelCase  :Any=3_7		,				_lowerCamelCase  :Optional[Any]="gelu"		,				_lowerCamelCase  :List[str]=1_0		,				_lowerCamelCase  :List[str]=0.0_2		,				_lowerCamelCase  :Any=["stage2", "stage3", "stage4"]		,				_lowerCamelCase  :str=[2, 3, 4]		,				_lowerCamelCase  :int=None		,				):
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			parent
       __SCREAMING_SNAKE_CASE					:     Optional[int]   				=			batch_size
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			image_size
       __SCREAMING_SNAKE_CASE					:     List[str]   				=			num_channels
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			num_stages
       __SCREAMING_SNAKE_CASE					:     Any   				=			hidden_sizes
       __SCREAMING_SNAKE_CASE					:     Dict   				=			depths
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			is_training
       __SCREAMING_SNAKE_CASE					:     Dict   				=			use_labels
       __SCREAMING_SNAKE_CASE					:     Any   				=			intermediate_size
       __SCREAMING_SNAKE_CASE					:     List[Any]   				=			hidden_act
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			num_labels
       __SCREAMING_SNAKE_CASE					:     Dict   				=			initializer_range
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			out_features
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			out_indices
       __SCREAMING_SNAKE_CASE					:     Optional[int]   				=			scope

      def 		SCREAMING_SNAKE_CASE_     (     self  :Optional[int]		):
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			None
       if self.use_labels:
        __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			ids_tensor([self.batch_size]		,				self.num_labels		)

       __SCREAMING_SNAKE_CASE					:     Tuple   				=			self.get_config()
       return config, pixel_values, labels

      def 		SCREAMING_SNAKE_CASE_     (     self  :int		):
       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=SCREAMING_SNAKE_CASE__		,				initializer_range=self.initializer_range		,				out_features=self.out_features		,				out_indices=self.out_indices		,				num_labels=self.num_labels		,				)

      def 		SCREAMING_SNAKE_CASE_     (     self  :Optional[Any]		,				_lowerCamelCase  :Optional[int]		,				_lowerCamelCase  :Optional[int]		,				_lowerCamelCase  :str		):
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			ConvNextModel(config=SCREAMING_SNAKE_CASE__		)
       model.to(SCREAMING_SNAKE_CASE__		)
       model.eval()
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			model(SCREAMING_SNAKE_CASE__		)
       # 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 // 3_2, self.image_size // 3_2)		,				)

      def 		SCREAMING_SNAKE_CASE_     (     self  :int		,				_lowerCamelCase  :Union[str, Any]		,				_lowerCamelCase  :Tuple		,				_lowerCamelCase  :Optional[int]		):
       __SCREAMING_SNAKE_CASE					:     List[Any]   				=			ConvNextForImageClassification(SCREAMING_SNAKE_CASE__		)
       model.to(SCREAMING_SNAKE_CASE__		)
       model.eval()
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			model(SCREAMING_SNAKE_CASE__		,				labels=SCREAMING_SNAKE_CASE__		)
       self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)		)

      def 		SCREAMING_SNAKE_CASE_     (     self  :int		,				_lowerCamelCase  :Dict		,				_lowerCamelCase  :Optional[Any]		,				_lowerCamelCase  :Union[str, Any]		):
       __SCREAMING_SNAKE_CASE					:     str   				=			ConvNextBackbone(config=SCREAMING_SNAKE_CASE__		)
       model.to(SCREAMING_SNAKE_CASE__		)
       model.eval()
       __SCREAMING_SNAKE_CASE					:     int   				=			model(SCREAMING_SNAKE_CASE__		)

       # 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
       __SCREAMING_SNAKE_CASE					:     List[Any]   				=			None
       __SCREAMING_SNAKE_CASE					:     str   				=			ConvNextBackbone(config=SCREAMING_SNAKE_CASE__		)
       model.to(SCREAMING_SNAKE_CASE__		)
       model.eval()
       __SCREAMING_SNAKE_CASE					:     List[str]   				=			model(SCREAMING_SNAKE_CASE__		)

       # 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 		SCREAMING_SNAKE_CASE_     (     self  :str		):
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			self.prepare_config_and_inputs()
       __SCREAMING_SNAKE_CASE				, __SCREAMING_SNAKE_CASE				, __SCREAMING_SNAKE_CASE					:     Any   				=			config_and_inputs
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			{'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_torch
class      snake_case						(  __UpperCAmelCase					,	__UpperCAmelCase					,	unittest.TestCase  ):
      lowerCamelCase__         =					(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      lowerCamelCase__         =					(
          {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      lowerCamelCase__         =					True
      lowerCamelCase__         =					False
      lowerCamelCase__         =					False
      lowerCamelCase__         =					False
      lowerCamelCase__         =					False

      def 		SCREAMING_SNAKE_CASE_     (     self  :Dict		):
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			ConvNextModelTester(self		)
       __SCREAMING_SNAKE_CASE					:     Optional[int]   				=			ConfigTester(self		,				config_class=SCREAMING_SNAKE_CASE__		,				has_text_modality=SCREAMING_SNAKE_CASE__		,				hidden_size=3_7		)

      def 		SCREAMING_SNAKE_CASE_     (     self  :Dict		):
       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 		SCREAMING_SNAKE_CASE_     (     self  :Optional[Any]		):
       return

      @unittest.skip(reason='''ConvNext does not use inputs_embeds'''		)
      def 		SCREAMING_SNAKE_CASE_     (     self  :Tuple		):
       pass

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

      @unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
      def 		SCREAMING_SNAKE_CASE_     (     self  :Any		):
       pass

      def 		SCREAMING_SNAKE_CASE_     (     self  :int		):
       __SCREAMING_SNAKE_CASE				, __SCREAMING_SNAKE_CASE					:     int   				=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __SCREAMING_SNAKE_CASE					:     List[Any]   				=			model_class(SCREAMING_SNAKE_CASE__		)
        __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			inspect.signature(model.forward		)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			[*signature.parameters.keys()]

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

      def 		SCREAMING_SNAKE_CASE_     (     self  :Tuple		):
       __SCREAMING_SNAKE_CASE					:     Any   				=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__		)

      def 		SCREAMING_SNAKE_CASE_     (     self  :Optional[int]		):
       __SCREAMING_SNAKE_CASE					:     List[str]   				=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE__		)

      def 		SCREAMING_SNAKE_CASE_     (     self  :str		):



       def check_hidden_states_output(_lowerCamelCase  :str		,				_lowerCamelCase  :Union[str, Any]		,				_lowerCamelCase  :Dict		):
        __SCREAMING_SNAKE_CASE					:     List[str]   				=			model_class(SCREAMING_SNAKE_CASE__		)
        model.to(SCREAMING_SNAKE_CASE__		)
        model.eval()

        with torch.no_grad():
         __SCREAMING_SNAKE_CASE					:     List[Any]   				=			model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__		,				SCREAMING_SNAKE_CASE__		)		)

        __SCREAMING_SNAKE_CASE					:     int   				=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			self.model_tester.num_stages
        self.assertEqual(len(SCREAMING_SNAKE_CASE__		)		,				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]		,				)

       __SCREAMING_SNAKE_CASE				, __SCREAMING_SNAKE_CASE					:     Any   				=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			True
        check_hidden_states_output(SCREAMING_SNAKE_CASE__		,				SCREAMING_SNAKE_CASE__		,				SCREAMING_SNAKE_CASE__		)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			True

        check_hidden_states_output(SCREAMING_SNAKE_CASE__		,				SCREAMING_SNAKE_CASE__		,				SCREAMING_SNAKE_CASE__		)

      def 		SCREAMING_SNAKE_CASE_     (     self  :List[Any]		):
       __SCREAMING_SNAKE_CASE					:     Tuple   				=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__		)



      @slow
      def 		SCREAMING_SNAKE_CASE_     (     self  :List[str]		):



       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			ConvNextModel.from_pretrained(SCREAMING_SNAKE_CASE__		)
        self.assertIsNotNone(SCREAMING_SNAKE_CASE__		)







def 						lowerCAmelCase_      (    ):

 '''simple docstring'''






 __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
 return image





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

      @cached_property
      def 		SCREAMING_SNAKE_CASE_     (     self  :List[Any]		):
       return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''		) if is_vision_available() else None



      @slow
      def 		SCREAMING_SNAKE_CASE_     (     self  :Union[str, Any]		):
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(SCREAMING_SNAKE_CASE__		)

       __SCREAMING_SNAKE_CASE					:     Any   				=			self.default_image_processor
       __SCREAMING_SNAKE_CASE					:     Any   				=			prepare_img()
       __SCREAMING_SNAKE_CASE					:     Union[str, Any]   				=			image_processor(images=SCREAMING_SNAKE_CASE__		,				return_tensors='''pt'''		).to(SCREAMING_SNAKE_CASE__		)

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

       # verify the logits
       __SCREAMING_SNAKE_CASE					:     str   				=			torch.Size((1, 1_0_0_0)		)
       self.assertEqual(outputs.logits.shape		,				SCREAMING_SNAKE_CASE__		)

       __SCREAMING_SNAKE_CASE					:     Dict   				=			torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]		).to(SCREAMING_SNAKE_CASE__		)

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







@require_torch
class      snake_case						(  unittest.TestCase					,	__UpperCAmelCase  ):
      lowerCamelCase__         =					(ConvNextBackbone,) if is_torch_available() else ()
      lowerCamelCase__         =					ConvNextConfig

      lowerCamelCase__         =					False

      def 		SCREAMING_SNAKE_CASE_     (     self  :Optional[Any]		):
       __SCREAMING_SNAKE_CASE					:     Optional[Any]   				=			ConvNextModelTester(self		)



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class       _lowerCAmelCase  (		__magic_name__							):

 """simple docstring"""
 SCREAMING_SNAKE_CASE_				:					Tuple       						="openai/whisper-base"
 SCREAMING_SNAKE_CASE_				:					List[str]       						=(
     "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the "
     "transcribed text."
 )
 SCREAMING_SNAKE_CASE_				:					int       						="transcriber"
 SCREAMING_SNAKE_CASE_				:					Tuple       						=WhisperProcessor
 SCREAMING_SNAKE_CASE_				:					List[Any]       						=WhisperForConditionalGeneration

 SCREAMING_SNAKE_CASE_				:					Union[str, Any]       						=["audio"]
 SCREAMING_SNAKE_CASE_				:					Any       						=["text"]

 def      __lowerCAmelCase  (						self			:			List[Any]					, SCREAMING_SNAKE_CASE__			:			List[Any]   ):






      """simple docstring"""



      return self.pre_processor(SCREAMING_SNAKE_CASE__					, return_tensors='pt'   ).input_features

 def      __lowerCAmelCase  (						self			:			Tuple					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]   ):






      """simple docstring"""



      return self.model.generate(inputs=SCREAMING_SNAKE_CASE__   )






 def      __lowerCAmelCase  (						self			:			List[str]					, SCREAMING_SNAKE_CASE__			:			List[str]   ):






      """simple docstring"""



      return self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE__					, skip_special_tokens=SCREAMING_SNAKE_CASE__   )[0]


