





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

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_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,
)


__A     =    logging.get_logger(__name__)

__A     =    OrderedDict(
    [
        ("align", "EfficientNetImageProcessor"),
        ("beit", "BeitImageProcessor"),
        ("bit", "BitImageProcessor"),
        ("blip", "BlipImageProcessor"),
        ("blip-2", "BlipImageProcessor"),
        ("bridgetower", "BridgeTowerImageProcessor"),
        ("chinese_clip", "ChineseCLIPImageProcessor"),
        ("clip", "CLIPImageProcessor"),
        ("clipseg", "ViTImageProcessor"),
        ("conditional_detr", "ConditionalDetrImageProcessor"),
        ("convnext", "ConvNextImageProcessor"),
        ("convnextv2", "ConvNextImageProcessor"),
        ("cvt", "ConvNextImageProcessor"),
        ("data2vec-vision", "BeitImageProcessor"),
        ("deformable_detr", "DeformableDetrImageProcessor"),
        ("deit", "DeiTImageProcessor"),
        ("deta", "DetaImageProcessor"),
        ("detr", "DetrImageProcessor"),
        ("dinat", "ViTImageProcessor"),
        ("donut-swin", "DonutImageProcessor"),
        ("dpt", "DPTImageProcessor"),
        ("efficientformer", "EfficientFormerImageProcessor"),
        ("efficientnet", "EfficientNetImageProcessor"),
        ("flava", "FlavaImageProcessor"),
        ("focalnet", "BitImageProcessor"),
        ("git", "CLIPImageProcessor"),
        ("glpn", "GLPNImageProcessor"),
        ("groupvit", "CLIPImageProcessor"),
        ("imagegpt", "ImageGPTImageProcessor"),
        ("instructblip", "BlipImageProcessor"),
        ("layoutlmv2", "LayoutLMv2ImageProcessor"),
        ("layoutlmv3", "LayoutLMv3ImageProcessor"),
        ("levit", "LevitImageProcessor"),
        ("mask2former", "Mask2FormerImageProcessor"),
        ("maskformer", "MaskFormerImageProcessor"),
        ("mgp-str", "ViTImageProcessor"),
        ("mobilenet_v1", "MobileNetV1ImageProcessor"),
        ("mobilenet_v2", "MobileNetV2ImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevitv2", "MobileViTImageProcessor"),
        ("nat", "ViTImageProcessor"),
        ("oneformer", "OneFormerImageProcessor"),
        ("owlvit", "OwlViTImageProcessor"),
        ("perceiver", "PerceiverImageProcessor"),
        ("pix2struct", "Pix2StructImageProcessor"),
        ("poolformer", "PoolFormerImageProcessor"),
        ("regnet", "ConvNextImageProcessor"),
        ("resnet", "ConvNextImageProcessor"),
        ("sam", "SamImageProcessor"),
        ("segformer", "SegformerImageProcessor"),
        ("swiftformer", "ViTImageProcessor"),
        ("swin", "ViTImageProcessor"),
        ("swin2sr", "Swin2SRImageProcessor"),
        ("swinv2", "ViTImageProcessor"),
        ("table-transformer", "DetrImageProcessor"),
        ("timesformer", "VideoMAEImageProcessor"),
        ("tvlt", "TvltImageProcessor"),
        ("upernet", "SegformerImageProcessor"),
        ("van", "ConvNextImageProcessor"),
        ("videomae", "VideoMAEImageProcessor"),
        ("vilt", "ViltImageProcessor"),
        ("vit", "ViTImageProcessor"),
        ("vit_hybrid", "ViTHybridImageProcessor"),
        ("vit_mae", "ViTImageProcessor"),
        ("vit_msn", "ViTImageProcessor"),
        ("xclip", "CLIPImageProcessor"),
        ("yolos", "YolosImageProcessor"),
    ]
)

__A     =    _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)





def 					lowerCAmelCase_			(	__a		)					->		Tuple:







  """simple docstring"""





  for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
    if class_name in extractors:
      lowerCamelCase__:				Optional[Any]        =model_type_to_module_name(__a		)

      lowerCamelCase__:				Dict        =importlib.import_module(F""".{module_name}"""     ,   "transformers.models"		)
      try:
        return getattr(__a     ,   __a		)
      except AttributeError:
        continue

  for _, extractor in IMAGE_PROCESSOR_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__:				Any        =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     ,   )					->		int:







  """simple docstring"""





  lowerCamelCase__:				List[str]        =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 image processor configuration file, will try to use the model config instead."		)
    return {}

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






