
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        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							_snake_case       :					Optional[int]				       =   0







		def        lowercase       (    self				)      ->      str:


							'''simple docstring'''

							_snake_case       :					str				       =   AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32"				)
							self.assertIsInstance(snake_case_ ,						snake_case_				)







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							with tempfile.TemporaryDirectory() as tmpdirname:
												_snake_case       :					Dict				       =   Path(snake_case_				) / "preprocessor_config.json"
												_snake_case       :					List[str]				       =   Path(snake_case_				) / "config.json"
												json.dump(
												    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} ,						open(snake_case_ ,						"w"				) ,						)
												json.dump({"model_type": "clip"} ,						open(snake_case_ ,						"w"				)				)

												_snake_case       :					Optional[Any]				       =   AutoImageProcessor.from_pretrained(snake_case_				)
												self.assertIsInstance(snake_case_ ,						snake_case_				)







		def        lowercase       (    self				)      ->      int:


							'''simple docstring'''

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

												_snake_case       :					Dict				       =   AutoImageProcessor.from_pretrained(snake_case_				)
												self.assertIsInstance(snake_case_ ,						snake_case_				)







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							with tempfile.TemporaryDirectory() as tmpdirname:
												_snake_case       :					Tuple				       =   CLIPConfig()

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

												# remove image_processor_type to make sure config.json alone is enough to load image processor locally
												_snake_case       :					int				       =   AutoImageProcessor.from_pretrained(snake_case_				).to_dict()

												config_dict.pop("image_processor_type"				)
												_snake_case       :					Dict				       =   CLIPImageProcessor(**snake_case_				)

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

												_snake_case       :					List[Any]				       =   AutoImageProcessor.from_pretrained(snake_case_				)

												# make sure private variable is not incorrectly saved
												_snake_case       :					Union[str, Any]				       =   json.loads(config.to_json_string()				)
												self.assertTrue("_processor_class" not in dict_as_saved				)

							self.assertIsInstance(snake_case_ ,						snake_case_				)







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

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

												_snake_case       :					Optional[Any]				       =   AutoImageProcessor.from_pretrained(snake_case_				)
												self.assertIsInstance(snake_case_ ,						snake_case_				)







		def        lowercase       (    self				)      ->      str:


							'''simple docstring'''

							with self.assertRaisesRegex(
							    snake_case_ ,						"clip-base is not a local folder and is not a valid model identifier"				):
												_snake_case       :					Optional[Any]				       =   AutoImageProcessor.from_pretrained("clip-base"				)







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


							'''simple docstring'''

							with self.assertRaisesRegex(
							    snake_case_ ,						r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"				):
												_snake_case       :					List[str]				       =   AutoImageProcessor.from_pretrained(snake_case_ ,						revision="aaaaaa"				)







		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

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







		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							with self.assertRaises(snake_case_				):
												_snake_case       :					str				       =   AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"				)
							# If remote code is disabled, we can't load this config.
							with self.assertRaises(snake_case_				):
												_snake_case       :					Union[str, Any]				       =   AutoImageProcessor.from_pretrained(
												    "hf-internal-testing/test_dynamic_image_processor" ,						trust_remote_code=snake_case_				)

							_snake_case       :					Dict				       =   AutoImageProcessor.from_pretrained(
							    "hf-internal-testing/test_dynamic_image_processor" ,						trust_remote_code=snake_case_				)
							self.assertEqual(image_processor.__class__.__name__ ,						"NewImageProcessor"				)

							# Test image processor can be reloaded.
							with tempfile.TemporaryDirectory() as tmp_dir:
												image_processor.save_pretrained(snake_case_				)
												_snake_case       :					Optional[Any]				       =   AutoImageProcessor.from_pretrained(snake_case_ ,						trust_remote_code=snake_case_				)
							self.assertEqual(reloaded_image_processor.__class__.__name__ ,						"NewImageProcessor"				)







		def        lowercase       (    self				)      ->      Any:


							'''simple docstring'''

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

												with tempfile.TemporaryDirectory() as tmpdirname:
																	_snake_case       :					Optional[Any]				       =   Path(snake_case_				) / "preprocessor_config.json"
																	_snake_case       :					Dict				       =   Path(snake_case_				) / "config.json"
																	json.dump(
																	    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} ,						open(snake_case_ ,						"w"				) ,						)
																	json.dump({"model_type": "clip"} ,						open(snake_case_ ,						"w"				)				)

																	_snake_case       :					Tuple				       =   CustomImageProcessor.from_pretrained(snake_case_				)

												# 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(snake_case_				)
																	_snake_case       :					Optional[Any]				       =   AutoImageProcessor.from_pretrained(snake_case_				)
																	self.assertIsInstance(snake_case_ ,						snake_case_				)

							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        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							class        _a(    _snake_case    ):
									lowerCamelCase__     :str   				=		True

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

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






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from .config import config_command_parser
from .config_args import default_config_file, load_config_from_file  # noqa: F401
from .default import default_command_parser
from .update import update_command_parser







def    A				(							UpperCAmelCase=None				):
					_snake_case       :					Union[str, Any]				       =   argparse.ArgumentParser(add_help=UpperCAmelCase  ,  allow_abbrev=UpperCAmelCase				)
					# The main config parser
					_snake_case       :					Tuple				       =   config_command_parser(UpperCAmelCase				)
					# The subparser to add commands to
					_snake_case       :					Any				       =   config_parser.add_subparsers(title="subcommands"  ,  dest="subcommand"				)

					# Then add other parsers with the parent parser
					default_command_parser(UpperCAmelCase  ,  parents=[parent_parser]				)
					update_command_parser(UpperCAmelCase  ,  parents=[parent_parser]				)

					return config_parser







def    A				(							):
					_snake_case       :					str				       =   get_config_parser()
					_snake_case       :					Union[str, Any]				       =   config_parser.parse_args()

					if not hasattr(UpperCAmelCase  ,  "func"				):
										config_parser.print_help()
										exit(1				)

					# Run
					args.func(UpperCAmelCase				)


if __name__ == "__main__":
							main()