






'''simple docstring'''





import collections
import inspect
import unittest

from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
						from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor


class  snake_case__      :




					def __init__(  self  :		List[str]				, _A  :		List[str]				, _A  :		Optional[Any]=13				, _A  :		Any=32				, _A  :		Any=2				, _A  :		int=3				, _A  :		Tuple=16				, _A  :		int=[1, 2, 1]				, _A  :		Optional[Any]=[2, 2, 4]				, _A  :		int=2				, _A  :		Optional[int]=2.0				, _A  :		str=True				, _A  :		List[Any]=0.0				, _A  :		Union[str, Any]=0.0				, _A  :		List[str]=0.1				, _A  :		Any="gelu"				, _A  :		Any=False				, _A  :		Optional[int]=True				, _A  :		Optional[int]=0.02				, _A  :		List[str]=1e-5				, _A  :		List[Any]=True				, _A  :		str=None				, _A  :		Optional[Any]=True				, _A  :		str=10				, _A  :		List[str]=8				, )    ->							List[Any]:
								UpperCAmelCase_      :       Union[str, Any]          =       parent
								UpperCAmelCase_      :       int          =       batch_size
								UpperCAmelCase_      :       Union[str, Any]          =       image_size
								UpperCAmelCase_      :       str          =       patch_size
								UpperCAmelCase_      :       Dict          =       num_channels
								UpperCAmelCase_      :       List[str]          =       embed_dim
								UpperCAmelCase_      :       str          =       depths
								UpperCAmelCase_      :       Any          =       num_heads
								UpperCAmelCase_      :       Dict          =       window_size
								UpperCAmelCase_      :       Dict          =       mlp_ratio
								UpperCAmelCase_      :       str          =       qkv_bias
								UpperCAmelCase_      :       Any          =       hidden_dropout_prob
								UpperCAmelCase_      :       List[str]          =       attention_probs_dropout_prob
								UpperCAmelCase_      :       Union[str, Any]          =       drop_path_rate
								UpperCAmelCase_      :       Optional[int]          =       hidden_act
								UpperCAmelCase_      :       int          =       use_absolute_embeddings
								UpperCAmelCase_      :       str          =       patch_norm
								UpperCAmelCase_      :       List[str]          =       layer_norm_eps
								UpperCAmelCase_      :       Optional[Any]          =       initializer_range
								UpperCAmelCase_      :       List[Any]          =       is_training
								UpperCAmelCase_      :       List[Any]          =       scope
								UpperCAmelCase_      :       List[str]          =       use_labels
								UpperCAmelCase_      :       Tuple          =       type_sequence_label_size
								UpperCAmelCase_      :       List[Any]          =       encoder_stride




					def 		A      (  self  :		List[Any]      )    ->							Optional[Any]:
								UpperCAmelCase_      :       int          =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

								UpperCAmelCase_      :       Dict          =       None
								if self.use_labels:
											UpperCAmelCase_      :       Dict          =       ids_tensor([self.batch_size]				, self.type_sequence_label_size      )

								UpperCAmelCase_      :       List[str]          =       self.get_config()

								return config, pixel_values, labels




					def 		A      (  self  :		Tuple      )    ->							Union[str, Any]:
								return SwinvaConfig(
								    image_size=self.image_size				, patch_size=self.patch_size				, num_channels=self.num_channels				, embed_dim=self.embed_dim				, depths=self.depths				, num_heads=self.num_heads				, window_size=self.window_size				, mlp_ratio=self.mlp_ratio				, qkv_bias=self.qkv_bias				, hidden_dropout_prob=self.hidden_dropout_prob				, attention_probs_dropout_prob=self.attention_probs_dropout_prob				, drop_path_rate=self.drop_path_rate				, hidden_act=self.hidden_act				, use_absolute_embeddings=self.use_absolute_embeddings				, path_norm=self.patch_norm				, layer_norm_eps=self.layer_norm_eps				, initializer_range=self.initializer_range				, encoder_stride=self.encoder_stride				, )




					def 		A      (  self  :		List[Any]				, _A  :		Dict				, _A  :		str				, _A  :		Optional[int]      )    ->							List[str]:
								UpperCAmelCase_      :       Any          =       SwinvaModel(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       Union[str, Any]          =       model(_A      )

								UpperCAmelCase_      :       List[str]          =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
								UpperCAmelCase_      :       Tuple          =       int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

								self.parent.assertEqual(result.last_hidden_state.shape				, (self.batch_size, expected_seq_len, expected_dim)      )




					def 		A      (  self  :		List[Any]				, _A  :		Optional[int]				, _A  :		Optional[int]				, _A  :		int      )    ->							Union[str, Any]:
								UpperCAmelCase_      :       Optional[Any]          =       SwinvaForMaskedImageModeling(config=_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       List[str]          =       model(_A      )
								self.parent.assertEqual(
								    result.logits.shape				, (self.batch_size, self.num_channels, self.image_size, self.image_size)      )

								# test greyscale images
								UpperCAmelCase_      :       List[str]          =       1
								UpperCAmelCase_      :       Optional[int]          =       SwinvaForMaskedImageModeling(_A      )
								model.to(_A      )
								model.eval()

								UpperCAmelCase_      :       Any          =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
								UpperCAmelCase_      :       str          =       model(_A      )
								self.parent.assertEqual(result.logits.shape				, (self.batch_size, 1, self.image_size, self.image_size)      )




					def 		A      (  self  :		Union[str, Any]				, _A  :		Dict				, _A  :		Tuple				, _A  :		Dict      )    ->							Optional[Any]:
								UpperCAmelCase_      :       Optional[int]          =       self.type_sequence_label_size
								UpperCAmelCase_      :       str          =       SwinvaForImageClassification(_A      )
								model.to(_A      )
								model.eval()
								UpperCAmelCase_      :       List[Any]          =       model(_A				, labels=_A      )
								self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.type_sequence_label_size)      )





					def 		A      (  self  :		Optional[Any]      )    ->							str:
								UpperCAmelCase_      :       Optional[int]          =       self.prepare_config_and_inputs()
								UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       Any          =       config_and_inputs
								UpperCAmelCase_      :       str          =       {'''pixel_values''': pixel_values}
								return config, inputs_dict