class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 def __init__(self    :       str)	->int:



   '''simple docstring'''



   raise EnvironmentError(
       "AutoImageProcessor is designed to be instantiated "
       "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.")

 @classmethod
 @replace_list_option_in_docstrings(UpperCAmelCase_)
 def 							SCREAMING_SNAKE_CASE_ (cls    :       str	,			UpperCAmelCase_    :       List[Any]	,			**UpperCAmelCase_    :       List[Any])	->Any:



   '''simple docstring'''



   lowerCamelCase__:				int        =kwargs.pop("config"	,			UpperCAmelCase_)
   lowerCamelCase__:				str        =kwargs.pop("trust_remote_code"	,			UpperCAmelCase_)
   lowerCamelCase__:				int        =True

   lowerCamelCase__  , lowerCamelCase__:				str        =ImageProcessingMixin.get_image_processor_dict(UpperCAmelCase_	,			**UpperCAmelCase_)
   lowerCamelCase__:				Optional[int]        =config_dict.get("image_processor_type"	,			UpperCAmelCase_)
   lowerCamelCase__:				str        =None
   if "AutoImageProcessor" in config_dict.get("auto_map"	,			{}):
     lowerCamelCase__:				Union[str, Any]        =config_dict["auto_map"]["AutoImageProcessor"]

   # If we still don't have the image processor class, check if we're loading from a previous feature extractor config
   # and if so, infer the image processor class from there.
   if image_processor_class is None and image_processor_auto_map is None:
     lowerCamelCase__:				Dict        =config_dict.pop("feature_extractor_type"	,			UpperCAmelCase_)
     if feature_extractor_class is not None:
       logger.warning(
           "Could not find image processor class in the image processor config or the model config. Loading"
           " based on pattern matching with the model's feature extractor configuration.")
       lowerCamelCase__:				Tuple        =feature_extractor_class.replace("FeatureExtractor"	,			"ImageProcessor")
     if "AutoFeatureExtractor" in config_dict.get("auto_map"	,			{}):
       lowerCamelCase__:				Optional[Any]        =config_dict["auto_map"]["AutoFeatureExtractor"]
       lowerCamelCase__:				str        =feature_extractor_auto_map.replace("FeatureExtractor"	,			"ImageProcessor")
       logger.warning(
           "Could not find image processor auto map in the image processor config or the model config."
           " Loading based on pattern matching with the model's feature extractor configuration.")

        # If we don't find the image processor class in the image processor config, let's try the model config.
   if image_processor_class is None and image_processor_auto_map is None:
     if not isinstance(UpperCAmelCase_	,			UpperCAmelCase_):
       lowerCamelCase__:				List[str]        =AutoConfig.from_pretrained(UpperCAmelCase_	,			**UpperCAmelCase_)
     # It could be in `config.image_processor_type``
     lowerCamelCase__:				List[str]        =getattr(UpperCAmelCase_	,			"image_processor_type"	,			UpperCAmelCase_)
     if hasattr(UpperCAmelCase_	,			"auto_map") and "AutoImageProcessor" in config.auto_map:
       lowerCamelCase__:				Optional[Any]        =config.auto_map["AutoImageProcessor"]

   if image_processor_class is not None:
     lowerCamelCase__:				Union[str, Any]        =image_processor_class_from_name(UpperCAmelCase_)

   lowerCamelCase__:				Tuple        =image_processor_auto_map is not None
   lowerCamelCase__:				List[Any]        =image_processor_class is not None or type(UpperCAmelCase_) in IMAGE_PROCESSOR_MAPPING
   lowerCamelCase__:				Union[str, Any]        =resolve_trust_remote_code(
       UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_)

   if has_remote_code and trust_remote_code:
     lowerCamelCase__:				List[Any]        =get_class_from_dynamic_module(
         UpperCAmelCase_	,			UpperCAmelCase_	,			**UpperCAmelCase_)
     lowerCamelCase__:				Dict        =kwargs.pop("code_revision"	,			UpperCAmelCase_)
     if os.path.isdir(UpperCAmelCase_):
       image_processor_class.register_for_auto_class()
     return image_processor_class.from_dict(UpperCAmelCase_	,			**UpperCAmelCase_)
   elif image_processor_class is not None:
     return image_processor_class.from_dict(UpperCAmelCase_	,			**UpperCAmelCase_)
   # Last try: we use the IMAGE_PROCESSOR_MAPPING.
   elif type(UpperCAmelCase_) in IMAGE_PROCESSOR_MAPPING:
     lowerCamelCase__:				Optional[int]        =IMAGE_PROCESSOR_MAPPING[type(UpperCAmelCase_)]
     return image_processor_class.from_dict(UpperCAmelCase_	,			**UpperCAmelCase_)

   raise ValueError(
       F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """
       F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """
       F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}""")







 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       Any	,			UpperCAmelCase_    :       Optional[int])	->List[Any]:



   '''simple docstring'''



   IMAGE_PROCESSOR_MAPPING.register(UpperCAmelCase_	,			UpperCAmelCase_)








from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand





def 					lowerCAmelCase_			(	__a		)					->		int:







  """simple docstring"""





  return ConvertCommand(
      args.model_type     ,   args.tf_checkpoint     ,   args.pytorch_dump_output     ,   args.config     ,   args.finetuning_task_name		)


__A     =    "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n"






class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       ArgumentParser)	->str:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =parser.add_parser(
       "convert"	,			help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints."	,			)
   train_parser.add_argument("--model_type"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Model's type.")
   train_parser.add_argument(
       "--tf_checkpoint"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="TensorFlow checkpoint path or folder.")
   train_parser.add_argument(
       "--pytorch_dump_output"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Path to the PyTorch saved model output.")
   train_parser.add_argument("--config"	,			type=UpperCAmelCase_	,			default=""	,			help="Configuration file path or folder.")
   train_parser.add_argument(
       "--finetuning_task_name"	,			type=UpperCAmelCase_	,			default=UpperCAmelCase_	,			help="Optional fine-tuning task name if the TF model was a finetuned model."	,			)
   train_parser.set_defaults(func=UpperCAmelCase_)

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			*UpperCAmelCase_    :       Optional[int]	,			)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =logging.get_logger("transformers-cli/converting")

   self._logger.info(F"""Loading model {model_type}""")
   lowerCamelCase__:				Any        =model_type
   lowerCamelCase__:				Optional[int]        =tf_checkpoint
   lowerCamelCase__:				Any        =pytorch_dump_output
   lowerCamelCase__:				Union[str, Any]        =config
   lowerCamelCase__:				str        =finetuning_task_name







 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->Tuple:



   '''simple docstring'''



   if self._model_type == "albert":
     try:
       from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "bert":
     try:
       from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "funnel":
     try:
       from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "t5":
     try:
       from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "gpt":
     from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
         convert_openai_checkpoint_to_pytorch,
     )

     convert_openai_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "transfo_xl":
     try:
       from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
           convert_transfo_xl_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     if "ckpt" in self._tf_checkpoint.lower():
       lowerCamelCase__:				Tuple        =self._tf_checkpoint
       lowerCamelCase__:				List[str]        =""
     else:
       lowerCamelCase__:				Any        =self._tf_checkpoint
       lowerCamelCase__:				Dict        =""
     convert_transfo_xl_checkpoint_to_pytorch(
         UpperCAmelCase_	,			self._config	,			self._pytorch_dump_output	,			UpperCAmelCase_)
   elif self._model_type == "gpt2":
     try:
       from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
           convert_gpta_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "xlnet":
     try:
       from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
           convert_xlnet_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_xlnet_checkpoint_to_pytorch(
         self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output	,			self._finetuning_task_name)
   elif self._model_type == "xlm":
     from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
         convert_xlm_checkpoint_to_pytorch,
     )

     convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint	,			self._pytorch_dump_output)
   elif self._model_type == "lxmert":
     from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
         convert_lxmert_checkpoint_to_pytorch,
     )

     convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint	,			self._pytorch_dump_output)
   elif self._model_type == "rembert":
     from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
         convert_rembert_tf_checkpoint_to_pytorch,
     )

     convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   else:
     raise ValueError(
         "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]")

