import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# 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 ...utils import CONFIG_NAME, 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,
)


lowerCamelCase						=		logging.get_logger(__name__)

lowerCamelCase						=		OrderedDict(
    [
        ('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''),
        ('''beit''', '''BeitFeatureExtractor'''),
        ('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''),
        ('''clap''', '''ClapFeatureExtractor'''),
        ('''clip''', '''CLIPFeatureExtractor'''),
        ('''clipseg''', '''ViTFeatureExtractor'''),
        ('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''),
        ('''convnext''', '''ConvNextFeatureExtractor'''),
        ('''cvt''', '''ConvNextFeatureExtractor'''),
        ('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''),
        ('''data2vec-vision''', '''BeitFeatureExtractor'''),
        ('''deformable_detr''', '''DeformableDetrFeatureExtractor'''),
        ('''deit''', '''DeiTFeatureExtractor'''),
        ('''detr''', '''DetrFeatureExtractor'''),
        ('''dinat''', '''ViTFeatureExtractor'''),
        ('''donut-swin''', '''DonutFeatureExtractor'''),
        ('''dpt''', '''DPTFeatureExtractor'''),
        ('''encodec''', '''EncodecFeatureExtractor'''),
        ('''flava''', '''FlavaFeatureExtractor'''),
        ('''glpn''', '''GLPNFeatureExtractor'''),
        ('''groupvit''', '''CLIPFeatureExtractor'''),
        ('''hubert''', '''Wav2Vec2FeatureExtractor'''),
        ('''imagegpt''', '''ImageGPTFeatureExtractor'''),
        ('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''),
        ('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''),
        ('''levit''', '''LevitFeatureExtractor'''),
        ('''maskformer''', '''MaskFormerFeatureExtractor'''),
        ('''mctct''', '''MCTCTFeatureExtractor'''),
        ('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''),
        ('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''),
        ('''mobilevit''', '''MobileViTFeatureExtractor'''),
        ('''nat''', '''ViTFeatureExtractor'''),
        ('''owlvit''', '''OwlViTFeatureExtractor'''),
        ('''perceiver''', '''PerceiverFeatureExtractor'''),
        ('''poolformer''', '''PoolFormerFeatureExtractor'''),
        ('''regnet''', '''ConvNextFeatureExtractor'''),
        ('''resnet''', '''ConvNextFeatureExtractor'''),
        ('''segformer''', '''SegformerFeatureExtractor'''),
        ('''sew''', '''Wav2Vec2FeatureExtractor'''),
        ('''sew-d''', '''Wav2Vec2FeatureExtractor'''),
        ('''speech_to_text''', '''Speech2TextFeatureExtractor'''),
        ('''speecht5''', '''SpeechT5FeatureExtractor'''),
        ('''swiftformer''', '''ViTFeatureExtractor'''),
        ('''swin''', '''ViTFeatureExtractor'''),
        ('''swinv2''', '''ViTFeatureExtractor'''),
        ('''table-transformer''', '''DetrFeatureExtractor'''),
        ('''timesformer''', '''VideoMAEFeatureExtractor'''),
        ('''tvlt''', '''TvltFeatureExtractor'''),
        ('''unispeech''', '''Wav2Vec2FeatureExtractor'''),
        ('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''),
        ('''van''', '''ConvNextFeatureExtractor'''),
        ('''videomae''', '''VideoMAEFeatureExtractor'''),
        ('''vilt''', '''ViltFeatureExtractor'''),
        ('''vit''', '''ViTFeatureExtractor'''),
        ('''vit_mae''', '''ViTFeatureExtractor'''),
        ('''vit_msn''', '''ViTFeatureExtractor'''),
        ('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''),
        ('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''),
        ('''wavlm''', '''Wav2Vec2FeatureExtractor'''),
        ('''whisper''', '''WhisperFeatureExtractor'''),
        ('''xclip''', '''CLIPFeatureExtractor'''),
        ('''yolos''', '''YolosFeatureExtractor'''),
    ]
)

lowerCamelCase						=		_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)






def 					lowerCamelCase_   (	_a	):




		"""simple docstring"""






		for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
				if class_name in extractors:
						lowerCAmelCase__       :      Dict   					= model_type_to_module_name(_a	)

						lowerCAmelCase__       :      Optional[int]   					= importlib.import_module(f'.{module_name}'     ,       '''transformers.models'''	)
						try:
								return getattr(_a     ,       _a	)
						except AttributeError:
								continue

		for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
				if getattr(_a     ,       '''__name__'''     ,       _a	) == class_name:
						return extractor

    # 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.
		lowerCAmelCase__       :      Dict   					= importlib.import_module('''transformers'''	)
		if hasattr(_a     ,       _a	):
				return getattr(_a     ,       _a	)

		return None






def 					lowerCamelCase_   (	_a     ,       _a = None     ,       _a = False     ,       _a = False     ,       _a = None     ,       _a = None     ,       _a = None     ,       _a = False     ,       **_a     ,       ):




		"""simple docstring"""






		lowerCAmelCase__       :      Any   					= get_file_from_repo(
		    _a     ,       _a     ,       cache_dir=_a     ,       force_download=_a     ,       resume_download=_a     ,       proxies=_a     ,       use_auth_token=_a     ,       revision=_a     ,       local_files_only=_a     ,       )
		if resolved_config_file is None:
				logger.info(
				    '''Could not locate the feature extractor configuration file, will try to use the model config instead.'''	)
				return {}

		with open(_a     ,       encoding='''utf-8'''	) as reader:
				return json.load(_a	)





class  _a							:




	def __init__( self						:		Union[str, Any]		)->	List[Any]:
			raise EnvironmentError(
			    '''AutoFeatureExtractor is designed to be instantiated '''
			    '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.'''		)




	@classmethod
	@replace_list_option_in_docstrings(_SCREAMING_SNAKE_CASE		)
	def 							UpperCAmelCase__( cls						:		Any		, _SCREAMING_SNAKE_CASE						:		Optional[int]		, **_SCREAMING_SNAKE_CASE						:		Any		)->	Optional[int]:
			lowerCAmelCase__       :      Optional[Any]   					= kwargs.pop('''config'''		, _SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      Dict   					= kwargs.pop('''trust_remote_code'''		, _SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      str   					= True

			lowerCAmelCase__       :      int   					= FeatureExtractionMixin.get_feature_extractor_dict(_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      List[str]   					= config_dict.get('''feature_extractor_type'''		, _SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      Optional[Any]   					= None
			if "AutoFeatureExtractor" in config_dict.get('''auto_map'''		, {}		):
					lowerCAmelCase__       :      List[Any]   					= config_dict['''auto_map''']['''AutoFeatureExtractor''']

			# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
			if feature_extractor_class is None and feature_extractor_auto_map is None:
					if not isinstance(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		):
							lowerCAmelCase__       :      List[str]   					= AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)
					# It could be in `config.feature_extractor_type``
					lowerCAmelCase__       :      Tuple   					= getattr(_SCREAMING_SNAKE_CASE		, '''feature_extractor_type'''		, _SCREAMING_SNAKE_CASE		)
					if hasattr(_SCREAMING_SNAKE_CASE		, '''auto_map'''		) and "AutoFeatureExtractor" in config.auto_map:
							lowerCAmelCase__       :      Any   					= config.auto_map['''AutoFeatureExtractor''']

			if feature_extractor_class is not None:
					lowerCAmelCase__       :      Optional[int]   					= feature_extractor_class_from_name(_SCREAMING_SNAKE_CASE		)

			lowerCAmelCase__       :      Dict   					= feature_extractor_auto_map is not None
			lowerCAmelCase__       :      Optional[int]   					= feature_extractor_class is not None or type(_SCREAMING_SNAKE_CASE		) in FEATURE_EXTRACTOR_MAPPING
			lowerCAmelCase__       :      Tuple   					= resolve_trust_remote_code(
			    _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		)

			if has_remote_code and trust_remote_code:
					lowerCAmelCase__       :      int   					= get_class_from_dynamic_module(
					    _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)
					lowerCAmelCase__       :      int   					= kwargs.pop('''code_revision'''		, _SCREAMING_SNAKE_CASE		)
					if os.path.isdir(_SCREAMING_SNAKE_CASE		):
							feature_extractor_class.register_for_auto_class()
					return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)
			elif feature_extractor_class is not None:
					return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)
			# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
			elif type(_SCREAMING_SNAKE_CASE		) in FEATURE_EXTRACTOR_MAPPING:
					lowerCAmelCase__       :      Dict   					= FEATURE_EXTRACTOR_MAPPING[type(_SCREAMING_SNAKE_CASE		)]
					return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE		)

			raise ValueError(
			    F'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a '
			    F'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following '
			    F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys()		)}'		)




	@staticmethod
	def 							UpperCAmelCase__( _SCREAMING_SNAKE_CASE						:		str		, _SCREAMING_SNAKE_CASE						:		Optional[Any]		)->	Optional[int]:
			FEATURE_EXTRACTOR_MAPPING.register(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		)








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowerCamelCase						=		False





class  _a							(    unittest.TestCase):
	pass





@nightly
@require_torch_gpu
class  _a							(    unittest.TestCase):




	def 							UpperCAmelCase__( self						:		int		)->	int:
			# clean up the VRAM after each test
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()




	def 							UpperCAmelCase__( self						:		Any		)->	Dict:
			lowerCAmelCase__       :      int   					= VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''		, torch_dtype=torch.floataa		)
			pipe.to(_SCREAMING_SNAKE_CASE		)
			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

			lowerCAmelCase__       :      List[str]   					= load_image(
			    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''		)

			lowerCAmelCase__       :      List[str]   					= torch.manual_seed(0		)
			lowerCAmelCase__       :      List[str]   					= pipe.dual_guided(
			    prompt='''first prompt'''		, image=_SCREAMING_SNAKE_CASE		, text_to_image_strength=0.75		, generator=_SCREAMING_SNAKE_CASE		, guidance_scale=7.5		, num_inference_steps=2		, output_type='''numpy'''		, ).images

			with tempfile.TemporaryDirectory() as tmpdirname:
					pipe.save_pretrained(_SCREAMING_SNAKE_CASE		)
					lowerCAmelCase__       :      List[Any]   					= VersatileDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE		, torch_dtype=torch.floataa		)
			pipe.to(_SCREAMING_SNAKE_CASE		)
			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

			lowerCAmelCase__       :      List[str]   					= generator.manual_seed(0		)
			lowerCAmelCase__       :      str   					= pipe.dual_guided(
			    prompt='''first prompt'''		, image=_SCREAMING_SNAKE_CASE		, text_to_image_strength=0.75		, generator=_SCREAMING_SNAKE_CASE		, guidance_scale=7.5		, num_inference_steps=2		, output_type='''numpy'''		, ).images

			assert np.abs(image - new_image		).sum() < 1E-5, "Models don't have the same forward pass"




	def 							UpperCAmelCase__( self						:		Tuple		)->	List[Any]:
			lowerCAmelCase__       :      Optional[int]   					= VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''		, torch_dtype=torch.floataa		)
			pipe.to(_SCREAMING_SNAKE_CASE		)
			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

			lowerCAmelCase__       :      int   					= '''cyberpunk 2077'''
			lowerCAmelCase__       :      List[str]   					= load_image(
			    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''		)
			lowerCAmelCase__       :      List[Any]   					= torch.manual_seed(0		)
			lowerCAmelCase__       :      Union[str, Any]   					= pipe.dual_guided(
			    prompt=_SCREAMING_SNAKE_CASE		, image=_SCREAMING_SNAKE_CASE		, text_to_image_strength=0.75		, generator=_SCREAMING_SNAKE_CASE		, guidance_scale=7.5		, num_inference_steps=50		, output_type='''numpy'''		, ).images

			lowerCAmelCase__       :      List[Any]   					= image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			lowerCAmelCase__       :      List[str]   					= np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001]		)

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

			lowerCAmelCase__       :      int   					= '''A painting of a squirrel eating a burger '''
			lowerCAmelCase__       :      Optional[Any]   					= torch.manual_seed(0		)
			lowerCAmelCase__       :      Union[str, Any]   					= pipe.text_to_image(
			    prompt=_SCREAMING_SNAKE_CASE		, generator=_SCREAMING_SNAKE_CASE		, guidance_scale=7.5		, num_inference_steps=50		, output_type='''numpy'''		).images

			lowerCAmelCase__       :      List[Any]   					= image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			lowerCAmelCase__       :      Optional[Any]   					= np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]		)

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

			lowerCAmelCase__       :      Optional[Any]   					= pipe.image_variation(_SCREAMING_SNAKE_CASE		, generator=_SCREAMING_SNAKE_CASE		, output_type='''numpy'''		).images

			lowerCAmelCase__       :      List[Any]   					= image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			lowerCAmelCase__       :      Any   					= np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456]		)

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




