

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			):
  for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
    if class_name in extractors:
      UpperCAmelCase					      =  model_type_to_module_name(__A			)

      UpperCAmelCase					      =  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.
  UpperCAmelCase					      =  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   ,       ):
  UpperCAmelCase					      =  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 						__magic_name__    :


 def __init__(						self		: Union[str, Any]    )    ->      str:
   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 _UpperCamelCase	(						cls		: Optional[Any]			,						lowerCAmelCase__		: Union[str, Any]			,						**lowerCAmelCase__		: Any    )    ->      str:
   UpperCAmelCase					      =  kwargs.pop("config"			,						lowerCAmelCase__    )
   UpperCAmelCase					      =  kwargs.pop("trust_remote_code"			,						lowerCAmelCase__    )
   UpperCAmelCase					      =  True

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

   if feature_extractor_class is not None:
     UpperCAmelCase					      =  feature_extractor_class_from_name(lowerCAmelCase__    )

   UpperCAmelCase					      =  feature_extractor_auto_map is not None
   UpperCAmelCase					      =  feature_extractor_class is not None or type(lowerCAmelCase__    ) in FEATURE_EXTRACTOR_MAPPING
   UpperCAmelCase					      =  resolve_trust_remote_code(
       lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__    )

   if has_remote_code and trust_remote_code:
     UpperCAmelCase					      =  get_class_from_dynamic_module(
         lowerCAmelCase__			,						lowerCAmelCase__			,						**lowerCAmelCase__    )
     UpperCAmelCase					      =  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:
     UpperCAmelCase					      =  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 _UpperCamelCase	(						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: int    )    ->      Optional[int]:
   FEATURE_EXTRACTOR_MAPPING.register(lowerCAmelCase__			,						lowerCAmelCase__    )






import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
lowerCAmelCase__       = "src/diffusers"

# Matches is_xxx_available()
lowerCAmelCase__       = re.compile(r"is\_([a-z_]*)_available\(\)")
# Matches from xxx import bla
lowerCAmelCase__       = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")


lowerCAmelCase__       = "\n{0} = None\n"

lowerCAmelCase__       = "\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n"


lowerCAmelCase__       = "\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"
def      _lowerCAmelCase(	__A			):
  UpperCAmelCase					      =  _re_backend.findall(__A			)
  if len(__A			) == 0:
    return None

  return "_and_".join(__A			)
def      _lowerCAmelCase(	):
  with open(os.path.join(__A   ,       "__init__.py"			)   ,       "r"   ,       encoding="utf-8"   ,       newline="\n"			) as f:
    UpperCAmelCase					      =  f.readlines()

  # Get to the point we do the actual imports for type checking
  UpperCAmelCase					      =  0
  UpperCAmelCase					      =  {}
  # Go through the end of the file
  while line_index < len(__A			):
    # If the line contains is_backend_available, we grab all objects associated with the `else` block
    UpperCAmelCase					      =  find_backend(lines[line_index]			)
    if backend is not None:
      while not lines[line_index].startswith("else:"			):
        line_index += 1
      line_index += 1
      UpperCAmelCase					      =  []
      # Until we unindent, add backend objects to the list
      while line_index < len(__A			) and len(lines[line_index]			) > 1:
        UpperCAmelCase					      =  lines[line_index]
        UpperCAmelCase					      =  _re_single_line_import.search(__A			)
        if single_line_import_search is not None:
          objects.extend(single_line_import_search.groups()[0].split(", "			)			)
        elif line.startswith(" " * 8			):
          objects.append(line[8:-2]			)
        line_index += 1

      if len(__A			) > 0:
        UpperCAmelCase					      =  objects
    else:
      line_index += 1

  return backend_specific_objects
def      _lowerCAmelCase(	__A   ,       __A			):
  if name.isupper():
    return DUMMY_CONSTANT.format(__A			)
  elif name.islower():
    return DUMMY_FUNCTION.format(__A   ,       __A			)
  else:
    return DUMMY_CLASS.format(__A   ,       __A			)
def      _lowerCAmelCase(	__A=None			):
  if backend_specific_objects is None:
    UpperCAmelCase					      =  read_init()
  # For special correspondence backend to module name as used in the function requires_modulename
  UpperCAmelCase					      =  {}

  for backend, objects in backend_specific_objects.items():
    UpperCAmelCase					      =  "[" + ", ".join(F"\"{b}\"" for b in backend.split("_and_"			)			) + "]"
    UpperCAmelCase					      =  "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
    dummy_file += "\n".join([create_dummy_object(__A   ,       __A			) for o in objects]			)
    UpperCAmelCase					      =  dummy_file

  return dummy_files
def      _lowerCAmelCase(	__A=False			):
  UpperCAmelCase					      =  create_dummy_files()
  # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
  UpperCAmelCase					      =  {"torch": "pt"}

  # Locate actual dummy modules and read their content.
  UpperCAmelCase					      =  os.path.join(__A   ,       "utils"			)
  UpperCAmelCase					      =  {
      backend: os.path.join(__A   ,       F"dummy_{short_names.get(__A   ,       __A			)}_objects.py"			)
      for backend in dummy_files.keys()
  }

  UpperCAmelCase					      =  {}
  for backend, file_path in dummy_file_paths.items():
    if os.path.isfile(__A			):
      with open(__A   ,       "r"   ,       encoding="utf-8"   ,       newline="\n"			) as f:
        UpperCAmelCase					      =  f.read()
    else:
      UpperCAmelCase					      =  ""

  for backend in dummy_files.keys():
    if dummy_files[backend] != actual_dummies[backend]:
      if overwrite:
        print(
            F"Updating diffusers.utils.dummy_{short_names.get(__A   ,       __A			)}_objects.py as the main "
            "__init__ has new objects."			)
        with open(dummy_file_paths[backend]   ,       "w"   ,       encoding="utf-8"   ,       newline="\n"			) as f:
          f.write(dummy_files[backend]			)
      else:
        raise ValueError(
            "The main __init__ has objects that are not present in "
            F"diffusers.utils.dummy_{short_names.get(__A   ,       __A			)}_objects.py. Run `make fix-copies` "
            "to fix this."			)


if __name__ == "__main__":
      lowerCAmelCase__       = argparse.ArgumentParser()
      parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
      lowerCAmelCase__       = parser.parse_args()

      check_dummies(args.fix_and_overwrite)



