

import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()







class        a__       (   snake_case__	,			snake_case__	,			snake_case__	,			unittest.TestCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Union[str, Any]			       =StableDiffusionControlNetImgaImgPipeline
  UpperCAmelCase__      : List[Any]			       =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
  UpperCAmelCase__      : Any			       =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  UpperCAmelCase__      : str			       =IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"""control_image"""}       )
  UpperCAmelCase__      : Dict			       =IMAGE_TO_IMAGE_IMAGE_PARAMS


  def  _lowercase      (			self    : int		)					->Optional[int]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   UNetaDConditionModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				sample_size=3_2				,				in_channels=4				,				out_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,				cross_attention_dim=3_2				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Dict       =   ControlNetModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				in_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				cross_attention_dim=3_2				,				conditioning_embedding_out_channels=(1_6, 3_2)				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   DDIMScheduler(
            beta_start=0.0_00_85				,				beta_end=0.0_12				,				beta_schedule="""scaled_linear"""				,				clip_sample=lowercase_				,				set_alpha_to_one=lowercase_				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      List[str]       =   AutoencoderKL(
            block_out_channels=[3_2, 6_4]				,				in_channels=3				,				out_channels=3				,				down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,				up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,				latent_channels=4				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      str       =   CLIPTextConfig(
            bos_token_id=0				,				eos_token_id=2				,				hidden_size=3_2				,				intermediate_size=3_7				,				layer_norm_eps=1e-05				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_0_0_0				,				)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   CLIPTextModel(lowercase_		)
        SCREAMING_SNAKE_CASE :      str       =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

        SCREAMING_SNAKE_CASE :      Optional[int]       =   {
            "unet": unet,
            "controlnet": controlnet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "safety_checker": None,
            "feature_extractor": None,
        }
        return components


  def  _lowercase      (			self    : Union[str, Any]				,				UpperCAmelCase__    : Optional[Any]				,				UpperCAmelCase__    : Tuple=0		)					->str:
        """simple docstring"""







        if str(lowercase_		).startswith("""mps"""		):
              SCREAMING_SNAKE_CASE :      Dict       =   torch.manual_seed(lowercase_		)
        else:
              SCREAMING_SNAKE_CASE :      List[str]       =   torch.Generator(device=lowercase_		).manual_seed(lowercase_		)

        SCREAMING_SNAKE_CASE :      Dict       =   2
        SCREAMING_SNAKE_CASE :      str       =   randn_tensor(
            (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)				,				generator=lowercase_				,				device=torch.device(lowercase_		)				,				)
        SCREAMING_SNAKE_CASE :      int       =   floats_tensor(control_image.shape				,				rng=random.Random(lowercase_		)		).to(lowercase_		)
        SCREAMING_SNAKE_CASE :      int       =   image.cpu().permute(0				,				2				,				3				,				1		)[0]
        SCREAMING_SNAKE_CASE :      Dict       =   Image.fromarray(np.uinta(lowercase_		)		).convert("""RGB"""		).resize((6_4, 6_4)		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 6.0,
            "output_type": "numpy",
            "image": image,
            "control_image": control_image,
        }

        return inputs


  def  _lowercase      (			self    : List[Any]		)					->int:
        """simple docstring"""







        return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3		)


  @unittest.skipIf(
      torch_device != """cuda""" or not is_xformers_available()				,				reason="""XFormers attention is only available with CUDA and `xformers` installed"""				,				)
  def  _lowercase      (			self    : int		)					->List[Any]:
        """simple docstring"""







        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3		)




  def  _lowercase      (			self    : Union[str, Any]		)					->List[str]:
        """simple docstring"""







        self._test_inference_batch_single_identical(expected_max_diff=2e-3		)







