





import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
     import jax
     import jax.numpy as jnp

     from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor



class   _SCREAMING_SNAKE_CASE		(      unittest.TestCase       ):







 '''simple docstring'''

 def __init__(self							:  int			,					UpperCAmelCase_							:  Dict			,					UpperCAmelCase_							:  Tuple=3			,					UpperCAmelCase_							:  Dict=32			,					UpperCAmelCase_							:  Union[str, Any]=3			,					UpperCAmelCase_							:  Optional[Any]=10			,					UpperCAmelCase_							:  Optional[int]=[10, 20, 30, 40]			,					UpperCAmelCase_							:  Optional[Any]=[1, 1, 2, 1]			,					UpperCAmelCase_							:  int=True			,					UpperCAmelCase_							:  Optional[Any]=True			,					UpperCAmelCase_							:  Optional[int]="relu"			,					UpperCAmelCase_							:  Any=3			,					UpperCAmelCase_							:  Optional[Any]=None			,					)			->str:



   '''simple docstring'''



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

 def 				SCREAMING_SNAKE_CASE_   (self							:  Dict)			->Tuple:



   '''simple docstring'''



   lowerCamelCase__: Optional[Any]         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowerCamelCase__: Any         =self.get_config()

   return config, pixel_values

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->str:



   '''simple docstring'''



   return RegNetConfig(
       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 				SCREAMING_SNAKE_CASE_   (self							:  List[Any]			,					UpperCAmelCase_							:  str			,					UpperCAmelCase_							:  Dict)			->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__: List[Any]         =FlaxRegNetModel(config=UpperCAmelCase_)
   lowerCamelCase__: Dict         =model(UpperCAmelCase_)

   # Output shape (b, c, h, w)
   self.parent.assertEqual(
       result.last_hidden_state.shape			,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,					)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str]			,					UpperCAmelCase_							:  int			,					UpperCAmelCase_							:  Optional[int])			->Any:



   '''simple docstring'''



   lowerCamelCase__: str         =self.num_labels
   lowerCamelCase__: int         =FlaxRegNetForImageClassification(config=UpperCAmelCase_)
   lowerCamelCase__: Optional[Any]         =model(UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_labels))







 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->int:



   '''simple docstring'''



   lowerCamelCase__: Union[str, Any]         =self.prepare_config_and_inputs()
   lowerCamelCase__    ,   lowerCamelCase__: Union[str, Any]         =config_and_inputs
   lowerCamelCase__: Union[str, Any]         ={"pixel_values": pixel_values}
   return config, inputs_dict



