


import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


lowerCAmelCase	=							(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


lowerCAmelCase	=							logging.get_logger(__name__)  # pylint: disable=invalid-name
def       _a			(				):


		"""simple docstring"""




		lowercase__						=				'''https://pypi.org/pypi/diffusers/json'''
		lowercase__						=				json.loads(request.urlopen(SCREAMING_SNAKE_CASE					).read()					)['''releases'''].keys()
		return sorted(SCREAMING_SNAKE_CASE						,    key=lambda SCREAMING_SNAKE_CASE					: version.Version(SCREAMING_SNAKE_CASE					)					)
def       _a			(				):


		"""simple docstring"""




		if HF_MODULES_CACHE in sys.path:
				return

		sys.path.append(SCREAMING_SNAKE_CASE					)
		os.makedirs(SCREAMING_SNAKE_CASE						,    exist_ok=SCREAMING_SNAKE_CASE					)
		lowercase__						=				Path(SCREAMING_SNAKE_CASE					) / '''__init__.py'''
		if not init_path.exists():
				init_path.touch()
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		init_hf_modules()
		lowercase__						=				Path(SCREAMING_SNAKE_CASE					) / name
		# If the parent module does not exist yet, recursively create it.
		if not dynamic_module_path.parent.exists():
				create_dynamic_module(dynamic_module_path.parent					)
		os.makedirs(SCREAMING_SNAKE_CASE						,    exist_ok=SCREAMING_SNAKE_CASE					)
		lowercase__						=				dynamic_module_path / '''__init__.py'''
		if not init_path.exists():
				init_path.touch()
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		with open(SCREAMING_SNAKE_CASE						,    '''r'''						,    encoding='''utf-8'''					) as f:
				lowercase__						=				f.read()

		# Imports of the form `import .xxx`
		lowercase__						=				re.findall('''^\s*import\s+\.(\S+)\s*$'''						,    SCREAMING_SNAKE_CASE						,    flags=re.MULTILINE					)
		# Imports of the form `from .xxx import yyy`
		relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''						,    SCREAMING_SNAKE_CASE						,    flags=re.MULTILINE					)
		# Unique-ify
		return list(set(SCREAMING_SNAKE_CASE					)					)
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		lowercase__						=				False
		lowercase__						=				[module_file]
		lowercase__						=				[]

		# Let's recurse through all relative imports
		while not no_change:
				lowercase__						=				[]
				for f in files_to_check:
						new_imports.extend(get_relative_imports(SCREAMING_SNAKE_CASE					)					)

				lowercase__						=				Path(SCREAMING_SNAKE_CASE					).parent
				lowercase__						=				[str(module_path / m					) for m in new_imports]
				lowercase__						=				[f for f in new_import_files if f not in all_relative_imports]
				lowercase__						=				[f'{f}.py' for f in new_import_files]

				lowercase__						=				len(SCREAMING_SNAKE_CASE					) == 0
				all_relative_imports.extend(SCREAMING_SNAKE_CASE					)

		return all_relative_imports
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		with open(SCREAMING_SNAKE_CASE						,    '''r'''						,    encoding='''utf-8'''					) as f:
				lowercase__						=				f.read()

		# Imports of the form `import xxx`
		lowercase__						=				re.findall('''^\s*import\s+(\S+)\s*$'''						,    SCREAMING_SNAKE_CASE						,    flags=re.MULTILINE					)
		# Imports of the form `from xxx import yyy`
		imports += re.findall('''^\s*from\s+(\S+)\s+import'''						,    SCREAMING_SNAKE_CASE						,    flags=re.MULTILINE					)
		# Only keep the top-level module
		lowercase__						=				[imp.split('''.'''					)[0] for imp in imports if not imp.startswith('''.'''					)]

		# Unique-ify and test we got them all
		lowercase__						=				list(set(SCREAMING_SNAKE_CASE					)					)
		lowercase__						=				[]
		for imp in imports:
				try:
						importlib.import_module(SCREAMING_SNAKE_CASE					)
				except ImportError:
						missing_packages.append(SCREAMING_SNAKE_CASE					)

		if len(SCREAMING_SNAKE_CASE					) > 0:
				raise ImportError(
				    '''This modeling file requires the following packages that were not found in your environment: '''
				    f'{", ".join(SCREAMING_SNAKE_CASE					)}. Run `pip install {" ".join(SCREAMING_SNAKE_CASE					)}`'					)

		return get_relative_imports(SCREAMING_SNAKE_CASE					)
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		lowercase__						=				module_path.replace(os.path.sep						,    '''.'''					)
		lowercase__						=				importlib.import_module(SCREAMING_SNAKE_CASE					)

		if class_name is None:
				return find_pipeline_class(SCREAMING_SNAKE_CASE					)
		return getattr(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		from ..pipelines import DiffusionPipeline

		lowercase__						=				dict(inspect.getmembers(SCREAMING_SNAKE_CASE						,    inspect.isclass					)					)

		lowercase__						=				None
		for cls_name, cls in cls_members.items():
				if (
				    cls_name != DiffusionPipeline.__name__
				    and issubclass(cls						,    SCREAMING_SNAKE_CASE					)
				    and cls.__module__.split('''.'''					)[0] != "diffusers"
				):
						if pipeline_class is not None:
								raise ValueError(
								    f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:'
								    f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in'
								    f' {loaded_module}.'					)
						lowercase__						=				cls

		return pipeline_class
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    ):


		"""simple docstring"""




		lowercase__						=				str(SCREAMING_SNAKE_CASE					)

		lowercase__						=				os.path.join(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)

		if os.path.isfile(SCREAMING_SNAKE_CASE					):
				lowercase__						=				module_file_or_url
				lowercase__						=				'''local'''
		elif pretrained_model_name_or_path.count('''/'''					) == 0:
				lowercase__						=				get_diffusers_versions()
				# cut ".dev0"
				lowercase__						=				'''v''' + '''.'''.join(__version__.split('''.'''					)[:3]					)

				# retrieve github version that matches
				if revision is None:
						lowercase__						=				latest_version if latest_version[1:] in available_versions else '''main'''
						logger.info(f'Defaulting to latest_version: {revision}.'					)
				elif revision in available_versions:
						lowercase__						=				f'v{revision}'
				elif revision == "main":
						lowercase__						=				revision
				else:
						raise ValueError(
						    f'`custom_revision`: {revision} does not exist. Please make sure to choose one of'
						    f' {", ".join(available_versions + ["main"]					)}.'					)

				# community pipeline on GitHub
				lowercase__						=				COMMUNITY_PIPELINES_URL.format(revision=SCREAMING_SNAKE_CASE						,    pipeline=SCREAMING_SNAKE_CASE					)
				try:
						lowercase__						=				cached_download(
						    SCREAMING_SNAKE_CASE						,    cache_dir=SCREAMING_SNAKE_CASE						,    force_download=SCREAMING_SNAKE_CASE						,    proxies=SCREAMING_SNAKE_CASE						,    resume_download=SCREAMING_SNAKE_CASE						,    local_files_only=SCREAMING_SNAKE_CASE						,    use_auth_token=SCREAMING_SNAKE_CASE						,    )
						lowercase__						=				'''git'''
						lowercase__						=				pretrained_model_name_or_path + '''.py'''
				except EnvironmentError:
						logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.'					)
						raise
		else:
				try:
						# Load from URL or cache if already cached
						lowercase__						=				hf_hub_download(
						    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    cache_dir=SCREAMING_SNAKE_CASE						,    force_download=SCREAMING_SNAKE_CASE						,    proxies=SCREAMING_SNAKE_CASE						,    resume_download=SCREAMING_SNAKE_CASE						,    local_files_only=SCREAMING_SNAKE_CASE						,    use_auth_token=SCREAMING_SNAKE_CASE						,    )
						lowercase__						=				os.path.join('''local'''						,    '''--'''.join(pretrained_model_name_or_path.split('''/'''					)					)					)
				except EnvironmentError:
						logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.'					)
						raise

    # Check we have all the requirements in our environment
		lowercase__						=				check_imports(SCREAMING_SNAKE_CASE					)

		# Now we move the module inside our cached dynamic modules.
		lowercase__						=				DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
		create_dynamic_module(SCREAMING_SNAKE_CASE					)
		lowercase__						=				Path(SCREAMING_SNAKE_CASE					) / full_submodule
		if submodule == "local" or submodule == "git":
				# We always copy local files (we could hash the file to see if there was a change, and give them the name of
				# that hash, to only copy when there is a modification but it seems overkill for now).
				# The only reason we do the copy is to avoid putting too many folders in sys.path.
				shutil.copy(SCREAMING_SNAKE_CASE						,    submodule_path / module_file					)
				for module_needed in modules_needed:
						lowercase__						=				f'{module_needed}.py'
						shutil.copy(os.path.join(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)						,    submodule_path / module_needed					)
		else:
				# Get the commit hash
				# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
				if isinstance(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					):
						lowercase__						=				use_auth_token
				elif use_auth_token is True:
						lowercase__						=				HfFolder.get_token()
				else:
						lowercase__						=				None

				lowercase__						=				model_info(SCREAMING_SNAKE_CASE						,    revision=SCREAMING_SNAKE_CASE						,    token=SCREAMING_SNAKE_CASE					).sha

				# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
				# benefit of versioning.
				lowercase__						=				submodule_path / commit_hash
				lowercase__						=				full_submodule + os.path.sep + commit_hash
				create_dynamic_module(SCREAMING_SNAKE_CASE					)

				if not (submodule_path / module_file).exists():
						shutil.copy(SCREAMING_SNAKE_CASE						,    submodule_path / module_file					)
				# Make sure we also have every file with relative
				for module_needed in modules_needed:
						if not (submodule_path / module_needed).exists():
								get_cached_module_file(
								    SCREAMING_SNAKE_CASE						,    f'{module_needed}.py'						,    cache_dir=SCREAMING_SNAKE_CASE						,    force_download=SCREAMING_SNAKE_CASE						,    resume_download=SCREAMING_SNAKE_CASE						,    proxies=SCREAMING_SNAKE_CASE						,    use_auth_token=SCREAMING_SNAKE_CASE						,    revision=SCREAMING_SNAKE_CASE						,    local_files_only=SCREAMING_SNAKE_CASE						,    )
		return os.path.join(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    **SCREAMING_SNAKE_CASE						,    ):


		"""simple docstring"""




		lowercase__						=				get_cached_module_file(
		    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    cache_dir=SCREAMING_SNAKE_CASE						,    force_download=SCREAMING_SNAKE_CASE						,    resume_download=SCREAMING_SNAKE_CASE						,    proxies=SCREAMING_SNAKE_CASE						,    use_auth_token=SCREAMING_SNAKE_CASE						,    revision=SCREAMING_SNAKE_CASE						,    local_files_only=SCREAMING_SNAKE_CASE						,    )
		return get_class_in_module(SCREAMING_SNAKE_CASE						,    final_module.replace('''.py'''						,    ''''''					)					)






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase	=							logging.get_logger(__name__)

