
import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class __snake_case	(   unittest.TestCase  ):
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
    @property
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Union[str, Any] 			=   1
           lowercase							:  Dict 			=   3
           lowercase							:  Union[str, Any] 			=   (32, 32)

           lowercase							:  List[str] 			=   floats_tensor((batch_size, num_channels) + sizes	,rng=random.Random(0   )   ).to(snake_case   )
           return image
    @property
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           torch.manual_seed(0   )
           lowercase							:  Optional[Any] 			=   UNetaDConditionModel(
               block_out_channels=(32, 64)	,layers_per_block=2	,sample_size=32	,in_channels=4	,out_channels=4	,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")	,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")	,cross_attention_dim=32	,)
           return model
    @property
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           torch.manual_seed(0   )
           lowercase							:  int 			=   AutoencoderKL(
               block_out_channels=[32, 64]	,in_channels=3	,out_channels=3	,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]	,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]	,latent_channels=4	,)
           return model
    @property
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           torch.manual_seed(0   )
           lowercase							:  int 			=   CLIPTextConfig(
               bos_token_id=0	,eos_token_id=2	,hidden_size=32	,intermediate_size=37	,layer_norm_eps=1e-05	,num_attention_heads=4	,num_hidden_layers=5	,pad_token_id=1	,vocab_size=1000	,)
           return CLIPTextModel(snake_case   )
    @property
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           def extract(*snake_case	,**snake_case   ):

                  class __snake_case	:
                      def __init__(						self   ):



                             '''simple docstring'''







                             lowercase							:  Union[str, Any] 			=   torch.ones([0]   )
                      def    _SCREAMING_SNAKE_CASE (						self	,snake_case   ):



                             '''simple docstring'''







                             self.pixel_values.to(snake_case   )
                             return self






                  return Out()

           return extract
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Optional[Any] 			=   """cpu"""  # ensure determinism for the device-dependent torch.Generator
           lowercase							:  Union[str, Any] 			=   self.dummy_cond_unet
           lowercase							:  Dict 			=   DDIMScheduler(
               beta_start=0.00_085	,beta_end=0.012	,beta_schedule="""scaled_linear"""	,clip_sample=snake_case	,set_alpha_to_one=snake_case	,)

           lowercase							:  List[Any] 			=   self.dummy_vae
           lowercase							:  List[str] 			=   self.dummy_text_encoder
           lowercase							:  str 			=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

           # make sure here that pndm scheduler skips prk
           lowercase							:  str 			=   StableDiffusionPipeline(
               unet=snake_case	,scheduler=snake_case	,vae=snake_case	,text_encoder=snake_case	,tokenizer=snake_case	,safety_checker=snake_case	,feature_extractor=self.dummy_extractor	,)
           lowercase							:  List[Any] 			=   sd_pipe.to(snake_case   )
           sd_pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  List[str] 			=   """A painting of a squirrel eating a burger"""

           lowercase							:  List[Any] 			=   torch.Generator(device=snake_case   ).manual_seed(0   )
           lowercase							:  Dict 			=   sd_pipe([prompt]	,generator=snake_case	,guidance_scale=6.0	,num_inference_steps=2	,output_type="""np"""   )
           lowercase							:  Union[str, Any] 			=   output.images

           lowercase							:  Dict 			=   torch.Generator(device=snake_case   ).manual_seed(0   )
           lowercase							:  List[Any] 			=   sd_pipe(
               [prompt]	,generator=snake_case	,guidance_scale=6.0	,num_inference_steps=2	,output_type="""np"""	,return_dict=snake_case	,)[0]

           lowercase							:  Optional[int] 			=   image[0, -3:, -3:, -1]
           lowercase							:  str 			=   image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 64, 64, 3)
           lowercase							:  Tuple 			=   np.array([0.5_753, 0.6_114, 0.5_001, 0.5_034, 0.5_470, 0.4_729, 0.4_971, 0.4_867, 0.4_867]   )

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1e-2
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Tuple 			=   """cpu"""  # ensure determinism for the device-dependent torch.Generator
           lowercase							:  Optional[int] 			=   self.dummy_cond_unet
           lowercase							:  List[str] 			=   PNDMScheduler(skip_prk_steps=snake_case   )
           lowercase							:  str 			=   self.dummy_vae
           lowercase							:  List[Any] 			=   self.dummy_text_encoder
           lowercase							:  Tuple 			=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

           # make sure here that pndm scheduler skips prk
           lowercase							:  List[Any] 			=   StableDiffusionPipeline(
               unet=snake_case	,scheduler=snake_case	,vae=snake_case	,text_encoder=snake_case	,tokenizer=snake_case	,safety_checker=snake_case	,feature_extractor=self.dummy_extractor	,)
           lowercase							:  Union[str, Any] 			=   sd_pipe.to(snake_case   )
           sd_pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  Tuple 			=   """A painting of a squirrel eating a burger"""
           lowercase							:  List[Any] 			=   torch.Generator(device=snake_case   ).manual_seed(0   )
           lowercase							:  Optional[int] 			=   sd_pipe([prompt]	,generator=snake_case	,guidance_scale=6.0	,num_inference_steps=2	,output_type="""np"""   )

           lowercase							:  Dict 			=   output.images

           lowercase							:  int 			=   torch.Generator(device=snake_case   ).manual_seed(0   )
           lowercase							:  str 			=   sd_pipe(
               [prompt]	,generator=snake_case	,guidance_scale=6.0	,num_inference_steps=2	,output_type="""np"""	,return_dict=snake_case	,)[0]

           lowercase							:  Union[str, Any] 			=   image[0, -3:, -3:, -1]
           lowercase							:  Tuple 			=   image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 64, 64, 3)
           lowercase							:  List[Any] 			=   np.array([0.5_122, 0.5_712, 0.4_825, 0.5_053, 0.5_646, 0.4_769, 0.5_179, 0.4_894, 0.4_994]   )

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1e-2
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Any 			=   StableDiffusionPipeline.from_pretrained(
               """hf-internal-testing/tiny-stable-diffusion-lms-pipe"""	,safety_checker=snake_case   )
           assert isinstance(snake_case	,snake_case   )
           assert isinstance(pipe.scheduler	,snake_case   )
           assert pipe.safety_checker is None

           lowercase							:  int 			=   pipe("""example prompt"""	,num_inference_steps=2   ).images[0]
           assert image is not None

           # check that there's no error when saving a pipeline with one of the models being None
           with tempfile.TemporaryDirectory() as tmpdirname:
                  pipe.save_pretrained(snake_case   )
                  lowercase							:  Union[str, Any] 			=   StableDiffusionPipeline.from_pretrained(snake_case   )

           # sanity check that the pipeline still works
           assert pipe.safety_checker is None
           lowercase							:  List[str] 			=   pipe("""example prompt"""	,num_inference_steps=2   ).images[0]
           assert image is not None
    @unittest.skipIf(torch_device != """cuda"""	,"""This test requires a GPU"""   )
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  List[str] 			=   self.dummy_cond_unet
           lowercase							:  Optional[Any] 			=   PNDMScheduler(skip_prk_steps=snake_case   )
           lowercase							:  Dict 			=   self.dummy_vae
           lowercase							:  str 			=   self.dummy_text_encoder
           lowercase							:  Any 			=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

           # put models in fp16
           lowercase							:  List[str] 			=   unet.half()
           lowercase							:  Dict 			=   vae.half()
           lowercase							:  Optional[int] 			=   bert.half()

           # make sure here that pndm scheduler skips prk
           lowercase							:  Optional[int] 			=   StableDiffusionPipeline(
               unet=snake_case	,scheduler=snake_case	,vae=snake_case	,text_encoder=snake_case	,tokenizer=snake_case	,safety_checker=snake_case	,feature_extractor=self.dummy_extractor	,)
           lowercase							:  Tuple 			=   sd_pipe.to(snake_case   )
           sd_pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  Any 			=   """A painting of a squirrel eating a burger"""
           lowercase							:  Dict 			=   sd_pipe([prompt]	,num_inference_steps=2	,output_type="""np"""   ).images

           assert image.shape == (1, 64, 64, 3)






