


"""simple docstring"""



import inspect
import unittest

from transformers import MobileNetVaConfig
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_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 MobileNetVaForImageClassification, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor







class _lowerCAmelCase    (				snake_case_     ):







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

       '''simple docstring'''




       snake_case   :				Tuple				 =   self.config_class(**self.inputs_dict						)
       self.parent.assertTrue(hasattr(UpperCamelCase__						,     "tf_padding"						)						)
       self.parent.assertTrue(hasattr(UpperCamelCase__						,     "depth_multiplier"						)						)







class _lowerCAmelCase    :







   def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__=13						,     UpperCamelCase__=3						,     UpperCamelCase__=32						,     UpperCamelCase__=0.25						,     UpperCamelCase__=8						,     UpperCamelCase__=True						,     UpperCamelCase__=1024						,     UpperCamelCase__=32						,     UpperCamelCase__="relu6"						,     UpperCamelCase__=0.1						,     UpperCamelCase__=0.02						,     UpperCamelCase__=True						,     UpperCamelCase__=True						,     UpperCamelCase__=10						,     UpperCamelCase__=None						,     )     ->		List[Any]:

       '''simple docstring'''




       snake_case   :				int				 =   parent
       snake_case   :				int				 =   batch_size
       snake_case   :				List[Any]				 =   num_channels
       snake_case   :				Any				 =   image_size
       snake_case   :				str				 =   depth_multiplier
       snake_case   :				Dict				 =   min_depth
       snake_case   :				List[Any]				 =   tf_padding
       snake_case   :				Tuple				 =   int(last_hidden_size * depth_multiplier						)
       snake_case   :				Tuple				 =   output_stride
       snake_case   :				int				 =   hidden_act
       snake_case   :				int				 =   classifier_dropout_prob
       snake_case   :				Any				 =   use_labels
       snake_case   :				Union[str, Any]				 =   is_training
       snake_case   :				Dict				 =   num_labels
       snake_case   :				Dict				 =   initializer_range
       snake_case   :				Optional[Any]				 =   scope







   def 			lowerCamelCase		(     self						)     ->		List[Any]:

       '''simple docstring'''




       snake_case   :				Optional[int]				 =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       snake_case   :				str				 =   None
       snake_case   :				Dict				 =   None
       if self.use_labels:
           snake_case   :				Union[str, Any]				 =   ids_tensor([self.batch_size]						,     self.num_labels						)
           snake_case   :				Optional[Any]				 =   ids_tensor([self.batch_size, self.image_size, self.image_size]						,     self.num_labels						)

       snake_case   :				Optional[int]				 =   self.get_config()

       return config, pixel_values, labels, pixel_labels







   def 			lowerCamelCase		(     self						)     ->		List[Any]:

       '''simple docstring'''




       return MobileNetVaConfig(
           num_channels=self.num_channels						,     image_size=self.image_size						,     depth_multiplier=self.depth_multiplier						,     min_depth=self.min_depth						,     tf_padding=self.tf_padding						,     hidden_act=self.hidden_act						,     classifier_dropout_prob=self.classifier_dropout_prob						,     initializer_range=self.initializer_range						,     )







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Union[str, Any]:

       '''simple docstring'''




       snake_case   :				Union[str, Any]				 =   MobileNetVaModel(config=UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Tuple				 =   model(UpperCamelCase__						)
       self.parent.assertEqual(
           result.last_hidden_state.shape						,     (
               self.batch_size,
               self.last_hidden_size,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )						,     )







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Optional[int]:

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.num_labels
       snake_case   :				int				 =   MobileNetVaForImageClassification(UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Tuple				 =   model(UpperCamelCase__						,     labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)						)







   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




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







@require_torch
class _lowerCAmelCase    (				snake_case_   ,							snake_case_   ,							unittest.TestCase     ):
   __UpperCAmelCase			:	List[str]							  =  (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase			:	Tuple							  =  (
       {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase			:	Any							  =  False
   __UpperCAmelCase			:	int							  =  False
   __UpperCAmelCase			:	Optional[Any]							  =  False
   __UpperCAmelCase			:	str							  =  False







   def 			lowerCamelCase		(     self						)     ->		Optional[Any]:

       '''simple docstring'''




       snake_case   :				List[str]				 =   MobileNetVaModelTester(self						)
       snake_case   :				Union[str, Any]				 =   MobileNetVaConfigTester(self						,     config_class=UpperCamelCase__						,     has_text_modality=UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"						)
   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       pass







   @unittest.skip(reason="MobileNetV1 does not output attentions"						)
   def 			lowerCamelCase		(     self						)     ->		Dict:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       snake_case ,snake_case   :				str				 =   self.model_tester.prepare_config_and_inputs_for_common()

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

           snake_case   :				List[str]				 =   ["pixel_values"]
           self.assertListEqual(arg_names[:1]						,     UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       snake_case   :				Tuple				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       def check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						):
           snake_case   :				Union[str, Any]				 =   model_class(UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()

           with torch.no_grad():
               snake_case   :				Any				 =   model(**self._prepare_for_class(UpperCamelCase__						,     UpperCamelCase__						)						)

           snake_case   :				str				 =   outputs.hidden_states

           snake_case   :				List[str]				 =   26
           self.assertEqual(len(UpperCamelCase__						)						,     UpperCamelCase__						)

       snake_case ,snake_case   :				Dict				 =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case   :				Optional[int]				 =   True
           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)

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

           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)







   @slow
   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case   :				Union[str, Any]				 =   MobileNetVaModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)     ->						List[str]:


    """simple docstring"""





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







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







   @cached_property
   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       return (
           MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224"						) if is_vision_available() else None
       )







   @slow
   def 			lowerCamelCase		(     self						)     ->		Optional[int]:

       '''simple docstring'''




       snake_case   :				List[str]				 =   MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"						).to(UpperCamelCase__						)

       snake_case   :				List[Any]				 =   self.default_image_processor
       snake_case   :				Dict				 =   prepare_img()
       snake_case   :				Optional[int]				 =   image_processor(images=UpperCamelCase__						,     return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case   :				Any				 =   model(**UpperCamelCase__						)

       # verify the logits
       snake_case   :				List[Any]				 =   torch.Size((1, 1001)						)
       self.assertEqual(outputs.logits.shape						,     UpperCamelCase__						)

       snake_case   :				Any				 =   torch.tensor([-4.1739, -1.1233, 3.1205]						).to(UpperCamelCase__						)

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









"""simple docstring"""



from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import (
    BaseOutput,
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_onnx_available,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)







@dataclass
class _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	Union[List[PIL.Image.Image], np.ndarray]
   __UpperCAmelCase			:	Optional[List[bool]]


try:
  if not (is_transformers_available() and is_torch_available()):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
  from .pipeline_cycle_diffusion import CycleDiffusionPipeline
  from .pipeline_stable_diffusion import StableDiffusionPipeline
  from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline
  from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline
  from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
  from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy
  from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline
  from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline
  from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline
  from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline
  from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline
  from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline
  from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline
  from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
  from .pipeline_stable_unclip import StableUnCLIPPipeline
  from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline
  from .safety_checker import StableDiffusionSafetyChecker
  from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer

try:
  if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline
else:
  from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline


try:
  if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.26.0""")):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_torch_and_transformers_objects import (
      StableDiffusionDepthaImgPipeline,
      StableDiffusionDiffEditPipeline,
      StableDiffusionPixaPixZeroPipeline,
  )
else:
  from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline
  from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline
  from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline


try:
  if not (
      is_torch_available()
      and is_transformers_available()
      and is_k_diffusion_available()
      and is_k_diffusion_version(""">=""", """0.0.12""")
  ):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
  from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline

try:
  if not (is_transformers_available() and is_onnx_available()):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_onnx_objects import *  # noqa F403
else:
  from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline
  from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline
  from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline
  from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy
  from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline

if is_transformers_available() and is_flax_available():
  import flax







  @flax.struct.dataclass
  class _lowerCAmelCase    (				snake_case_     ):
     __UpperCAmelCase			:	np.ndarray
     __UpperCAmelCase			:	List[bool]



  from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState
  from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline
  from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline
  from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline
  from .safety_checker_flax import FlaxStableDiffusionSafetyChecker





