






"""simple docstring"""




import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)






def        lowerCAmelCase (      UpperCamelCase_:							Dict     , UpperCamelCase_:							Any=False					)       ->							Tuple:







  '''simple docstring'''







  try:
    _a							=	os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    _a							=	default
  else:
    # KEY is set, convert it to True or False.
    try:
      _a							=	strtobool(UpperCamelCase_					)
    except ValueError:
      # More values are supported, but let's keep the message simple.
      raise ValueError(f'''If set, {key} must be yes or no.'''					)
  return _value


UpperCamelCase							       =    parse_flag_from_env("""RUN_SLOW""", default=False)






def        lowerCAmelCase (      UpperCamelCase_:							Dict					)       ->							Any:







  '''simple docstring'''







  return unittest.skip("Test was skipped"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							int					)       ->							List[str]:







  '''simple docstring'''







  return unittest.skipUnless(_run_slow_tests     , "test is slow"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[Any]					)       ->							Union[str, Any]:







  '''simple docstring'''







  return unittest.skipUnless(not torch.cuda.is_available()     , "test requires only a CPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, Any]					)       ->							Optional[Any]:







  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.is_available()     , "test requires a GPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[Any]					)       ->							Optional[Any]:







  '''simple docstring'''







  return unittest.skipUnless(is_xpu_available()     , "test requires a XPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[Any]					)       ->							Tuple:







  '''simple docstring'''







  return unittest.skipUnless(is_mps_available()     , "test requires a `mps` backend support in `torch`"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, Any]					)       ->							int:







  '''simple docstring'''







  return unittest.skipUnless(
      is_transformers_available() and is_datasets_available()     , "test requires the Hugging Face suite"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							List[Any]					)       ->							List[Any]:







  '''simple docstring'''







  return unittest.skipUnless(is_bnb_available()     , "test requires the bitsandbytes library"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							List[str]					)       ->							List[Any]:







  '''simple docstring'''







  return unittest.skipUnless(is_tpu_available()     , "test requires TPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Dict					)       ->							Any:







  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.device_count() == 1     , "test requires a GPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							List[str]					)       ->							str:







  '''simple docstring'''







  return unittest.skipUnless(torch.xpu.device_count() == 1     , "test requires a XPU"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							int					)       ->							Any:







  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.device_count() > 1     , "test requires multiple GPUs"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[Any]					)       ->							List[Any]:







  '''simple docstring'''







  return unittest.skipUnless(torch.xpu.device_count() > 1     , "test requires multiple XPUs"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Any					)       ->							Tuple:







  '''simple docstring'''







  return unittest.skipUnless(is_safetensors_available()     , "test requires safetensors"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Dict					)       ->							Any:







  '''simple docstring'''







  return unittest.skipUnless(is_deepspeed_available()     , "test requires DeepSpeed"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Any					)       ->							int:







  '''simple docstring'''







  return unittest.skipUnless(is_torch_version(">="     , "1.12.0"					)     , "test requires torch version >= 1.12.0"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Tuple=None     , UpperCamelCase_:							List[Any]=None					)       ->							Optional[Any]:







  '''simple docstring'''







  if test_case is None:
    return partial(UpperCamelCase_     , version=UpperCamelCase_					)
  return unittest.skipUnless(is_torch_version(">="     , UpperCamelCase_					)     , f'''test requires torch version >= {version}'''					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Tuple					)       ->							List[str]:







  '''simple docstring'''







  return unittest.skipUnless(is_tensorboard_available()     , "test requires Tensorboard"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, Any]					)       ->							str:







  '''simple docstring'''







  return unittest.skipUnless(is_wandb_available()     , "test requires wandb"					)(UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Dict					)       ->							Dict:







  '''simple docstring'''







  return unittest.skipUnless(is_comet_ml_available()     , "test requires comet_ml"					)(UpperCamelCase_					)


UpperCamelCase							       =    (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[int]					)       ->							Tuple:







  '''simple docstring'''







  return unittest.skipUnless(
      _atleast_one_tracker_available     , "test requires at least one tracker to be available and for `comet_ml` to not be installed"     , )(UpperCamelCase_					)




class    lowercase_    (unittest.TestCase     ):
      A__	:		Dict       			=				True






      @classmethod
      def 			lowerCamelCase__    (    cls	)	->Any:







        '''simple docstring'''


        _a							=	tempfile.mkdtemp()






      @classmethod
      def 			lowerCamelCase__    (    cls	)	->List[str]:







        '''simple docstring'''


        if os.path.exists(cls.tmpdir	):
          shutil.rmtree(cls.tmpdir	)






      def 			lowerCamelCase__    (    self	)	->List[str]:







        '''simple docstring'''


        if self.clear_on_setup:
          for path in Path(self.tmpdir	).glob("**/*"	):
            if path.is_file():
              path.unlink()
            elif path.is_dir():
              shutil.rmtree(a_	)







