






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,
)


SCREAMING_SNAKE_CASE						:						List[str]					   =       logging.get_logger(__name__)

SCREAMING_SNAKE_CASE						:						Optional[Any]					   =       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'''),
    ]
)

SCREAMING_SNAKE_CASE						:						List[str]					   =       _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)



def  __lowerCamelCase					(					lowerCAmelCase__				):
				for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
								if class_name in extractors:
												A__							 =       model_type_to_module_name(lowerCAmelCase__				)

												A__							 =       importlib.import_module(f'''.{module_name}'''       ,'transformers.models'				)
												try:
																return getattr(lowerCAmelCase__       ,lowerCAmelCase__				)
												except AttributeError:
																continue

				for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
								if getattr(lowerCAmelCase__       ,'__name__'       ,lowerCAmelCase__				) == 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.
				A__							 =       importlib.import_module('transformers'				)
				if hasattr(lowerCAmelCase__       ,lowerCAmelCase__				):
								return getattr(lowerCAmelCase__       ,lowerCAmelCase__				)

				return None



def  __lowerCamelCase					(					lowerCAmelCase__       ,lowerCAmelCase__ = None       ,lowerCAmelCase__ = False       ,lowerCAmelCase__ = False       ,lowerCAmelCase__ = None       ,lowerCAmelCase__ = None       ,lowerCAmelCase__ = None       ,lowerCAmelCase__ = False       ,**lowerCAmelCase__       ,):
				A__							 =       get_file_from_repo(
				    lowerCAmelCase__       ,lowerCAmelCase__       ,cache_dir=lowerCAmelCase__       ,force_download=lowerCAmelCase__       ,resume_download=lowerCAmelCase__       ,proxies=lowerCAmelCase__       ,use_auth_token=lowerCAmelCase__       ,revision=lowerCAmelCase__       ,local_files_only=lowerCAmelCase__       ,)
				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(lowerCAmelCase__       ,encoding='utf-8'				) as reader:
								return json.load(lowerCAmelCase__				)







class       snake_case_       :



	"""simple docstring"""

	def __init__(      self						):


					"""simple docstring"""

					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(__a						)
	def       _UpperCAmelCase						(      cls  ,					__a  ,					**__a						):


					"""simple docstring"""

					A__							 =       kwargs.pop('config'  ,					__a						)
					A__							 =       kwargs.pop('trust_remote_code'  ,					__a						)
					A__							 =       True

					A__ ,			A__							 =       FeatureExtractionMixin.get_feature_extractor_dict(__a  ,					**__a						)
					A__							 =       config_dict.get('feature_extractor_type'  ,					__a						)
					A__							 =       None
					if "AutoFeatureExtractor" in config_dict.get('auto_map'  ,					{}						):
									A__							 =       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(__a  ,					__a						):
													A__							 =       AutoConfig.from_pretrained(__a  ,					**__a						)
									# It could be in `config.feature_extractor_type``
									A__							 =       getattr(__a  ,					'feature_extractor_type'  ,					__a						)
									if hasattr(__a  ,					'auto_map'						) and "AutoFeatureExtractor" in config.auto_map:
													A__							 =       config.auto_map['AutoFeatureExtractor']

					if feature_extractor_class is not None:
									A__							 =       feature_extractor_class_from_name(__a						)

					A__							 =       feature_extractor_auto_map is not None
					A__							 =       feature_extractor_class is not None or type(__a						) in FEATURE_EXTRACTOR_MAPPING
					A__							 =       resolve_trust_remote_code(
					    __a  ,					__a  ,					__a  ,					__a						)

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

					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						(      __a  ,					__a						):


					"""simple docstring"""

					FEATURE_EXTRACTOR_MAPPING.register(__a  ,					__a						)










"""simple docstring"""






# Copyright 2021 The HuggingFace 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 pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


SCREAMING_SNAKE_CASE						:						Dict					   =       '''Create a default config file for Accelerate with only a few flags set.'''



def  __lowerCamelCase					(					lowerCAmelCase__="no"       ,lowerCAmelCase__ = default_json_config_file       ,lowerCAmelCase__ = False				):
				A__							 =       Path(lowerCAmelCase__				)
				path.parent.mkdir(parents=lowerCAmelCase__       ,exist_ok=lowerCAmelCase__				)
				if path.exists():
								print(
								    f'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''				)
								return False
				A__							 =       mixed_precision.lower()
				if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
								raise ValueError(
								    f'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''				)
				A__							 =       {
				    'compute_environment': 'LOCAL_MACHINE',
				    'mixed_precision': mixed_precision,
				}
				if torch.cuda.is_available():
								A__							 =       torch.cuda.device_count()
								A__							 =       num_gpus
								A__							 =       False
								if num_gpus > 1:
												A__							 =       'MULTI_GPU'
								else:
												A__							 =       'NO'
				elif is_xpu_available() and use_xpu:
								A__							 =       torch.xpu.device_count()
								A__							 =       num_xpus
								A__							 =       False
								if num_xpus > 1:
												A__							 =       'MULTI_XPU'
								else:
												A__							 =       'NO'
				elif is_npu_available():
								A__							 =       torch.npu.device_count()
								A__							 =       num_npus
								A__							 =       False
								if num_npus > 1:
												A__							 =       'MULTI_NPU'
								else:
												A__							 =       'NO'
				else:
								A__							 =       0
								A__							 =       True
								A__							 =       1
								A__							 =       'NO'
				A__							 =       ClusterConfig(**lowerCAmelCase__				)
				config.to_json_file(lowerCAmelCase__				)
				return path



def  __lowerCamelCase					(					lowerCAmelCase__       ,lowerCAmelCase__				):
				A__							 =       parser.add_parser('default'       ,parents=lowerCAmelCase__       ,help=lowerCAmelCase__       ,formatter_class=lowerCAmelCase__				)
				parser.add_argument(
				    '--config_file'       ,default=lowerCAmelCase__       ,help=(
				        'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
				        'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
				        'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
				        'with \'huggingface\'.'
				    )       ,dest='save_location'       ,)

				parser.add_argument(
				    '--mixed_precision'       ,choices=['no', 'fp16', 'bf16']       ,type=lowerCAmelCase__       ,help='Whether or not to use mixed precision training. '
				    'Choose between FP16 and BF16 (bfloat16) training. '
				    'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'       ,default='no'       ,)
				parser.set_defaults(func=lowerCAmelCase__				)
				return parser







def  __lowerCamelCase					(					lowerCAmelCase__				):
				A__							 =       write_basic_config(args.mixed_precision       ,args.save_location				)
				if config_file:
								print(f'''accelerate configuration saved at {config_file}'''				)