@require_torch
class  snake_case__      (					UpperCamelCase     ,				UpperCamelCase     ,				unittest.TestCase):
					a_        =					(
					    (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
					)
					a_        =					(
					    {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification}
					    if is_torch_available()
					    else {}
					)

					a_        =					False
					a_        =					False
					a_        =					False
					a_        =					False




					def 		A      (  self  :		str      )    ->							Union[str, Any]:
								UpperCAmelCase_      :       List[Any]          =       SwinvaModelTester(self      )
								UpperCAmelCase_      :       Tuple          =       ConfigTester(self				, config_class=_A				, embed_dim=37      )




					def 		A      (  self  :		Optional[Any]      )    ->							Optional[int]:
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()




					def 		A      (  self  :		Tuple      )    ->							int:
								UpperCAmelCase_      :       Dict          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_A      )




					@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''      )
					def 		A      (  self  :		List[Any]      )    ->							Any:
								pass




					@unittest.skip(reason='''Swinv2 does not use inputs_embeds'''      )
					def 		A      (  self  :		Optional[int]      )    ->							str:
								pass




					def 		A      (  self  :		Any      )    ->							Optional[int]:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       Union[str, Any]          =       self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       str          =       model_class(_A      )
											self.assertIsInstance(model.get_input_embeddings()				, (nn.Module)      )
											UpperCAmelCase_      :       Tuple          =       model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(_A				, nn.Linear      )      )




					def 		A      (  self  :		Tuple      )    ->							List[Any]:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       Optional[int]          =       self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       Optional[Any]          =       model_class(_A      )
											UpperCAmelCase_      :       Any          =       inspect.signature(model.forward      )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											UpperCAmelCase_      :       Optional[Any]          =       [*signature.parameters.keys()]

											UpperCAmelCase_      :       Optional[Any]          =       ['''pixel_values''']
											self.assertListEqual(arg_names[:1]				, _A      )




					def 		A      (  self  :		Any      )    ->							List[str]:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       Any          =       self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase_      :       List[Any]          =       True

								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       List[Any]          =       True
											UpperCAmelCase_      :       Any          =       False
											UpperCAmelCase_      :       List[str]          =       True
											UpperCAmelCase_      :       List[Any]          =       model_class(_A      )
											model.to(_A      )
											model.eval()
											with torch.no_grad():
														UpperCAmelCase_      :       List[Any]          =       model(**self._prepare_for_class(_A				, _A      )      )
											UpperCAmelCase_      :       int          =       outputs.attentions
											UpperCAmelCase_      :       Any          =       len(self.model_tester.depths      )
											self.assertEqual(len(_A      )				, _A      )

											# check that output_attentions also work using config
											del inputs_dict["output_attentions"]
											UpperCAmelCase_      :       Dict          =       True
											UpperCAmelCase_      :       Optional[Any]          =       config.window_size**2
											UpperCAmelCase_      :       Tuple          =       model_class(_A      )
											model.to(_A      )
											model.eval()
											with torch.no_grad():
														UpperCAmelCase_      :       Any          =       model(**self._prepare_for_class(_A				, _A      )      )
											UpperCAmelCase_      :       List[Any]          =       outputs.attentions
											self.assertEqual(len(_A      )				, _A      )

											self.assertListEqual(
											    list(attentions[0].shape[-3:]      )				, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				, )
											UpperCAmelCase_      :       Union[str, Any]          =       len(_A      )

											# Check attention is always last and order is fine
											UpperCAmelCase_      :       str          =       True
											UpperCAmelCase_      :       Dict          =       True
											UpperCAmelCase_      :       Union[str, Any]          =       model_class(_A      )
											model.to(_A      )
											model.eval()
											with torch.no_grad():
														UpperCAmelCase_      :       str          =       model(**self._prepare_for_class(_A				, _A      )      )

											if hasattr(self.model_tester				, '''num_hidden_states_types'''      ):
														UpperCAmelCase_      :       List[Any]          =       self.model_tester.num_hidden_states_types
											else:
														# also another +1 for reshaped_hidden_states
														UpperCAmelCase_      :       Optional[int]          =       2
											self.assertEqual(out_len + added_hidden_states				, len(_A      )      )

											UpperCAmelCase_      :       Dict          =       outputs.attentions

											self.assertEqual(len(_A      )				, _A      )

											self.assertListEqual(
											    list(self_attentions[0].shape[-3:]      )				, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				, )




					def 		A      (  self  :		Any				, _A  :		int				, _A  :		Tuple				, _A  :		List[str]				, _A  :		Tuple      )    ->							List[Any]:
								UpperCAmelCase_      :       Any          =       model_class(_A      )
								model.to(_A      )
								model.eval()

								with torch.no_grad():
											UpperCAmelCase_      :       Optional[int]          =       model(**self._prepare_for_class(_A				, _A      )      )

								UpperCAmelCase_      :       List[str]          =       outputs.hidden_states

								UpperCAmelCase_      :       List[Any]          =       getattr(
								    self.model_tester				, '''expected_num_hidden_layers'''				, len(self.model_tester.depths      ) + 1      )
								self.assertEqual(len(_A      )				, _A      )

								# Swinv2 has a different seq_length
								UpperCAmelCase_      :       Any          =       (
								    config.patch_size
								    if isinstance(config.patch_size				, collections.abc.Iterable      )
								    else (config.patch_size, config.patch_size)
								)

								UpperCAmelCase_      :       List[str]          =       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]      )				, [num_patches, self.model_tester.embed_dim]				, )

								UpperCAmelCase_      :       Any          =       outputs.reshaped_hidden_states
								self.assertEqual(len(_A      )				, _A      )

								UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       Optional[Any]          =       reshaped_hidden_states[0].shape
								UpperCAmelCase_      :       Tuple          =       (
								    reshaped_hidden_states[0].view(_A				, _A				, height * width      ).permute(0				, 2				, 1      )
								)
								self.assertListEqual(
								    list(reshaped_hidden_states.shape[-2:]      )				, [num_patches, self.model_tester.embed_dim]				, )




					def 		A      (  self  :		Optional[Any]      )    ->							Dict:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       Tuple          =       self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase_      :       List[str]          =       (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size				, collections.abc.Iterable      )
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)

								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       Optional[int]          =       True
											self.check_hidden_states_output(_A				, _A				, _A				, _A      )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											UpperCAmelCase_      :       Optional[Any]          =       True

											self.check_hidden_states_output(_A				, _A				, _A				, _A      )




					def 		A      (  self  :		Optional[int]      )    ->							int:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       Union[str, Any]          =       self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase_      :       Optional[Any]          =       3

								UpperCAmelCase_      :       Dict          =       (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size				, collections.abc.Iterable      )
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)
								UpperCAmelCase_      :       Union[str, Any]          =       (
								    config.patch_size
								    if isinstance(config.patch_size				, collections.abc.Iterable      )
								    else (config.patch_size, config.patch_size)
								)

								UpperCAmelCase_      :       Dict          =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								UpperCAmelCase_      :       int          =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       Optional[Any]          =       True
											self.check_hidden_states_output(_A				, _A				, _A				, (padded_height, padded_width)      )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											UpperCAmelCase_      :       str          =       True
											self.check_hidden_states_output(_A				, _A				, _A				, (padded_height, padded_width)      )




					def 		A      (  self  :		Union[str, Any]      )    ->							Dict:
								UpperCAmelCase_      :       Dict          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*_A      )




					def 		A      (  self  :		Optional[int]      )    ->							int:
								UpperCAmelCase_      :       Union[str, Any]          =       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*_A      )




					@slow
					def 		A      (  self  :		str      )    ->							List[str]:
								for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCAmelCase_      :       Tuple          =       SwinvaModel.from_pretrained(_A      )
											self.assertIsNotNone(_A      )





					def 		A      (  self  :		List[str]      )    ->							Any:
								UpperCAmelCase_    ,      UpperCAmelCase_      :       List[Any]          =       self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase_      :       Optional[Any]          =       _config_zero_init(_A      )
								for model_class in self.all_model_classes:
											UpperCAmelCase_      :       Optional[int]          =       model_class(config=_A      )
											for name, param in model.named_parameters():
														if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
																	self.assertIn(
																	    ((param.data.mean() * 1e9).round() / 1e9).item()				, [0.0, 1.0]				, msg=F"Parameter {name} of model {model_class} seems not properly initialized"				, )