class    lowercase_    (unittest.TestCase     ):






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        super().tearDown()
        # Reset the state of the AcceleratorState singleton.
        AcceleratorState._reset_state()
        PartialState._reset_state()







class    lowercase_    (unittest.TestCase     ):






      def 			lowerCamelCase__    (    self     ,     a_	)	->Any:







        '''simple docstring'''


        _a							=	mocks if isinstance(a_     ,     (tuple, list)	) else [mocks]
        for m in self.mocks:
          m.start()
          self.addCleanup(m.stop	)







def        lowerCAmelCase (      UpperCamelCase_:							Any					)       ->							Union[str, Any]:







  '''simple docstring'''







  _a							=	AcceleratorState()
  _a							=	tensor[None].clone().to(state.device					)
  _a							=	gather(UpperCamelCase_					).cpu()
  _a							=	tensor[0].cpu()
  for i in range(tensors.shape[0]					):
    if not torch.equal(tensors[i]     , UpperCamelCase_					):
      return False
  return True




class    lowercase_    :






      def __init__(    self     ,     a_     ,     a_     ,     a_	)	->int:







        '''simple docstring'''


        _a							=	returncode
        _a							=	stdout
        _a							=	stderr







async def        lowerCAmelCase (      UpperCamelCase_:							Tuple     , UpperCamelCase_:							str					)       ->							Tuple:







  '''simple docstring'''







  while True:
    _a							=	await stream.readline()
    if line:
      callback(UpperCamelCase_					)
    else:
      break






async def        lowerCAmelCase (      UpperCamelCase_:							Optional[int]     , UpperCamelCase_:							List[Any]=None     , UpperCamelCase_:							List[Any]=None     , UpperCamelCase_:							List[Any]=None     , UpperCamelCase_:							Tuple=False     , UpperCamelCase_:							Union[str, Any]=False					)       ->							_RunOutput:







  '''simple docstring'''







  if echo:
    print("\nRunning: "     , " ".join(UpperCamelCase_					)					)

  _a							=	await asyncio.create_subprocess_exec(
      cmd[0]     , *cmd[1:]     , stdin=UpperCamelCase_     , stdout=asyncio.subprocess.PIPE     , stderr=asyncio.subprocess.PIPE     , env=UpperCamelCase_     , )

  # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
  # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
  #
  # If it starts hanging, will need to switch to the following code. The problem is that no data
  # will be seen until it's done and if it hangs for example there will be no debug info.
  # out, err = await p.communicate()
  # return _RunOutput(p.returncode, out, err)

  _a							=	[]
  _a							=	[]

  def tee(UpperCamelCase_:							Union[str, Any]     , UpperCamelCase_:							Tuple     , UpperCamelCase_:							List[Any]     , UpperCamelCase_:							List[Any]=""					):
    _a							=	line.decode("utf-8"					).rstrip()
    sink.append(UpperCamelCase_					)
    if not quiet:
      print(UpperCamelCase_     , UpperCamelCase_     , file=UpperCamelCase_					)

    # XXX: the timeout doesn't seem to make any difference here
  await asyncio.wait(
      [
          asyncio.create_task(_read_stream(p.stdout     , lambda UpperCamelCase_					: tee(UpperCamelCase_     , UpperCamelCase_     , sys.stdout     , label="stdout:"					)					)					),
          asyncio.create_task(_read_stream(p.stderr     , lambda UpperCamelCase_					: tee(UpperCamelCase_     , UpperCamelCase_     , sys.stderr     , label="stderr:"					)					)					),
      ]     , timeout=UpperCamelCase_     , )
  return _RunOutput(await p.wait()     , UpperCamelCase_     , UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							List[str]     , UpperCamelCase_:							Tuple=None     , UpperCamelCase_:							Union[str, Any]=None     , UpperCamelCase_:							Optional[int]=180     , UpperCamelCase_:							str=False     , UpperCamelCase_:							Any=True					)       ->							_RunOutput:







  '''simple docstring'''







  _a							=	asyncio.get_event_loop()
  _a							=	loop.run_until_complete(
      _stream_subprocess(UpperCamelCase_     , env=UpperCamelCase_     , stdin=UpperCamelCase_     , timeout=UpperCamelCase_     , quiet=UpperCamelCase_     , echo=UpperCamelCase_					)					)

  _a							=	" ".join(UpperCamelCase_					)
  if result.returncode > 0:
    _a							=	"\n".join(result.stderr					)
    raise RuntimeError(
        f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
        f'''The combined stderr from workers follows:\n{stderr}'''					)

  return result




class    lowercase_    (_UpperCAmelCase     ):
      pass







