





'''simple docstring'''

import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


a   	=    threading.Lock()
a   	=    None

a   	=    {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL,
}

a   	=    logging.WARNING

a   	=    True

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

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							os.getenv("""TRANSFORMERS_VERBOSITY"""				,						__UpperCAmelCase   )
   if env_level_str:
      if env_level_str in log_levels:
         return log_levels[env_level_str]
      else:
         logging.getLogger().warning(
             f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
             f"""has to be one of: { ', '.join(log_levels.keys()   ) }"""   )
   return _default_log_level

def     __magic_name__							(				)    ->       str:

   '''simple docstring'''







   return __name__.split("""."""   )[0]

def     __magic_name__							(				)    ->       logging.Logger:

   '''simple docstring'''







   return logging.getLogger(_get_library_name()   )

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   global _default_handler

   with _lock:
      if _default_handler:
         # This library has already configured the library root logger.
         return
      __SCREAMING_SNAKE_CASE   				=							logging.StreamHandler()  # Set sys.stderr as stream.
      __SCREAMING_SNAKE_CASE   				=							sys.stderr.flush

      # Apply our default configuration to the library root logger.
      __SCREAMING_SNAKE_CASE   				=							_get_library_root_logger()
      library_root_logger.addHandler(_default_handler   )
      library_root_logger.setLevel(_get_default_logging_level()   )
      __SCREAMING_SNAKE_CASE   				=							False

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   global _default_handler

   with _lock:
      if not _default_handler:
         return

      __SCREAMING_SNAKE_CASE   				=							_get_library_root_logger()
      library_root_logger.removeHandler(_default_handler   )
      library_root_logger.setLevel(logging.NOTSET   )
      __SCREAMING_SNAKE_CASE   				=							None

def     __magic_name__							(				)    ->       int:

   '''simple docstring'''







   return log_levels

