
"""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 __lowerCAmelCase	(   unittest.TestCase    ):





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




						__UpperCamelCase       						= 0





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




						__UpperCamelCase       						= AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32'   )
						self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase   )
							self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase   )
							self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

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

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

							config_dict.pop('image_processor_type'   )
							__UpperCamelCase       						= CLIPImageProcessor(**__UpperCAmelCase   )

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

							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase   )

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

						self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase   )
							self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




						with self.assertRaisesRegex(
						    __UpperCAmelCase			,  'clip-base is not a local folder and is not a valid model identifier'   ):
							__UpperCamelCase       						= AutoImageProcessor.from_pretrained('clip-base'   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




						with self.assertRaisesRegex(
						    __UpperCAmelCase			,  R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'   ):
							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase			,  revision='aaaaaa'   )





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

						__UpperCamelCase       						= AutoImageProcessor.from_pretrained(
						    'hf-internal-testing/test_dynamic_image_processor'			,  trust_remote_code=__UpperCAmelCase   )
						self.assertEqual(image_processor.__class__.__name__			,  'NewImageProcessor'   )

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





					def 		UpperCAmelCase      (			self   ):

						'''simple docstring'''




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

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

								__UpperCamelCase       						= CustomImageProcessor.from_pretrained(__UpperCAmelCase   )

							# 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(__UpperCAmelCase   )
								__UpperCamelCase       						= AutoImageProcessor.from_pretrained(__UpperCAmelCase   )
								self.assertIsInstance(__UpperCAmelCase			,  __UpperCAmelCase   )

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

						'''simple docstring'''




						class __lowerCAmelCase	(   __SCREAMING_SNAKE_CASE    ):
											lowercase		     =		True

						try:
							AutoConfig.register('custom'			,  __UpperCAmelCase   )
							AutoImageProcessor.register(__UpperCAmelCase			,  __UpperCAmelCase   )
							# If remote code is not set, the default is to use local
							__UpperCamelCase       						= 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.
							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_image_processor'			,  trust_remote_code=__UpperCAmelCase   )
							self.assertEqual(image_processor.__class__.__name__			,  'NewImageProcessor'   )
							self.assertTrue(image_processor.is_local   )

							# If remote is enabled, we load from the Hub
							__UpperCamelCase       						= AutoImageProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_image_processor'			,  trust_remote_code=__UpperCAmelCase   )
							self.assertEqual(image_processor.__class__.__name__			,  'NewImageProcessor'   )
							self.assertTrue(not hasattr(__UpperCAmelCase			,  '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]





"""simple docstring"""

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCamelCase			:       Dict									=				{
    "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"],
    "tokenization_lxmert": ["LxmertTokenizer"],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase			:       List[str]									=				["LxmertTokenizerFast"]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase			:       Optional[Any]									=				[
          "LxmertEncoder",
          "LxmertForPreTraining",
          "LxmertForQuestionAnswering",
          "LxmertModel",
          "LxmertPreTrainedModel",
          "LxmertVisualFeatureEncoder",
          "LxmertXLayer",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase			:       List[Any]									=				[
          "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST",
          "TFLxmertForPreTraining",
          "TFLxmertMainLayer",
          "TFLxmertModel",
          "TFLxmertPreTrainedModel",
          "TFLxmertVisualFeatureEncoder",
      ]


if TYPE_CHECKING:
      from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig
      from .tokenization_lxmert import LxmertTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_lxmert_fast import LxmertTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_lxmert import (
                LxmertEncoder,
                LxmertForPreTraining,
                LxmertForQuestionAnswering,
                LxmertModel,
                LxmertPreTrainedModel,
                LxmertVisualFeatureEncoder,
                LxmertXLayer,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_lxmert import (
                TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFLxmertForPreTraining,
                TFLxmertMainLayer,
                TFLxmertModel,
                TFLxmertPreTrainedModel,
                TFLxmertVisualFeatureEncoder,
            )

else:
      import sys

      UpperCamelCase			:       Any									=				_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