def        lowerCAmelCase (      UpperCamelCase_:							List[str]     , UpperCamelCase_:							Dict=False					)       ->							Tuple:







  '''simple docstring'''







  try:
    _a							=	subprocess.check_output(UpperCamelCase_     , stderr=subprocess.STDOUT					)
    if return_stdout:
      if hasattr(UpperCamelCase_     , "decode"					):
        _a							=	output.decode("utf-8"					)
      return output
  except subprocess.CalledProcessError as e:
    raise SubprocessCallException(
        f'''Command `{' '.join(UpperCamelCase_					)}` failed with the following error:\n\n{e.output.decode()}'''					) from e







"""simple docstring"""




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


UpperCamelCase							       =    logging.get_logger(__name__)

UpperCamelCase							       =    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"""),
    ]
)

UpperCamelCase							       =    _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)






def        lowerCAmelCase (      UpperCamelCase_:							str					)       ->							Union[str, Any]:







  '''simple docstring'''







  for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
    if class_name in extractors:
      _a							=	model_type_to_module_name(UpperCamelCase_					)

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

  for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
    if getattr(UpperCamelCase_     , "__name__"     , UpperCamelCase_					) == 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(UpperCamelCase_     , UpperCamelCase_					):
    return getattr(UpperCamelCase_     , UpperCamelCase_					)

  return None






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, os.PathLike]     , UpperCamelCase_:							Optional[Union[str, os.PathLike]] = None     , UpperCamelCase_:							bool = False     , UpperCamelCase_:							bool = False     , UpperCamelCase_:							Optional[Dict[str, str]] = None     , UpperCamelCase_:							Optional[Union[bool, str]] = None     , UpperCamelCase_:							Optional[str] = None     , UpperCamelCase_:							bool = False     , **UpperCamelCase_:							Dict     , )       ->							Optional[int]:







  '''simple docstring'''







  _a							=	get_file_from_repo(
      UpperCamelCase_     , UpperCamelCase_     , cache_dir=UpperCamelCase_     , force_download=UpperCamelCase_     , resume_download=UpperCamelCase_     , proxies=UpperCamelCase_     , use_auth_token=UpperCamelCase_     , revision=UpperCamelCase_     , local_files_only=UpperCamelCase_     , )
  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(UpperCamelCase_     , encoding="utf-8"					) as reader:
    return json.load(UpperCamelCase_					)




class    lowercase_    :






      def __init__(    self	)	->List[Any]:







        '''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(a_	)
      def 			lowerCamelCase__    (    cls     ,     a_     ,     **a_	)	->Dict:







        '''simple docstring'''


        _a							=	kwargs.pop("config"     ,     a_	)
        _a							=	kwargs.pop("trust_remote_code"     ,     a_	)
        _a							=	True

        _a			,	_a							=	ImageProcessingMixin.get_image_processor_dict(a_     ,     **a_	)
        _a							=	config_dict.get("image_processor_type"     ,     a_	)
        _a							=	None
        if "AutoImageProcessor" in config_dict.get("auto_map"     ,     {}	):
          _a							=	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:
          _a							=	config_dict.pop("feature_extractor_type"     ,     a_	)
          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."	)
            _a							=	feature_extractor_class.replace("FeatureExtractor"     ,     "ImageProcessor"	)
          if "AutoFeatureExtractor" in config_dict.get("auto_map"     ,     {}	):
            _a							=	config_dict["auto_map"]["AutoFeatureExtractor"]
            _a							=	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(a_     ,     a_	):
            _a							=	AutoConfig.from_pretrained(a_     ,     **a_	)
          # It could be in `config.image_processor_type``
          _a							=	getattr(a_     ,     "image_processor_type"     ,     a_	)
          if hasattr(a_     ,     "auto_map"	) and "AutoImageProcessor" in config.auto_map:
            _a							=	config.auto_map["AutoImageProcessor"]

        if image_processor_class is not None:
          _a							=	image_processor_class_from_name(a_	)

        _a							=	image_processor_auto_map is not None
        _a							=	image_processor_class is not None or type(a_	) in IMAGE_PROCESSOR_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_	):
            image_processor_class.register_for_auto_class()
          return image_processor_class.from_dict(a_     ,     **a_	)
        elif image_processor_class is not None:
          return image_processor_class.from_dict(a_     ,     **a_	)
        # Last try: we use the IMAGE_PROCESSOR_MAPPING.
        elif type(a_	) in IMAGE_PROCESSOR_MAPPING:
          _a							=	IMAGE_PROCESSOR_MAPPING[type(a_	)]
          return image_processor_class.from_dict(a_     ,     **a_	)

        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 			lowerCamelCase__    (    a_     ,     a_	)	->Optional[int]:







        '''simple docstring'''


        IMAGE_PROCESSOR_MAPPING.register(a_     ,     a_	)