def     __magic_name__							(				__UpperCAmelCase = None   )    ->       logging.Logger:

   '''simple docstring'''







   if name is None:
      __SCREAMING_SNAKE_CASE   				=							_get_library_name()

   _configure_library_root_logger()
   return logging.getLogger(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       int:

   '''simple docstring'''







   _configure_library_root_logger()
   return _get_library_root_logger().getEffectiveLevel()

def     __magic_name__							(				__UpperCAmelCase   )    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()
   _get_library_root_logger().setLevel(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       str:

   '''simple docstring'''







   return set_verbosity(__UpperCAmelCase   )

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

   '''simple docstring'''







   return set_verbosity(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       Optional[int]:

   '''simple docstring'''







   return set_verbosity(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       Tuple:

   '''simple docstring'''







   return set_verbosity(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()

   assert _default_handler is not None
   _get_library_root_logger().removeHandler(_default_handler   )

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()

   assert _default_handler is not None
   _get_library_root_logger().addHandler(_default_handler   )

def     __magic_name__							(				__UpperCAmelCase   )    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()

   assert handler is not None
   _get_library_root_logger().addHandler(__UpperCAmelCase   )

def     __magic_name__							(				__UpperCAmelCase   )    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()

   assert handler is not None and handler not in _get_library_root_logger().handlers
   _get_library_root_logger().removeHandler(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()
   __SCREAMING_SNAKE_CASE   				=							False

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   _configure_library_root_logger()
   __SCREAMING_SNAKE_CASE   				=							True

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							_get_library_root_logger().handlers

   for handler in handlers:
      __SCREAMING_SNAKE_CASE   				=							logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s"""   )
      handler.setFormatter(__UpperCAmelCase   )

def     __magic_name__							(				)    ->       None:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							_get_library_root_logger().handlers

   for handler in handlers:
      handler.setFormatter(__UpperCAmelCase   )

def     __magic_name__							(				self				,						*__UpperCAmelCase				,						**__UpperCAmelCase   )    ->       Optional[int]:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS"""				,						__UpperCAmelCase   )
   if no_advisory_warnings:
      return
   self.warning(*__UpperCAmelCase				,						**__UpperCAmelCase   )


a   	=    warning_advice

@functools.lru_cache(__UpperCAmelCase   )
def     __magic_name__							(				self				,						*__UpperCAmelCase				,						**__UpperCAmelCase   )    ->       str:

   '''simple docstring'''







   self.warning(*__UpperCAmelCase				,						**__UpperCAmelCase   )


a   	=    warning_once







class __a			:





   def __init__(       self					:      List[Any]					,*lowerCamelCase					:      Union[str, Any]					,**lowerCamelCase					:      Optional[int]     ):  # pylint: disable=unused-argument

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							args[0] if args else None





   def __iter__(       self					:      Optional[int]     ):

      '''simple docstring'''

      return iter(self._iterator     )





   def __getattr__(       self					:      List[str]					,lowerCamelCase					:      int     ):

      '''simple docstring'''

      def empty_fn(*lowerCamelCase					:      Any					,**lowerCamelCase					:      Tuple     ):  # pylint: disable=unused-argument
         return

      return empty_fn





   def __enter__(       self					:      List[Any]     ):

      '''simple docstring'''

      return self





   def __exit__(       self					:      List[Any]					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      Tuple     ):

      '''simple docstring'''

      return







class __a			:





   def __call__(       self					:      Optional[Any]					,*lowerCamelCase					:      Optional[Any]					,**lowerCamelCase					:      Union[str, Any]     ):

      '''simple docstring'''

      if _tqdm_active:
         return tqdm_lib.tqdm(*lowerCamelCase					,**lowerCamelCase     )
      else:
         return EmptyTqdm(*lowerCamelCase					,**lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[Any]					,*lowerCamelCase					:      List[Any]					,**lowerCamelCase					:      Union[str, Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							None
      if _tqdm_active:
         return tqdm_lib.tqdm.set_lock(*lowerCamelCase					,**lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      if _tqdm_active:
         return tqdm_lib.tqdm.get_lock()





a   	=    _tqdm_cls()

def     __magic_name__							(				)    ->       bool:

   '''simple docstring'''







   global _tqdm_active
   return bool(_tqdm_active   )

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

   '''simple docstring'''







   global _tqdm_active
   __SCREAMING_SNAKE_CASE   				=							True
   hf_hub_utils.enable_progress_bars()







def     __magic_name__							(				)    ->       Tuple:

   '''simple docstring'''







   global _tqdm_active
   __SCREAMING_SNAKE_CASE   				=							False
   hf_hub_utils.disable_progress_bars()












'''simple docstring'''

import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402







class __a			( unittest.TestCase      ):





   def   UpperCAmelCase__  (       self					:      Any     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							0





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32"""     )
      self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdirname:
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """preprocessor_config.json"""
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """config.json"""
         json.dump(
             {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}					,open(lowerCamelCase					,"""w"""     )					,)
         json.dump({"""model_type""": """clip"""}					,open(lowerCamelCase					,"""w"""     )     )

         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     )
         self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[Any]     ):

      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdirname:
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """preprocessor_config.json"""
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """config.json"""
         json.dump(
             {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""}					,open(lowerCamelCase					,"""w"""     )					,)
         json.dump({"""model_type""": """clip"""}					,open(lowerCamelCase					,"""w"""     )     )

         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     )
         self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      List[str]     ):

      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdirname:
         __SCREAMING_SNAKE_CASE   				=							CLIPConfig()

         # Create a dummy config file with image_proceesor_type
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """preprocessor_config.json"""
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """config.json"""
         json.dump(
             {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}					,open(lowerCamelCase					,"""w"""     )					,)
         json.dump({"""model_type""": """clip"""}					,open(lowerCamelCase					,"""w"""     )     )

         # remove image_processor_type to make sure config.json alone is enough to load image processor locally
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     ).to_dict()

         config_dict.pop("""image_processor_type"""     )
         __SCREAMING_SNAKE_CASE   				=							CLIPImageProcessor(**lowerCamelCase     )

         # save in new folder
         model_config.save_pretrained(lowerCamelCase     )
         config.save_pretrained(lowerCamelCase     )

         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     )

         # make sure private variable is not incorrectly saved
         __SCREAMING_SNAKE_CASE   				=							json.loads(config.to_json_string()     )
         self.assertTrue("""_processor_class""" not in dict_as_saved     )

      self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Union[str, Any]     ):

      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdirname:
         __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """preprocessor_config.json"""
         json.dump(
             {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}					,open(lowerCamelCase					,"""w"""     )					,)

         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     )
         self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      with self.assertRaisesRegex(
          lowerCamelCase					,"""clip-base is not a local folder and is not a valid model identifier"""     ):
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained("""clip-base"""     )





   def   UpperCAmelCase__  (       self					:      Any     ):

      '''simple docstring'''

      with self.assertRaisesRegex(
          lowerCamelCase					,r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""     ):
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase					,revision="""aaaaaa"""     )





   def   UpperCAmelCase__  (       self					:      List[Any]     ):

      '''simple docstring'''

      with self.assertRaisesRegex(
          lowerCamelCase					,"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""					,):
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model"""     )





   def   UpperCAmelCase__  (       self					:      Any     ):

      '''simple docstring'''

      with self.assertRaises(lowerCamelCase     ):
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor"""     )
      # If remote code is disabled, we can't load this config.
      with self.assertRaises(lowerCamelCase     ):
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(
             """hf-internal-testing/test_dynamic_image_processor"""					,trust_remote_code=lowerCamelCase     )

      __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(
          """hf-internal-testing/test_dynamic_image_processor"""					,trust_remote_code=lowerCamelCase     )
      self.assertEqual(image_processor.__class__.__name__					,"""NewImageProcessor"""     )

      # Test image processor can be reloaded.
      with tempfile.TemporaryDirectory() as tmp_dir:
         image_processor.save_pretrained(lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase					,trust_remote_code=lowerCamelCase     )
      self.assertEqual(reloaded_image_processor.__class__.__name__					,"""NewImageProcessor"""     )





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      try:
         AutoConfig.register("""custom"""					,lowerCamelCase     )
         AutoImageProcessor.register(lowerCamelCase					,lowerCamelCase     )
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(lowerCamelCase     ):
            AutoImageProcessor.register(lowerCamelCase					,lowerCamelCase     )

         with tempfile.TemporaryDirectory() as tmpdirname:
            __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """preprocessor_config.json"""
            __SCREAMING_SNAKE_CASE   				=							Path(lowerCamelCase     ) / """config.json"""
            json.dump(
                {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""}					,open(lowerCamelCase					,"""w"""     )					,)
            json.dump({"""model_type""": """clip"""}					,open(lowerCamelCase					,"""w"""     )     )

            __SCREAMING_SNAKE_CASE   				=							CustomImageProcessor.from_pretrained(lowerCamelCase     )

         # Now that the config is registered, it can be used as any other config with the auto-API
         with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(lowerCamelCase     )
            __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(lowerCamelCase     )
            self.assertIsInstance(lowerCamelCase					,lowerCamelCase     )

      finally:
         if "custom" in CONFIG_MAPPING._extra_content:
            del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
            del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      class __a			( _snake_case      ):
         __UpperCamelCase :			int						   =						True

      try:
         AutoConfig.register("""custom"""					,lowerCamelCase     )
         AutoImageProcessor.register(lowerCamelCase					,lowerCamelCase     )
         # If remote code is not set, the default is to use local
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor"""     )
         self.assertEqual(image_processor.__class__.__name__					,"""NewImageProcessor"""     )
         self.assertTrue(image_processor.is_local     )

         # If remote code is disabled, we load the local one.
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(
             """hf-internal-testing/test_dynamic_image_processor"""					,trust_remote_code=lowerCamelCase     )
         self.assertEqual(image_processor.__class__.__name__					,"""NewImageProcessor"""     )
         self.assertTrue(image_processor.is_local     )

         # If remote is enabled, we load from the Hub
         __SCREAMING_SNAKE_CASE   				=							AutoImageProcessor.from_pretrained(
             """hf-internal-testing/test_dynamic_image_processor"""					,trust_remote_code=lowerCamelCase     )
         self.assertEqual(image_processor.__class__.__name__					,"""NewImageProcessor"""     )
         self.assertTrue(not hasattr(lowerCamelCase					,"""is_local"""     )     )

      finally:
         if "custom" in CONFIG_MAPPING._extra_content:
            del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
            del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