@require_flax
class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ,				unittest.TestCase       ):







 '''simple docstring'''
 lowercase_						=     (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

 lowercase_						=     False
 lowercase_						=     False
 lowercase_						=     False

 def 				SCREAMING_SNAKE_CASE_   (self							:  Union[str, Any])			->None:



   '''simple docstring'''



   lowerCamelCase__: List[Any]         =FlaxRegNetModelTester(self)
   lowerCamelCase__: List[Any]         =ConfigTester(self			,					config_class=UpperCAmelCase_			,					has_text_modality=UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  int)			->int:



   '''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 				SCREAMING_SNAKE_CASE_   (self							:  Optional[int])			->int:



   '''simple docstring'''



   return

 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[int])			->Dict:



   '''simple docstring'''



   lowerCamelCase__: Tuple         =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->int:



   '''simple docstring'''



   lowerCamelCase__: Dict         =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)

 @unittest.skip(reason="RegNet does not use inputs_embeds")
 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[int])			->str:



   '''simple docstring'''



   pass

 @unittest.skip(reason="RegNet does not support input and output embeddings")
 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[Any])			->Dict:



   '''simple docstring'''



   pass

 def 				SCREAMING_SNAKE_CASE_   (self							:  Union[str, Any])			->List[str]:



   '''simple docstring'''



   lowerCamelCase__    ,   lowerCamelCase__: List[Any]         =self.model_tester.prepare_config_and_inputs_for_common()

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

     lowerCamelCase__: Tuple         =["pixel_values"]
     self.assertListEqual(arg_names[:1]			,					UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  int)			->Optional[int]:



   '''simple docstring'''



   def check_hidden_states_output(UpperCAmelCase_							:  List[Any]			,					UpperCAmelCase_							:  List[str]			,					UpperCAmelCase_							:  Any):
     lowerCamelCase__: Optional[int]         =model_class(UpperCAmelCase_)

     lowerCamelCase__: Optional[int]         =model(**self._prepare_for_class(UpperCAmelCase_			,					UpperCAmelCase_))

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

     lowerCamelCase__: Optional[int]         =self.model_tester.num_stages
     self.assertEqual(len(UpperCAmelCase_)			,					expected_num_stages + 1)

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

   for model_class in self.all_model_classes:
     lowerCamelCase__: List[str]         =True
     check_hidden_states_output(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     lowerCamelCase__: Any         =True

     check_hidden_states_output(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)







 def 				SCREAMING_SNAKE_CASE_   (self							:  Dict)			->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__    ,   lowerCamelCase__: Union[str, Any]         =self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     with self.subTest(model_class.__name__):
       lowerCamelCase__: int         =self._prepare_for_class(UpperCAmelCase_			,					UpperCAmelCase_)
       lowerCamelCase__: Dict         =model_class(UpperCAmelCase_)

       @jax.jit
       def model_jitted(UpperCAmelCase_							:  List[Any]			,					**UpperCAmelCase_							:  str):
         return model(pixel_values=UpperCAmelCase_			,					**UpperCAmelCase_)

       with self.subTest("JIT Enabled"):
         lowerCamelCase__: Optional[Any]         =model_jitted(**UpperCAmelCase_).to_tuple()

       with self.subTest("JIT Disabled"):
         with jax.disable_jit():
           lowerCamelCase__: Union[str, Any]         =model_jitted(**UpperCAmelCase_).to_tuple()

       self.assertEqual(len(UpperCAmelCase_)			,					len(UpperCAmelCase_))
       for jitted_output, output in zip(UpperCAmelCase_			,					UpperCAmelCase_):
         self.assertEqual(jitted_output.shape			,					output.shape)





def 	lowerCAmelCase_					(			)	->						Any:







  """simple docstring"""





  lowerCamelCase__: Any         =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
  return image






@require_flax
class   _SCREAMING_SNAKE_CASE		(      unittest.TestCase       ):







 '''simple docstring'''

 @cached_property
 def 				SCREAMING_SNAKE_CASE_   (self							:  List[Any])			->int:



   '''simple docstring'''



   return AutoImageProcessor.from_pretrained("facebook/regnet-y-040") if is_vision_available() else None







 @slow
 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[Any])			->List[str]:



   '''simple docstring'''



   lowerCamelCase__: Any         =FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040")

   lowerCamelCase__: Optional[int]         =self.default_image_processor
   lowerCamelCase__: Any         =prepare_img()
   lowerCamelCase__: Any         =image_processor(images=UpperCAmelCase_			,					return_tensors="np")

   lowerCamelCase__: Tuple         =model(**UpperCAmelCase_)

   # verify the logits
   lowerCamelCase__: List[Any]         =(1, 1_000)
   self.assertEqual(outputs.logits.shape			,					UpperCAmelCase_)

   lowerCamelCase__: str         =jnp.array([-0.4180, -1.5051, -3.4836])

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






'''simple docstring'''






# 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 typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
     from PIL import Image

class 				a__(   lowerCamelCase__      ):
    lowercase__					=       """Salesforce/blip-image-captioning-base"""
    lowercase__					=       (
        """This is a tool that generates a description of an image. It takes an input named `image` which should be the """
        """image to caption, and returns a text that contains the description in English."""
    )
    lowercase__					=       """image_captioner"""
    lowercase__					=       AutoModelForVisionaSeq

    lowercase__					=       ["""image"""]
    lowercase__					=       ["""text"""]







    def __init__( self					:    Tuple		,     *__snake_case					:    int		,     **__snake_case					:    List[Any]      ):
      requires_backends(self		,     ['vision']      )
      super().__init__(*__snake_case		,     **__snake_case      )







    def      lowercase_			( self					:    Optional[int]		,     __snake_case					:    "Image"      ):
      return self.pre_processor(images=__snake_case		,     return_tensors='pt'      )







    def      lowercase_			( self					:    Optional[Any]		,     __snake_case					:    str      ):
      return self.model.generate(**__snake_case      )







    def      lowercase_			( self					:    Optional[Any]		,     __snake_case					:    Tuple      ):
      return self.pre_processor.batch_decode(__snake_case		,     skip_special_tokens=__snake_case      )[0].strip()