@require_vision
@require_torch
class  snake_case__      (					unittest.TestCase):




					@cached_property
					def 		A      (  self  :		Optional[Any]      )    ->							Any:
								return (
								    AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''      )
								    if is_vision_available()
								    else None
								)





					@slow
					def 		A      (  self  :		Tuple      )    ->							Tuple:
								UpperCAmelCase_      :       Dict          =       SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''      ).to(
								    _A      )
								UpperCAmelCase_      :       Optional[int]          =       self.default_image_processor

								UpperCAmelCase_      :       str          =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
								UpperCAmelCase_      :       Tuple          =       image_processor(images=_A				, return_tensors='''pt'''      ).to(_A      )

								# forward pass
								with torch.no_grad():
											UpperCAmelCase_      :       List[Any]          =       model(**_A      )

								# verify the logits
								UpperCAmelCase_      :       Any          =       torch.Size((1, 10_00)      )
								self.assertEqual(outputs.logits.shape				, _A      )
								UpperCAmelCase_      :       Tuple          =       torch.tensor([-0.3_947, -0.4_306, 0.0_026]      ).to(_A      )
								self.assertTrue(torch.allclose(outputs.logits[0, :3]				, _A				, atol=1e-4      )      )










'''simple docstring'''





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


_UpperCamelCase						:						Union[str, Any]  =					(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


_UpperCamelCase						:						Optional[int]  =					logging.get_logger(__name__)  # pylint: disable=invalid-name
def __UpperCAmelCase   (					)    ->   List[str]:
			UpperCAmelCase_      :       int          =       '''https://pypi.org/pypi/diffusers/json'''
			UpperCAmelCase_      :       List[str]          =       json.loads(request.urlopen(A		).read()		)['''releases'''].keys()
			return sorted(A			,       key=lambda A		: version.Version(A		)		)
def __UpperCAmelCase   (					)    ->   List[Any]:
			# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
			if HF_MODULES_CACHE in sys.path:
						return

			sys.path.append(A		)
			os.makedirs(A			,       exist_ok=A		)
			UpperCAmelCase_      :       Tuple          =       Path(A		) / '''__init__.py'''
			if not init_path.exists():
						init_path.touch()
def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]		)    ->   str:
			init_hf_modules()
			UpperCAmelCase_      :       Any          =       Path(A		) / 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(A			,       exist_ok=A		)
			UpperCAmelCase_      :       str          =       dynamic_module_path / '''__init__.py'''
			if not init_path.exists():
						init_path.touch()
