




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



 '''simple docstring'''


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

       """simple docstring"""






       lowerCamelCase_	  =					0

 def        a__				(       self      :						Dict						)     ->			Any:

       """simple docstring"""






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

 def        a__				(       self      :						Any						)     ->			List[str]:

       """simple docstring"""






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

             lowerCamelCase_	  =					AutoImageProcessor.from_pretrained(A_						)
             self.assertIsInstance(A_		,							A_						)

 def        a__				(       self      :						str						)     ->			int:

       """simple docstring"""






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

             lowerCamelCase_	  =					AutoImageProcessor.from_pretrained(A_						)
             self.assertIsInstance(A_		,							A_						)

 def        a__				(       self      :						Optional[int]						)     ->			List[str]:

       """simple docstring"""






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

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

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

             config_dict.pop('image_processor_type'						)
             lowerCamelCase_	  =					CLIPImageProcessor(**A_						)

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

             lowerCamelCase_	  =					AutoImageProcessor.from_pretrained(A_						)

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

       self.assertIsInstance(A_		,							A_						)

 def        a__				(       self      :						int						)     ->			Optional[Any]:

       """simple docstring"""






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

             lowerCamelCase_	  =					AutoImageProcessor.from_pretrained(A_						)
             self.assertIsInstance(A_		,							A_						)

 def        a__				(       self      :						List[str]						)     ->			List[Any]:

       """simple docstring"""






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

 def        a__				(       self      :						Union[str, Any]						)     ->			int:

       """simple docstring"""






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

 def        a__				(       self      :						Optional[int]						)     ->			Optional[Any]:

       """simple docstring"""






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

 def        a__				(       self      :						Optional[int]						)     ->			List[str]:

       """simple docstring"""






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

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

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

 def        a__				(       self      :						Tuple						)     ->			Any:

       """simple docstring"""






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

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

                   lowerCamelCase_	  =					CustomImageProcessor.from_pretrained(A_						)

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

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

       """simple docstring"""






       class 						A(		UpperCamelCase     ):



        '''simple docstring'''


        UpperCamelCase		     =		True

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

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






import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand

def     _SCREAMING_SNAKE_CASE    (							lowercase			: Optional[Any]  ):


      '''simple docstring'''



      return EnvironmentCommand()







class 						A(		UpperCamelCase     ):



 '''simple docstring'''


 @staticmethod
 def        a__				(       A_      :						ArgumentParser						)     ->			str:

       """simple docstring"""






       lowerCamelCase_	  =					parser.add_parser('env'						)
       download_parser.set_defaults(func=A_						)

 def        a__				(       self      :						Optional[Any]						)     ->			Any:

       """simple docstring"""






       lowerCamelCase_	  =					huggingface_hub.__version__

       lowerCamelCase_	  =					'not installed'
       lowerCamelCase_	  =					'NA'
       if is_torch_available():
             import torch

             lowerCamelCase_	  =					torch.__version__
             lowerCamelCase_	  =					torch.cuda.is_available()

       lowerCamelCase_	  =					'not installed'
       if is_transformers_available():
             import transformers

             lowerCamelCase_	  =					transformers.__version__

       lowerCamelCase_	  =					'not installed'
       if is_accelerate_available():
             import accelerate

             lowerCamelCase_	  =					accelerate.__version__

       lowerCamelCase_	  =					'not installed'
       if is_xformers_available():
             import xformers

             lowerCamelCase_	  =					xformers.__version__

       lowerCamelCase_	  =					{
           '`diffusers` version': version,
           'Platform': platform.platform(),
           'Python version': platform.python_version(),
           'PyTorch version (GPU?)': f"""{pt_version} ({pt_cuda_available})""",
           'Huggingface_hub version': hub_version,
           'Transformers version': transformers_version,
           'Accelerate version': accelerate_version,
           'xFormers version': xformers_version,
           'Using GPU in script?': '<fill in>',
           'Using distributed or parallel set-up in script?': '<fill in>',
       }

       print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'						)
       print(self.format_dict(A_						)						)

       return info





 @staticmethod
 def        a__				(       A_      :						Dict						)     ->			Any:

       """simple docstring"""






       return "\n".join([f"""- {prop}: {val}""" for prop, val in d.items()]						) + "\n"