@nightly
@require_torch_gpu
class __snake_case	(   unittest.TestCase  ):
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  List[str] 			=   """cuda"""
           lowercase							:  str 			=   StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""   )
           lowercase							:  Optional[int] 			=   pipe.to(snake_case   )
           pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  List[Any] 			=   """a photo of a cat"""
           lowercase							:  Tuple 			=   {
               """editing_prompt""": ["""sunglasses"""],
               """reverse_editing_direction""": [False],
               """edit_warmup_steps""": 10,
               """edit_guidance_scale""": 6,
               """edit_threshold""": 0.95,
               """edit_momentum_scale""": 0.5,
               """edit_mom_beta""": 0.6,
           }

           lowercase							:  Optional[int] 			=   3
           lowercase							:  List[Any] 			=   7

           # no sega enabled
           lowercase							:  int 			=   torch.Generator(snake_case   )
           generator.manual_seed(snake_case   )
           lowercase							:  List[str] 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,)

           lowercase							:  Tuple 			=   output.images
           lowercase							:  Union[str, Any] 			=   image[0, -3:, -3:, -1]
           lowercase							:  Tuple 			=   [
               0.34_673_113,
               0.38_492_733,
               0.37_597_352,
               0.34_086_335,
               0.35_650_748,
               0.35_579_205,
               0.3_384_763,
               0.34_340_236,
               0.3_573_271,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

           # with sega enabled
           # generator = torch.manual_seed(seed)
           generator.manual_seed(snake_case   )
           lowercase							:  Optional[Any] 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,**snake_case	,)

           lowercase							:  List[str] 			=   output.images
           lowercase							:  List[Any] 			=   image[0, -3:, -3:, -1]
           lowercase							:  Tuple 			=   [
               0.41_887_826,
               0.37_728_766,
               0.30_138_272,
               0.41_416_335,
               0.41_664_985,
               0.36_283_392,
               0.36_191_246,
               0.43_364_465,
               0.43_001_732,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  List[str] 			=   """cuda"""
           lowercase							:  List[Any] 			=   StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""   )
           lowercase							:  Optional[Any] 			=   pipe.to(snake_case   )
           pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  List[str] 			=   """an image of a crowded boulevard, realistic, 4k"""
           lowercase							:  List[Any] 			=   {
               """editing_prompt""": """crowd, crowded, people""",
               """reverse_editing_direction""": True,
               """edit_warmup_steps""": 10,
               """edit_guidance_scale""": 8.3,
               """edit_threshold""": 0.9,
               """edit_momentum_scale""": 0.5,
               """edit_mom_beta""": 0.6,
           }

           lowercase							:  Optional[int] 			=   9
           lowercase							:  Dict 			=   7

           # no sega enabled
           lowercase							:  Optional[Any] 			=   torch.Generator(snake_case   )
           generator.manual_seed(snake_case   )
           lowercase							:  Any 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,)

           lowercase							:  Optional[int] 			=   output.images
           lowercase							:  Optional[Any] 			=   image[0, -3:, -3:, -1]
           lowercase							:  List[Any] 			=   [
               0.43_497_998,
               0.91_814_065,
               0.7_540_739,
               0.55_580_205,
               0.8_467_265,
               0.5_389_691,
               0.62_574_506,
               0.58_897_763,
               0.50_926_757,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

           # with sega enabled
           # generator = torch.manual_seed(seed)
           generator.manual_seed(snake_case   )
           lowercase							:  Optional[int] 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,**snake_case	,)

           lowercase							:  List[str] 			=   output.images
           lowercase							:  Dict 			=   image[0, -3:, -3:, -1]
           lowercase							:  Optional[Any] 			=   [
               0.3_089_719,
               0.30_500_144,
               0.29_016_042,
               0.30_630_964,
               0.325_687,
               0.29_419_225,
               0.2_908_091,
               0.28_723_598,
               0.27_696_294,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Any 			=   """cuda"""
           lowercase							:  int 			=   StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""   )
           lowercase							:  Dict 			=   pipe.to(snake_case   )
           pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  Any 			=   """a castle next to a river"""
           lowercase							:  Tuple 			=   {
               """editing_prompt""": ["""boat on a river, boat""", """monet, impression, sunrise"""],
               """reverse_editing_direction""": False,
               """edit_warmup_steps""": [15, 18],
               """edit_guidance_scale""": 6,
               """edit_threshold""": [0.9, 0.8],
               """edit_momentum_scale""": 0.5,
               """edit_mom_beta""": 0.6,
           }

           lowercase							:  Tuple 			=   48
           lowercase							:  List[Any] 			=   7

           # no sega enabled
           lowercase							:  Tuple 			=   torch.Generator(snake_case   )
           generator.manual_seed(snake_case   )
           lowercase							:  Union[str, Any] 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,)

           lowercase							:  str 			=   output.images
           lowercase							:  List[Any] 			=   image[0, -3:, -3:, -1]
           lowercase							:  Optional[Any] 			=   [
               0.75_163_555,
               0.76_037_145,
               0.61_785,
               0.9_189_673,
               0.8_627_701,
               0.85_189_694,
               0.8_512_813,
               0.87_012_076,
               0.8_312_857,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

           # with sega enabled
           # generator = torch.manual_seed(seed)
           generator.manual_seed(snake_case   )
           lowercase							:  Any 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,**snake_case	,)

           lowercase							:  Optional[int] 			=   output.images
           lowercase							:  str 			=   image[0, -3:, -3:, -1]
           lowercase							:  Union[str, Any] 			=   [
               0.73_553_365,
               0.7_537_271,
               0.74_341_905,
               0.66_480_356,
               0.6_472_925,
               0.63_039_416,
               0.64_812_905,
               0.6_749_717,
               0.6_517_102,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Any 			=   """cuda"""
           lowercase							:  Optional[int] 			=   StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""	,torch_dtype=torch.floataa   )
           lowercase							:  Optional[int] 			=   pipe.to(snake_case   )
           pipe.set_progress_bar_config(disable=snake_case   )

           lowercase							:  List[Any] 			=   """a photo of a cat"""
           lowercase							:  Optional[int] 			=   {
               """editing_prompt""": ["""sunglasses"""],
               """reverse_editing_direction""": [False],
               """edit_warmup_steps""": 10,
               """edit_guidance_scale""": 6,
               """edit_threshold""": 0.95,
               """edit_momentum_scale""": 0.5,
               """edit_mom_beta""": 0.6,
           }

           lowercase							:  List[Any] 			=   3
           lowercase							:  int 			=   7

           # no sega enabled
           lowercase							:  Any 			=   torch.Generator(snake_case   )
           generator.manual_seed(snake_case   )
           lowercase							:  Any 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,)

           lowercase							:  int 			=   output.images
           lowercase							:  Dict 			=   image[0, -3:, -3:, -1]
           lowercase							:  int 			=   [
               0.34_887_695,
               0.3_876_953,
               0.375,
               0.34_423_828,
               0.3_581_543,
               0.35_717_773,
               0.3_383_789,
               0.34_570_312,
               0.359_375,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

           # with sega enabled
           # generator = torch.manual_seed(seed)
           generator.manual_seed(snake_case   )
           lowercase							:  str 			=   pipe(
               [prompt]	,generator=snake_case	,guidance_scale=snake_case	,num_inference_steps=50	,output_type="""np"""	,width=512	,height=512	,**snake_case	,)

           lowercase							:  Tuple 			=   output.images
           lowercase							:  Dict 			=   image[0, -3:, -3:, -1]
           lowercase							:  Any 			=   [
               0.42_285_156,
               0.36_914_062,
               0.29_077_148,
               0.42_041_016,
               0.41_918_945,
               0.35_498_047,
               0.3_618_164,
               0.4_423_828,
               0.43_115_234,
           ]

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2


import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


lowercase						:      Tuple							=							logging.get_logger(__name__)

lowercase						:      Optional[int]							=							OrderedDict(
    [
        ("""align""", """AlignProcessor"""),
        ("""altclip""", """AltCLIPProcessor"""),
        ("""bark""", """BarkProcessor"""),
        ("""blip""", """BlipProcessor"""),
        ("""blip-2""", """Blip2Processor"""),
        ("""bridgetower""", """BridgeTowerProcessor"""),
        ("""chinese_clip""", """ChineseCLIPProcessor"""),
        ("""clap""", """ClapProcessor"""),
        ("""clip""", """CLIPProcessor"""),
        ("""clipseg""", """CLIPSegProcessor"""),
        ("""flava""", """FlavaProcessor"""),
        ("""git""", """GitProcessor"""),
        ("""groupvit""", """CLIPProcessor"""),
        ("""hubert""", """Wav2Vec2Processor"""),
        ("""instructblip""", """InstructBlipProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2Processor"""),
        ("""layoutlmv3""", """LayoutLMv3Processor"""),
        ("""markuplm""", """MarkupLMProcessor"""),
        ("""mctct""", """MCTCTProcessor"""),
        ("""mgp-str""", """MgpstrProcessor"""),
        ("""oneformer""", """OneFormerProcessor"""),
        ("""owlvit""", """OwlViTProcessor"""),
        ("""pix2struct""", """Pix2StructProcessor"""),
        ("""sam""", """SamProcessor"""),
        ("""sew""", """Wav2Vec2Processor"""),
        ("""sew-d""", """Wav2Vec2Processor"""),
        ("""speech_to_text""", """Speech2TextProcessor"""),
        ("""speech_to_text_2""", """Speech2Text2Processor"""),
        ("""speecht5""", """SpeechT5Processor"""),
        ("""trocr""", """TrOCRProcessor"""),
        ("""tvlt""", """TvltProcessor"""),
        ("""unispeech""", """Wav2Vec2Processor"""),
        ("""unispeech-sat""", """Wav2Vec2Processor"""),
        ("""vilt""", """ViltProcessor"""),
        ("""vision-text-dual-encoder""", """VisionTextDualEncoderProcessor"""),
        ("""wav2vec2""", """Wav2Vec2Processor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2Processor"""),
        ("""wavlm""", """Wav2Vec2Processor"""),
        ("""whisper""", """WhisperProcessor"""),
        ("""xclip""", """XCLIPProcessor"""),
    ]
)

lowercase						:      str							=							_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					List[Any]:
       for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
              if class_name in processors:
                     lowercase							:  Optional[int] 			=   model_type_to_module_name(SCREAMING_SNAKE_CASE__       )

                     lowercase							:  str 			=   importlib.import_module(f".{module_name}"      ,			"""transformers.models"""       )
                     try:
                            return getattr(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       )
                     except AttributeError:
                            continue

       for processor in PROCESSOR_MAPPING._extra_content.values():
              if getattr(SCREAMING_SNAKE_CASE__      ,			"""__name__"""      ,			SCREAMING_SNAKE_CASE__       ) == class_name:
                     return processor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
       lowercase							:  Dict 			=   importlib.import_module("""transformers"""       )
       if hasattr(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       ):
              return getattr(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       )

       return None




class __snake_case	:
    def __init__(						self   ):



           '''simple docstring'''







           raise EnvironmentError(
               """AutoProcessor is designed to be instantiated """
               """using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."""   )
    @classmethod
    @replace_list_option_in_docstrings(snake_case   )
    def    _SCREAMING_SNAKE_CASE (						cls	,snake_case	,**snake_case   ):



           '''simple docstring'''







           lowercase							:  Any 			=   kwargs.pop("""config"""	,snake_case   )
           lowercase							:  Optional[int] 			=   kwargs.pop("""trust_remote_code"""	,snake_case   )
           lowercase							:  Union[str, Any] 			=   True

           lowercase							:  Optional[Any] 			=   None
           lowercase							:  Optional[Any] 			=   None

           # First, let's see if we have a preprocessor config.
           # Filter the kwargs for `get_file_from_repo`.
           lowercase							:  str 			=   {
               key: kwargs[key] for key in inspect.signature(snake_case   ).parameters.keys() if key in kwargs
           }
           # Let's start by checking whether the processor class is saved in an image processor
           lowercase							:  Dict 			=   get_file_from_repo(
               snake_case	,snake_case	,**snake_case   )
           if preprocessor_config_file is not None:
                  lowercase			,    lowercase							:  Dict 			=   ImageProcessingMixin.get_image_processor_dict(snake_case	,**snake_case   )
                  lowercase							:  Dict 			=   config_dict.get("""processor_class"""	,snake_case   )
                  if "AutoProcessor" in config_dict.get("""auto_map"""	,{}   ):
                         lowercase							:  List[str] 			=   config_dict["""auto_map"""]["""AutoProcessor"""]

        # If not found, let's check whether the processor class is saved in a feature extractor config
           if preprocessor_config_file is not None and processor_class is None:
                  lowercase			,    lowercase							:  Dict 			=   FeatureExtractionMixin.get_feature_extractor_dict(snake_case	,**snake_case   )
                  lowercase							:  Dict 			=   config_dict.get("""processor_class"""	,snake_case   )
                  if "AutoProcessor" in config_dict.get("""auto_map"""	,{}   ):
                         lowercase							:  Any 			=   config_dict["""auto_map"""]["""AutoProcessor"""]

           if processor_class is None:
                  # Next, let's check whether the processor class is saved in a tokenizer
                  lowercase							:  Any 			=   get_file_from_repo(
                      snake_case	,snake_case	,**snake_case   )
                  if tokenizer_config_file is not None:
                         with open(snake_case	,encoding="""utf-8"""   ) as reader:
                                lowercase							:  Optional[int] 			=   json.load(snake_case   )

                         lowercase							:  Union[str, Any] 			=   config_dict.get("""processor_class"""	,snake_case   )
                         if "AutoProcessor" in config_dict.get("""auto_map"""	,{}   ):
                                lowercase							:  Optional[Any] 			=   config_dict["""auto_map"""]["""AutoProcessor"""]

           if processor_class is None:
                  # Otherwise, load config, if it can be loaded.
                  if not isinstance(snake_case	,snake_case   ):
                         lowercase							:  Union[str, Any] 			=   AutoConfig.from_pretrained(
                             snake_case	,trust_remote_code=snake_case	,**snake_case   )

                  # And check if the config contains the processor class.
                  lowercase							:  str 			=   getattr(snake_case	,"""processor_class"""	,snake_case   )
                  if hasattr(snake_case	,"""auto_map"""   ) and "AutoProcessor" in config.auto_map:
                         lowercase							:  Tuple 			=   config.auto_map["""AutoProcessor"""]

           if processor_class is not None:
                  lowercase							:  List[str] 			=   processor_class_from_name(snake_case   )

           lowercase							:  str 			=   processor_auto_map is not None
           lowercase							:  str 			=   processor_class is not None or type(snake_case   ) in PROCESSOR_MAPPING
           lowercase							:  List[Any] 			=   resolve_trust_remote_code(
               snake_case	,snake_case	,snake_case	,snake_case   )

           if has_remote_code and trust_remote_code:
                  lowercase							:  Dict 			=   get_class_from_dynamic_module(
                      snake_case	,snake_case	,**snake_case   )
                  lowercase							:  str 			=   kwargs.pop("""code_revision"""	,snake_case   )
                  if os.path.isdir(snake_case   ):
                         processor_class.register_for_auto_class()
                  return processor_class.from_pretrained(
                      snake_case	,trust_remote_code=snake_case	,**snake_case   )
           elif processor_class is not None:
                  return processor_class.from_pretrained(
                      snake_case	,trust_remote_code=snake_case	,**snake_case   )
           # Last try: we use the PROCESSOR_MAPPING.
           elif type(snake_case   ) in PROCESSOR_MAPPING:
                  return PROCESSOR_MAPPING[type(snake_case   )].from_pretrained(snake_case	,**snake_case   )

           # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
           # tokenizer.
           try:
                  return AutoTokenizer.from_pretrained(
                      snake_case	,trust_remote_code=snake_case	,**snake_case   )
           except Exception:
                  try:
                         return AutoImageProcessor.from_pretrained(
                             snake_case	,trust_remote_code=snake_case	,**snake_case   )
                  except Exception:
                         pass

                  try:
                         return AutoFeatureExtractor.from_pretrained(
                             snake_case	,trust_remote_code=snake_case	,**snake_case   )
                  except Exception:
                         pass

           raise ValueError(
               f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
               """tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains"""
               """the files of at least one of those processing classes."""   )
    @staticmethod
    def    _SCREAMING_SNAKE_CASE (						snake_case	,snake_case   ):



           '''simple docstring'''







           PROCESSOR_MAPPING.register(snake_case	,snake_case   )