def __UpperCAmelCase   (					A					:			Dict		)    ->   Optional[int]:
			with open(A			,       '''r'''			,       encoding='''utf-8'''		) as f:
						UpperCAmelCase_      :       List[Any]          =       f.read()

			# Imports of the form `import .xxx`
			UpperCAmelCase_      :       Any          =       re.findall('''^\s*import\s+\.(\S+)\s*$'''			,       A			,       flags=re.MULTILINE		)
			# Imports of the form `from .xxx import yyy`
			relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''			,       A			,       flags=re.MULTILINE		)
			# Unique-ify
			return list(set(A		)		)
def __UpperCAmelCase   (					A					:			Tuple		)    ->   List[str]:
			UpperCAmelCase_      :       Dict          =       False
			UpperCAmelCase_      :       List[str]          =       [module_file]
			UpperCAmelCase_      :       str          =       []

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

						UpperCAmelCase_      :       Tuple          =       Path(A		).parent
						UpperCAmelCase_      :       Union[str, Any]          =       [str(module_path / m		) for m in new_imports]
						UpperCAmelCase_      :       str          =       [f for f in new_import_files if f not in all_relative_imports]
						UpperCAmelCase_      :       str          =       [F"{f}.py" for f in new_import_files]

						UpperCAmelCase_      :       Optional[int]          =       len(A		) == 0
						all_relative_imports.extend(A		)

			return all_relative_imports
