


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						:Optional[int]			=  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						:Any			=  _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)



def       _lowerCAmelCase    (				lowerCAmelCase_				:str				)->Optional[Any]:
   '''simple docstring'''






   for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
      if class_name in extractors:
         snake_case_            =       model_type_to_module_name(lowerCAmelCase_				)

         snake_case_            =       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.
   snake_case_            =       importlib.import_module("transformers"				)
   if hasattr(lowerCAmelCase_		,    lowerCAmelCase_				):
      return getattr(lowerCAmelCase_		,    lowerCAmelCase_				)

   return None



def       _lowerCAmelCase    (				lowerCAmelCase_				:Union[str, os.PathLike]		,    lowerCAmelCase_				:Optional[Union[str, os.PathLike]] = None		,    lowerCAmelCase_				:bool = False		,    lowerCAmelCase_				:bool = False		,    lowerCAmelCase_				:Optional[Dict[str, str]] = None		,    lowerCAmelCase_				:Optional[Union[bool, str]] = None		,    lowerCAmelCase_				:Optional[str] = None		,    lowerCAmelCase_				:bool = False		,    **lowerCAmelCase_				:List[Any]		,    )->int:
   '''simple docstring'''






   snake_case_            =       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      __lowerCAmelCase  :






  """simple docstring"""





  def __init__(  self							:							Optional[Any]	) ->			Dict:




     """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(_lowerCAmelCase	)
  def        lowerCAmelCase__	(  cls							:							List[str]     ,					_lowerCAmelCase							:							Optional[int]     ,					**_lowerCAmelCase							:							Union[str, Any]	) ->			Dict:




     """simple docstring"""
     snake_case_            =       kwargs.pop("config"     ,					_lowerCAmelCase	)
     snake_case_            =       kwargs.pop("trust_remote_code"     ,					_lowerCAmelCase	)
     snake_case_            =       True

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

     if feature_extractor_class is not None:
        snake_case_            =       feature_extractor_class_from_name(_lowerCAmelCase	)

     snake_case_            =       feature_extractor_auto_map is not None
     snake_case_            =       feature_extractor_class is not None or type(_lowerCAmelCase	) in FEATURE_EXTRACTOR_MAPPING
     snake_case_            =       resolve_trust_remote_code(
         _lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase	)

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

     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        lowerCAmelCase__	(  _lowerCAmelCase							:							Tuple     ,					_lowerCAmelCase							:							Optional[int]	) ->			Dict:




     """simple docstring"""
     FEATURE_EXTRACTOR_MAPPING.register(_lowerCAmelCase     ,					_lowerCAmelCase	)








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
   import PIL


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


class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		     =							['pixel_values']



  def __init__(  self							:							Optional[int]     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							PILImageResampling = PIL.Image.BICUBIC     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							Union[int, float] = 1 / 2_5_5     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					**_lowerCAmelCase							:							Optional[Any]     ,					) ->			None:




     """simple docstring"""
     super().__init__(**_lowerCAmelCase	)
     snake_case_            =       size if size is not None else {"height": 2_5_6, "width": 2_5_6}
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

     snake_case_            =       do_resize
     snake_case_            =       size
     snake_case_            =       resample
     snake_case_            =       do_center_crop
     snake_case_            =       crop_size
     snake_case_            =       do_rescale
     snake_case_            =       rescale_factor
     snake_case_            =       do_normalize
     snake_case_            =       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     snake_case_            =       image_std if image_std is not None else IMAGENET_STANDARD_STD



  def        lowerCAmelCase__	(  self							:							List[str]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							PILImageResampling = PIL.Image.BICUBIC     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							int     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     if "height" not in size or "width" not in size:
        raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
     return resize(
         _lowerCAmelCase     ,					size=(size["height"], size["width"])     ,					resample=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							int     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     if "height" not in size or "width" not in size:
        raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
     return center_crop(_lowerCAmelCase     ,					size=(size["height"], size["width"])     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Union[int, float]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							Union[str, Any]     ,					) ->			Optional[Any]:




     """simple docstring"""
     return rescale(_lowerCAmelCase     ,					scale=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Union[float, List[float]]     ,					_lowerCAmelCase							:							Union[float, List[float]]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							Any     ,					) ->			np.ndarray:




     """simple docstring"""
     return normalize(_lowerCAmelCase     ,					mean=_lowerCAmelCase     ,					std=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							ImageInput     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							int=None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							float = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[str, TensorType]] = None     ,					_lowerCAmelCase							:							ChannelDimension = ChannelDimension.FIRST     ,					**_lowerCAmelCase							:							Tuple     ,					) ->			PIL.Image.Image:




     """simple docstring"""
     snake_case_            =       do_resize if do_resize is not None else self.do_resize
     snake_case_            =       resample if resample is not None else self.resample
     snake_case_            =       do_center_crop if do_center_crop is not None else self.do_center_crop
     snake_case_            =       do_rescale if do_rescale is not None else self.do_rescale
     snake_case_            =       rescale_factor if rescale_factor is not None else self.rescale_factor
     snake_case_            =       do_normalize if do_normalize is not None else self.do_normalize
     snake_case_            =       image_mean if image_mean is not None else self.image_mean
     snake_case_            =       image_std if image_std is not None else self.image_std

     snake_case_            =       size if size is not None else self.size
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else self.crop_size
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

     snake_case_            =       make_list_of_images(_lowerCAmelCase	)

     if not valid_images(_lowerCAmelCase	):
        raise ValueError(
            "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
            "torch.Tensor, tf.Tensor or jax.ndarray."	)

     if do_resize and size is None or resample is None:
        raise ValueError("Size and resample must be specified if do_resize is True."	)

     if do_center_crop and crop_size is None:
        raise ValueError("Crop size must be specified if do_center_crop is True."	)

     if do_rescale and rescale_factor is None:
        raise ValueError("Rescale factor must be specified if do_rescale is True."	)

     if do_normalize and (image_mean is None or image_std is None):
        raise ValueError("Image mean and std must be specified if do_normalize is True."	)

     # All transformations expect numpy arrays.
     snake_case_            =       [to_numpy_array(_lowerCAmelCase	) for image in images]

     if do_resize:
        snake_case_            =       [self.resize(image=_lowerCAmelCase     ,					size=_lowerCAmelCase     ,					resample=_lowerCAmelCase	) for image in images]

     if do_center_crop:
        snake_case_            =       [self.center_crop(image=_lowerCAmelCase     ,					size=_lowerCAmelCase	) for image in images]

     if do_rescale:
        snake_case_            =       [self.rescale(image=_lowerCAmelCase     ,					scale=_lowerCAmelCase	) for image in images]

     if do_normalize:
        snake_case_            =       [self.normalize(image=_lowerCAmelCase     ,					mean=_lowerCAmelCase     ,					std=_lowerCAmelCase	) for image in images]

     snake_case_            =       [to_channel_dimension_format(_lowerCAmelCase     ,					_lowerCAmelCase	) for image in images]

     snake_case_            =       {"pixel_values": images}
     return BatchFeature(data=_lowerCAmelCase     ,					tensor_type=_lowerCAmelCase	)