class        a__       (   snake_case__	,			snake_case__	,			unittest.TestCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Union[str, Any]			       =StableDiffusionControlNetImgaImgPipeline
  UpperCAmelCase__      : List[str]			       =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
  UpperCAmelCase__      : Tuple			       =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  UpperCAmelCase__      : int			       =frozenset([]       )  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess


  def  _lowercase      (			self    : List[str]		)					->List[str]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   UNetaDConditionModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				sample_size=3_2				,				in_channels=4				,				out_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,				cross_attention_dim=3_2				,				)
        torch.manual_seed(0		)

        def init_weights(UpperCAmelCase__    : Dict		):
              if isinstance(lowercase_				,				torch.nn.Convad		):
                    torch.nn.init.normal(m.weight		)
                    m.bias.data.fill_(1.0		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   ControlNetModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				in_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				cross_attention_dim=3_2				,				conditioning_embedding_out_channels=(1_6, 3_2)				,				)
        controlneta.controlnet_down_blocks.apply(lowercase_		)

        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   ControlNetModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				in_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				cross_attention_dim=3_2				,				conditioning_embedding_out_channels=(1_6, 3_2)				,				)
        controlneta.controlnet_down_blocks.apply(lowercase_		)

        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   DDIMScheduler(
            beta_start=0.0_00_85				,				beta_end=0.0_12				,				beta_schedule="""scaled_linear"""				,				clip_sample=lowercase_				,				set_alpha_to_one=lowercase_				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      int       =   AutoencoderKL(
            block_out_channels=[3_2, 6_4]				,				in_channels=3				,				out_channels=3				,				down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,				up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,				latent_channels=4				,				)
        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Any       =   CLIPTextConfig(
            bos_token_id=0				,				eos_token_id=2				,				hidden_size=3_2				,				intermediate_size=3_7				,				layer_norm_eps=1e-05				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_0_0_0				,				)
        SCREAMING_SNAKE_CASE :      Any       =   CLIPTextModel(lowercase_		)
        SCREAMING_SNAKE_CASE :      Tuple       =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   MultiControlNetModel([controlneta, controlneta]		)

        SCREAMING_SNAKE_CASE :      int       =   {
            "unet": unet,
            "controlnet": controlnet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "safety_checker": None,
            "feature_extractor": None,
        }
        return components


  def  _lowercase      (			self    : int				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : int=0		)					->List[str]:
        """simple docstring"""







        if str(lowercase_		).startswith("""mps"""		):
              SCREAMING_SNAKE_CASE :      Optional[int]       =   torch.manual_seed(lowercase_		)
        else:
              SCREAMING_SNAKE_CASE :      Tuple       =   torch.Generator(device=lowercase_		).manual_seed(lowercase_		)

        SCREAMING_SNAKE_CASE :      List[Any]       =   2

        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   [
            randn_tensor(
                (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)				,				generator=lowercase_				,				device=torch.device(lowercase_		)				,				),
            randn_tensor(
                (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)				,				generator=lowercase_				,				device=torch.device(lowercase_		)				,				),
        ]

        SCREAMING_SNAKE_CASE :      Tuple       =   floats_tensor(control_image[0].shape				,				rng=random.Random(lowercase_		)		).to(lowercase_		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   image.cpu().permute(0				,				2				,				3				,				1		)[0]
        SCREAMING_SNAKE_CASE :      List[Any]       =   Image.fromarray(np.uinta(lowercase_		)		).convert("""RGB"""		).resize((6_4, 6_4)		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 6.0,
            "output_type": "numpy",
            "image": image,
            "control_image": control_image,
        }

        return inputs


  def  _lowercase      (			self    : List[Any]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   self.get_dummy_components()
        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.pipeline_class(**lowercase_		)
        pipe.to(lowercase_		)

        SCREAMING_SNAKE_CASE :      Tuple       =   10.0
        SCREAMING_SNAKE_CASE :      List[Any]       =   4

        SCREAMING_SNAKE_CASE :      str       =   self.get_dummy_inputs(lowercase_		)
        SCREAMING_SNAKE_CASE :      Any       =   steps
        SCREAMING_SNAKE_CASE :      Tuple       =   scale
        SCREAMING_SNAKE_CASE :      Dict       =   pipe(**lowercase_		)[0]

        SCREAMING_SNAKE_CASE :      int       =   self.get_dummy_inputs(lowercase_		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   steps
        SCREAMING_SNAKE_CASE :      Tuple       =   scale
        SCREAMING_SNAKE_CASE :      Optional[int]       =   pipe(**lowercase_				,				control_guidance_start=0.1				,				control_guidance_end=0.2		)[0]

        SCREAMING_SNAKE_CASE :      int       =   self.get_dummy_inputs(lowercase_		)
        SCREAMING_SNAKE_CASE :      str       =   steps
        SCREAMING_SNAKE_CASE :      Dict       =   scale
        SCREAMING_SNAKE_CASE :      int       =   pipe(**lowercase_				,				control_guidance_start=[0.1, 0.3]				,				control_guidance_end=[0.2, 0.7]		)[0]

        SCREAMING_SNAKE_CASE :      List[str]       =   self.get_dummy_inputs(lowercase_		)
        SCREAMING_SNAKE_CASE :      Tuple       =   steps
        SCREAMING_SNAKE_CASE :      int       =   scale
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   pipe(**lowercase_				,				control_guidance_start=0.4				,				control_guidance_end=[0.5, 0.8]		)[0]

        # make sure that all outputs are different
        assert np.sum(np.abs(output_a - output_a		)		) > 1e-3
        assert np.sum(np.abs(output_a - output_a		)		) > 1e-3
        assert np.sum(np.abs(output_a - output_a		)		) > 1e-3


  def  _lowercase      (			self    : List[Any]		)					->Dict:
        """simple docstring"""







        return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3		)


  @unittest.skipIf(
      torch_device != """cuda""" or not is_xformers_available()				,				reason="""XFormers attention is only available with CUDA and `xformers` installed"""				,				)
  def  _lowercase      (			self    : List[str]		)					->int:
        """simple docstring"""







        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3		)


  def  _lowercase      (			self    : Union[str, Any]		)					->Optional[Any]:
        """simple docstring"""







        self._test_inference_batch_single_identical(expected_max_diff=2e-3		)




  def  _lowercase      (			self    : int		)					->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.get_dummy_components()
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.pipeline_class(**lowercase_		)
        pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)
        with tempfile.TemporaryDirectory() as tmpdir:
              try:
                    # save_pretrained is not implemented for Multi-ControlNet
                    pipe.save_pretrained(lowercase_		)
              except NotImplementedError:
                    pass







@slow
@require_torch_gpu
class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : List[Any]		)					->Dict:
        """simple docstring"""







        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()




  def  _lowercase      (			self    : Optional[Any]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny"""		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   StableDiffusionControlNetImgaImgPipeline.from_pretrained(
            """runwayml/stable-diffusion-v1-5"""				,				safety_checker=lowercase_				,				controlnet=lowercase_		)
        pipe.enable_model_cpu_offload()
        pipe.set_progress_bar_config(disable=lowercase_		)

        SCREAMING_SNAKE_CASE :      str       =   torch.Generator(device="""cpu"""		).manual_seed(0		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   "evil space-punk bird"
        SCREAMING_SNAKE_CASE :      Dict       =   load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"""		).resize((5_1_2, 5_1_2)		)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   load_image(
            """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png"""		).resize((5_1_2, 5_1_2)		)

        SCREAMING_SNAKE_CASE :      List[str]       =   pipe(
            lowercase_				,				lowercase_				,				control_image=lowercase_				,				generator=lowercase_				,				output_type="""np"""				,				num_inference_steps=5_0				,				strength=0.6				,				)

        SCREAMING_SNAKE_CASE :      str       =   output.images[0]

        assert image.shape == (5_1_2, 5_1_2, 3)

        SCREAMING_SNAKE_CASE :      List[str]       =   load_numpy(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy"""		)

        assert np.abs(expected_image - image		).max() < 9e-2







import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / """utils"""))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCAmelCase__ :     int				    =    get_tests_dir("""fixtures""")







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Dict		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   mock.Mock()
        SCREAMING_SNAKE_CASE :      Optional[int]       =   5_0_0
        SCREAMING_SNAKE_CASE :      List[str]       =   {}
        SCREAMING_SNAKE_CASE :      List[Any]       =   HTTPError
        SCREAMING_SNAKE_CASE :      int       =   {}

        # Download this model to make sure it's in the cache.
        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
        # Under the mock environment we get a 500 error when trying to reach the model.
        with mock.patch("""requests.Session.request"""				,				return_value=UpperCAmelCase__		) as mock_head:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
              # This check we did call the fake head request
              mock_head.assert_called()




  def  _lowercase      (			self    : Optional[Any]		)					->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   WavaVecaFeatureExtractor.from_pretrained(
            """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"""		)







@is_staging_test
class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   TOKEN
        HfFolder.save_token(UpperCAmelCase__		)


  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Optional[int]:
        """simple docstring"""







        try:
              delete_repo(token=cls._token				,				repo_id="""test-feature-extractor"""		)
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token				,				repo_id="""valid_org/test-feature-extractor-org"""		)
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token				,				repo_id="""test-dynamic-feature-extractor"""		)
        except HTTPError:
              pass


  def  _lowercase      (			self    : int		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Any       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

        # Reset repo
        delete_repo(token=self._token				,				repo_id="""test-feature-extractor"""		)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  UpperCAmelCase__				,				repo_id="""test-feature-extractor"""				,				push_to_hub=UpperCAmelCase__				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)


  def  _lowercase      (			self    : List[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""valid_org/test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

        # Reset repo
        delete_repo(token=self._token				,				repo_id="""valid_org/test-feature-extractor"""		)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  UpperCAmelCase__				,				repo_id="""valid_org/test-feature-extractor-org"""				,				push_to_hub=UpperCAmelCase__				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)




  def  _lowercase      (			self    : Optional[Any]		)					->Optional[int]:
        """simple docstring"""







        CustomFeatureExtractor.register_for_auto_class()
        SCREAMING_SNAKE_CASE :      Any       =   CustomFeatureExtractor.from_pretrained(UpperCAmelCase__		)

        feature_extractor.push_to_hub("""test-dynamic-feature-extractor"""				,				use_auth_token=self._token		)

        # This has added the proper auto_map field to the config
        self.assertDictEqual(
            feature_extractor.auto_map				,				{"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""}				,				)

        SCREAMING_SNAKE_CASE :      Any       =   AutoFeatureExtractor.from_pretrained(
            f"{USER}/test-dynamic-feature-extractor"				,				trust_remote_code=UpperCAmelCase__		)
        # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
        self.assertEqual(new_feature_extractor.__class__.__name__				,				"""CustomFeatureExtractor"""		)