lowerCAmelCase	=							{
    'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json',
}


class 	_a							(      UpperCamelCase__      ):
							_lowercase     :      int  				=			'''git_vision_model'''

							def __init__(							self:     Tuple   ,						UpperCamelCase_:     Optional[int]=768   ,						UpperCamelCase_:     Optional[int]=3_072   ,						UpperCamelCase_:     Optional[int]=12   ,						UpperCamelCase_:     Union[str, Any]=12   ,						UpperCamelCase_:     Any=3   ,						UpperCamelCase_:     str=224   ,						UpperCamelCase_:     int=16   ,						UpperCamelCase_:     Any="quick_gelu"   ,						UpperCamelCase_:     Union[str, Any]=1E-5   ,						UpperCamelCase_:     Tuple=0.0   ,						UpperCamelCase_:     Tuple=0.02   ,						**UpperCamelCase_:     str   ,						)      ->       Optional[int]:





									"""simple docstring"""







									super().__init__(**UpperCamelCase_							)

									lowercase__						=				hidden_size
									lowercase__						=				intermediate_size
									lowercase__						=				num_hidden_layers
									lowercase__						=				num_attention_heads
									lowercase__						=				num_channels
									lowercase__						=				patch_size
									lowercase__						=				image_size
									lowercase__						=				initializer_range
									lowercase__						=				attention_dropout
									lowercase__						=				layer_norm_eps
									lowercase__						=				hidden_act


							@classmethod
							def 				lowerCamelCase_			(							cls:     Optional[Any]   ,						UpperCamelCase_:     Union[str, os.PathLike]   ,						**UpperCamelCase_:     List[Any]							)      ->       "PretrainedConfig":





									"""simple docstring"""







									cls._set_token_in_kwargs(UpperCamelCase_							)

									lowercase__					,		lowercase__						=				cls.get_config_dict(UpperCamelCase_   ,						**UpperCamelCase_							)

									# get the vision config dict if we are loading from GITConfig
									if config_dict.get('''model_type'''							) == "git":
											lowercase__						=				config_dict['''vision_config''']

									if "model_type" in config_dict and hasattr(cls   ,						'''model_type'''							) and config_dict["model_type"] != cls.model_type:
											logger.warning(
											    f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
											    f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'							)

									return cls.from_dict(UpperCamelCase_   ,						**UpperCamelCase_							)


class 	_a							(      UpperCamelCase__      ):
							_lowercase     :      Optional[int]  				=			'''git'''

							def __init__(							self:     Optional[Any]   ,						UpperCamelCase_:     Optional[Any]=None   ,						UpperCamelCase_:     List[str]=30_522   ,						UpperCamelCase_:     List[Any]=768   ,						UpperCamelCase_:     List[Any]=6   ,						UpperCamelCase_:     Union[str, Any]=12   ,						UpperCamelCase_:     Any=3_072   ,						UpperCamelCase_:     Any="gelu"   ,						UpperCamelCase_:     List[Any]=0.1   ,						UpperCamelCase_:     Dict=0.1   ,						UpperCamelCase_:     str=1_024   ,						UpperCamelCase_:     Any=0.02   ,						UpperCamelCase_:     str=1E-1_2   ,						UpperCamelCase_:     Optional[int]=0   ,						UpperCamelCase_:     Optional[Any]="absolute"   ,						UpperCamelCase_:     Optional[int]=True   ,						UpperCamelCase_:     List[Any]=False   ,						UpperCamelCase_:     List[Any]=101   ,						UpperCamelCase_:     int=102   ,						UpperCamelCase_:     List[str]=None   ,						**UpperCamelCase_:     int   ,						)      ->       Union[str, Any]:





									"""simple docstring"""







									super().__init__(bos_token_id=UpperCamelCase_   ,						eos_token_id=UpperCamelCase_   ,						pad_token_id=UpperCamelCase_   ,						**UpperCamelCase_							)

									if vision_config is None:
											lowercase__						=				{}
											logger.info('''vision_config is None. initializing the GitVisionConfig with default values.'''							)

									lowercase__						=				GitVisionConfig(**UpperCamelCase_							)
									lowercase__						=				vocab_size
									lowercase__						=				hidden_size
									lowercase__						=				num_hidden_layers
									lowercase__						=				num_attention_heads
									lowercase__						=				hidden_act
									lowercase__						=				intermediate_size
									lowercase__						=				hidden_dropout_prob
									lowercase__						=				attention_probs_dropout_prob
									lowercase__						=				max_position_embeddings
									lowercase__						=				initializer_range
									lowercase__						=				layer_norm_eps
									lowercase__						=				position_embedding_type
									lowercase__						=				use_cache
									lowercase__						=				tie_word_embeddings
									lowercase__						=				num_image_with_embedding

									lowercase__						=				bos_token_id
									lowercase__						=				eos_token_id


							def 				lowerCamelCase_			(							self:     Dict							)      ->       Tuple:





									"""simple docstring"""







									lowercase__						=				copy.deepcopy(self.__dict__							)
									lowercase__						=				self.vision_config.to_dict()
									lowercase__						=				self.__class__.model_type
									return output