def __UpperCAmelCase   (					A					:			List[str]		)    ->   Union[str, Any]:
			with open(A			,       '''r'''			,       encoding='''utf-8'''		) as f:
						UpperCAmelCase_      :       List[str]          =       f.read()

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

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

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

			return get_relative_imports(A		)
def __UpperCAmelCase   (					A					:			Optional[Any]			,       A					:			Optional[int]		)    ->   Union[str, Any]:
			UpperCAmelCase_      :       int          =       module_path.replace(os.path.sep			,       '''.'''		)
			UpperCAmelCase_      :       int          =       importlib.import_module(A		)

			if class_name is None:
						return find_pipeline_class(A		)
			return getattr(A			,       A		)
def __UpperCAmelCase   (					A					:			str		)    ->   List[str]:
			from ..pipelines import DiffusionPipeline

			UpperCAmelCase_      :       List[Any]          =       dict(inspect.getmembers(A			,       inspect.isclass		)		)

			UpperCAmelCase_      :       Optional[int]          =       None
			for cls_name, cls in cls_members.items():
						if (
						    cls_name != DiffusionPipeline.__name__
						    and issubclass(cls			,       A		)
						    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}."		)
									UpperCAmelCase_      :       int          =       cls

			return pipeline_class
def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]			,       A					:			str			,       A					:			Optional[Union[str, os.PathLike]] = None			,       A					:			bool = False			,       A					:			bool = False			,       A					:			Optional[Dict[str, str]] = None			,       A					:			Optional[Union[bool, str]] = None			,       A					:			Optional[str] = None			,       A					:			bool = False			,       )    ->   str:
			UpperCAmelCase_      :       Any          =       str(A		)

			UpperCAmelCase_      :       List[Any]          =       os.path.join(A			,       A		)

			if os.path.isfile(A		):
						UpperCAmelCase_      :       Optional[Any]          =       module_file_or_url
						UpperCAmelCase_      :       List[str]          =       '''local'''
			elif pretrained_model_name_or_path.count('''/'''		) == 0:
						UpperCAmelCase_      :       List[str]          =       get_diffusers_versions()
						# cut ".dev0"
						UpperCAmelCase_      :       Dict          =       '''v''' + '''.'''.join(__version__.split('''.'''		)[:3]		)

						# retrieve github version that matches
						if revision is None:
									UpperCAmelCase_      :       List[str]          =       latest_version if latest_version[1:] in available_versions else '''main'''
									logger.info(F"Defaulting to latest_version: {revision}."		)
						elif revision in available_versions:
									UpperCAmelCase_      :       List[str]          =       F"v{revision}"
						elif revision == "main":
									UpperCAmelCase_      :       Dict          =       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
						UpperCAmelCase_      :       Tuple          =       COMMUNITY_PIPELINES_URL.format(revision=A			,       pipeline=A		)
						try:
									UpperCAmelCase_      :       List[Any]          =       cached_download(
									    A			,       cache_dir=A			,       force_download=A			,       proxies=A			,       resume_download=A			,       local_files_only=A			,       use_auth_token=A			,       )
									UpperCAmelCase_      :       List[str]          =       '''git'''
									UpperCAmelCase_      :       Union[str, Any]          =       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
									UpperCAmelCase_      :       List[str]          =       hf_hub_download(
									    A			,       A			,       cache_dir=A			,       force_download=A			,       proxies=A			,       resume_download=A			,       local_files_only=A			,       use_auth_token=A			,       )
									UpperCAmelCase_      :       Tuple          =       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
			UpperCAmelCase_      :       Any          =       check_imports(A		)

			# Now we move the module inside our cached dynamic modules.
			UpperCAmelCase_      :       List[str]          =       DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
			create_dynamic_module(A		)
			UpperCAmelCase_      :       Optional[Any]          =       Path(A		) / 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(A			,       submodule_path / module_file		)
						for module_needed in modules_needed:
									UpperCAmelCase_      :       int          =       F"{module_needed}.py"
									shutil.copy(os.path.join(A			,       A		)			,       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(A			,       A		):
									UpperCAmelCase_      :       Tuple          =       use_auth_token
						elif use_auth_token is True:
									UpperCAmelCase_      :       Tuple          =       HfFolder.get_token()
						else:
									UpperCAmelCase_      :       str          =       None

						UpperCAmelCase_      :       List[Any]          =       model_info(A			,       revision=A			,       token=A		).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.
						UpperCAmelCase_      :       Optional[Any]          =       submodule_path / commit_hash
						UpperCAmelCase_      :       str          =       full_submodule + os.path.sep + commit_hash
						create_dynamic_module(A		)

						if not (submodule_path / module_file).exists():
									shutil.copy(A			,       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(
												    A			,       F"{module_needed}.py"			,       cache_dir=A			,       force_download=A			,       resume_download=A			,       proxies=A			,       use_auth_token=A			,       revision=A			,       local_files_only=A			,       )
			return os.path.join(A			,       A		)







def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]			,       A					:			str			,       A					:			Optional[str] = None			,       A					:			Optional[Union[str, os.PathLike]] = None			,       A					:			bool = False			,       A					:			bool = False			,       A					:			Optional[Dict[str, str]] = None			,       A					:			Optional[Union[bool, str]] = None			,       A					:			Optional[str] = None			,       A					:			bool = False			,       **A					:			Optional[int]			,       )    ->   Optional[Any]:
			UpperCAmelCase_      :       Tuple          =       get_cached_module_file(
			    A			,       A			,       cache_dir=A			,       force_download=A			,       resume_download=A			,       proxies=A			,       use_auth_token=A			,       revision=A			,       local_files_only=A			,       )
			return get_class_in_module(A			,       final_module.replace('''.py'''			,       ''''''		)		)


