



"""simple docstring"""







import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
		import torch

		UpperCAmelCase:  str			     =				True
except ImportError:
		UpperCAmelCase:  str			     =				False


try:
		from torch.hub import _get_torch_home

		UpperCAmelCase:  Tuple			     =				_get_torch_home()
except ImportError:
		UpperCAmelCase:  Union[str, Any]			     =				os.path.expanduser(
		    os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
		)

UpperCAmelCase:  Any			     =				os.path.join(torch_cache_home, """transformers""")

UpperCAmelCase:  str			     =				"""https://cdn.huggingface.co"""
UpperCAmelCase:  Optional[int]			     =				"""https://s3.amazonaws.com/models.huggingface.co/bert"""
UpperCAmelCase:  Tuple			     =				"""/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
UpperCAmelCase:  List[Any]			     =				os.path.join(PATH, """config.yaml""")
UpperCAmelCase:  Optional[Any]			     =				os.path.join(PATH, """attributes.txt""")
UpperCAmelCase:  Dict			     =				os.path.join(PATH, """objects.txt""")
UpperCAmelCase:  int			     =				os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
UpperCAmelCase:  str			     =				os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
UpperCAmelCase:  Optional[Any]			     =				os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
UpperCAmelCase:  Optional[Any]			     =				"""pytorch_model.bin"""
UpperCAmelCase:  Union[str, Any]			     =				"""config.yaml"""


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase=OBJECTS   ,				__UpperCAmelCase=ATTRIBUTES      ):
		_lowercase				: Union[str, Any]     =   []
		with open(__UpperCAmelCase      ) as f:
				for object in f.readlines():
						vg_classes.append(object.split(""","""      )[0].lower().strip()      )

		_lowercase				: Tuple     =   []
		with open(__UpperCAmelCase      ) as f:
				for object in f.readlines():
						vg_attrs.append(object.split(""","""      )[0].lower().strip()      )
		return vg_classes, vg_attrs


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		_lowercase				: Optional[Any]     =   OrderedDict()
		with open(__UpperCAmelCase   ,				"""rb"""      ) as f:
				_lowercase				: str     =   pkl.load(__UpperCAmelCase      )["""model"""]
		for k in copy.deepcopy(list(ckp.keys()      )      ):
				_lowercase				: Dict     =   ckp.pop(__UpperCAmelCase      )
				if isinstance(__UpperCAmelCase   ,				np.ndarray      ):
						_lowercase				: str     =   torch.tensor(__UpperCAmelCase      )
				else:
						assert isinstance(__UpperCAmelCase   ,				torch.tensor      ), type(__UpperCAmelCase      )
				_lowercase				: Union[str, Any]     =   v
		return r





class   UpperCamelCase	:




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_							:       Optional[int]						       =  {}






	def __init__(     self				,UpperCAmelCase_				,UpperCAmelCase_ = "root"				,UpperCAmelCase_=0   ):
			_lowercase				: Optional[Any]     =   name
			_lowercase				: int     =   level
			_lowercase				: Union[str, Any]     =   {}
			for k, v in dictionary.items():
					if v is None:
							raise ValueError()
					_lowercase				: List[Any]     =   copy.deepcopy(UpperCAmelCase_   )
					_lowercase				: List[Any]     =   copy.deepcopy(UpperCAmelCase_   )
					if isinstance(UpperCAmelCase_				,UpperCAmelCase_   ):
							_lowercase				: Optional[Any]     =   Config(UpperCAmelCase_				,name=UpperCAmelCase_				,level=level + 1   )
					_lowercase				: List[str]     =   v
					setattr(self				,UpperCAmelCase_				,UpperCAmelCase_   )

			_lowercase				: Union[str, Any]     =   d






	def __repr__(     self   ):
			return str(list((self._pointer.keys())   )   )






	def __setattr__(     self				,UpperCAmelCase_				,UpperCAmelCase_   ):
			_lowercase				: List[str]     =   val
			_lowercase				: Optional[Any]     =   val
			_lowercase				: Optional[int]     =   key.split("""."""   )
			_lowercase				: int     =   len(UpperCAmelCase_   ) - 1
			_lowercase				: List[Any]     =   self._pointer
			if len(UpperCAmelCase_   ) > 1:
					for i, l in enumerate(UpperCAmelCase_   ):
							if hasattr(self				,UpperCAmelCase_   ) and isinstance(getattr(self				,UpperCAmelCase_   )				,UpperCAmelCase_   ):
									setattr(getattr(self				,UpperCAmelCase_   )				,""".""".join(levels[i:]   )				,UpperCAmelCase_   )
							if l == last_level:
									_lowercase				: Tuple     =   val
							else:
									_lowercase				: List[Any]     =   pointer[l]






	def    lowerCamelCase__					(     self   ):
			return self._pointer






	def    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_   ):
			with open(f"""{file_name}"""				,"""w"""   ) as stream:
					dump(UpperCAmelCase_				,UpperCAmelCase_   )






	def    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_   ):
			with open(f"""{file_name}"""				,"""w"""   ) as stream:
					json.dump(UpperCAmelCase_				,UpperCAmelCase_   )






	@staticmethod
	def    lowerCamelCase__					(     UpperCAmelCase_   ):
			with open(UpperCAmelCase_   ) as stream:
					_lowercase				: Union[str, Any]     =   load(UpperCAmelCase_				,Loader=UpperCAmelCase_   )
			return data






	def __str__(     self   ):
			_lowercase				: str     =   """    """
			if self._name != "root":
					_lowercase				: List[Any]     =   f"""{t * (self._level-1)}{self._name}:\n"""
			else:
					_lowercase				: Any     =   """"""
			_lowercase				: List[Any]     =   self._level
			for i, (k, v) in enumerate(self._pointer.items()   ):
					if isinstance(UpperCAmelCase_				,UpperCAmelCase_   ):
							r += f"""{t * (self._level)}{v}\n"""
							self._level += 1
					else:
							r += f"""{t * (self._level)}{k}: {v} ({type(UpperCAmelCase_   ).__name__})\n"""
					_lowercase				: Optional[Any]     =   level
			return r[:-1]






	@classmethod
	def    lowerCamelCase__					(     cls				,UpperCAmelCase_				,**UpperCAmelCase_   ):
			_lowercase     ,  _lowercase				: Union[str, Any]     =   cls.get_config_dict(UpperCAmelCase_				,**UpperCAmelCase_   )
			return cls(UpperCAmelCase_   )






	@classmethod
	def    lowerCamelCase__					(     cls				,UpperCAmelCase_				,**UpperCAmelCase_   ):
			_lowercase				: Optional[Any]     =   kwargs.pop("""cache_dir"""				,UpperCAmelCase_   )
			_lowercase				: int     =   kwargs.pop("""force_download"""				,UpperCAmelCase_   )
			_lowercase				: List[str]     =   kwargs.pop("""resume_download"""				,UpperCAmelCase_   )
			_lowercase				: Any     =   kwargs.pop("""proxies"""				,UpperCAmelCase_   )
			_lowercase				: List[Any]     =   kwargs.pop("""local_files_only"""				,UpperCAmelCase_   )

			if os.path.isdir(UpperCAmelCase_   ):
					_lowercase				: List[Any]     =   os.path.join(UpperCAmelCase_				,UpperCAmelCase_   )
			elif os.path.isfile(UpperCAmelCase_   ) or is_remote_url(UpperCAmelCase_   ):
					_lowercase				: Optional[Any]     =   pretrained_model_name_or_path
			else:
					_lowercase				: List[Any]     =   hf_bucket_url(UpperCAmelCase_				,filename=UpperCAmelCase_				,use_cdn=UpperCAmelCase_   )

			try:
					# Load from URL or cache if already cached
					_lowercase				: int     =   cached_path(
					    UpperCAmelCase_				,cache_dir=UpperCAmelCase_				,force_download=UpperCAmelCase_				,proxies=UpperCAmelCase_				,resume_download=UpperCAmelCase_				,local_files_only=UpperCAmelCase_				,)
					# Load config dict
					if resolved_config_file is None:
							raise EnvironmentError

					_lowercase				: Union[str, Any]     =   Config.load_yaml(UpperCAmelCase_   )

			except EnvironmentError:
					_lowercase				: Optional[int]     =   """Can't load config for"""
					raise EnvironmentError(UpperCAmelCase_   )

			if resolved_config_file == config_file:
					print("""loading configuration file from path"""   )
			else:
					print("""loading configuration file cache"""   )

			return Config.load_yaml(UpperCAmelCase_   ), kwargs







def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		_lowercase				: Optional[Any]     =   torch.load("""dump.pt"""   ,				map_location=in_tensor.device      )
		_lowercase				: Optional[int]     =   in_tensor.numpy()
		_lowercase				: Dict     =   out_tensor.numpy()[0]
		print(na.shape   ,				na[0, 0, :5]      )
		print(na.shape   ,				na[0, 0, :5]      )
		assert np.allclose(__UpperCAmelCase   ,				__UpperCAmelCase   ,				rtol=0.0_1   ,				atol=0.1      ), (
		    F"""{sum([1 for x in np.isclose(__UpperCAmelCase   ,				__UpperCAmelCase   ,				rtol=0.0_1   ,				atol=0.1      ).flatten() if x is False]      )/len(na.flatten()      )*100:.4f} %"""
		    " element-wise mismatch"
		)
		raise Exception("""tensors are all good"""      )

		# Hugging face functions below


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		_lowercase				: int     =   urlparse(__UpperCAmelCase      )
		return parsed.scheme in ("http", "https")


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase=True      ):
		_lowercase				: str     =   CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
		_lowercase				: Any     =   """/""" not in model_id
		if legacy_format:
				return F"""{endpoint}/{model_id}-{filename}"""
		else:
				return F"""{endpoint}/{model_id}/{filename}"""


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=0   ,				__UpperCAmelCase=None   ,				):
		_lowercase				: str     =   """python/{}""".format(sys.version.split()[0]      )
		if _torch_available:
				ua += "; torch/{}".format(torch.__version__      )
		if isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				ua += "; " + "; ".join("""{}/{}""".format(__UpperCAmelCase   ,				__UpperCAmelCase      ) for k, v in user_agent.items()      )
		elif isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				ua += "; " + user_agent
		_lowercase				: str     =   {"""user-agent""": ua}
		if resume_size > 0:
				_lowercase				: Any     =   """bytes=%d-""" % (resume_size,)
		_lowercase				: Tuple     =   requests.get(__UpperCAmelCase   ,				stream=__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				headers=__UpperCAmelCase      )
		if response.status_code == 416:  # Range not satisfiable
				return
		_lowercase				: Any     =   response.headers.get("""Content-Length"""      )
		_lowercase				: Optional[Any]     =   resume_size + int(__UpperCAmelCase      ) if content_length is not None else None
		_lowercase				: Tuple     =   tqdm(
		    unit="""B"""   ,				unit_scale=__UpperCAmelCase   ,				total=__UpperCAmelCase   ,				initial=__UpperCAmelCase   ,				desc="""Downloading"""   ,				)
		for chunk in response.iter_content(chunk_size=1024      ):
				if chunk:  # filter out keep-alive new chunks
						progress.update(len(__UpperCAmelCase      )      )
						temp_file.write(__UpperCAmelCase      )
		progress.close()


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=10   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=False   ,				):
		if cache_dir is None:
				_lowercase				: Tuple     =   TRANSFORMERS_CACHE
		if isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				_lowercase				: List[Any]     =   str(__UpperCAmelCase      )

		os.makedirs(__UpperCAmelCase   ,				exist_ok=__UpperCAmelCase      )

		_lowercase				: Dict     =   None
		if not local_files_only:
				try:
						_lowercase				: Tuple     =   requests.head(__UpperCAmelCase   ,				allow_redirects=__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				timeout=__UpperCAmelCase      )
						if response.status_code == 200:
								_lowercase				: Any     =   response.headers.get("""ETag"""      )
				except (EnvironmentError, requests.exceptions.Timeout):
						# etag is already None
						pass

		_lowercase				: str     =   url_to_filename(__UpperCAmelCase   ,				__UpperCAmelCase      )

		# get cache path to put the file
		_lowercase				: Union[str, Any]     =   os.path.join(__UpperCAmelCase   ,				__UpperCAmelCase      )

		# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
		# try to get the last downloaded one
		if etag is None:
				if os.path.exists(__UpperCAmelCase      ):
						return cache_path
				else:
						_lowercase				: List[str]     =   [
						    file
						    for file in fnmatch.filter(os.listdir(__UpperCAmelCase      )   ,				filename + """.*"""      )
						    if not file.endswith(""".json"""      ) and not file.endswith(""".lock"""      )
						]
						if len(__UpperCAmelCase      ) > 0:
								return os.path.join(__UpperCAmelCase   ,				matching_files[-1]      )
						else:
								# If files cannot be found and local_files_only=True,
								# the models might've been found if local_files_only=False
								# Notify the user about that
								if local_files_only:
										raise ValueError(
										    """Cannot find the requested files in the cached path and outgoing traffic has been"""
										    """ disabled. To enable model look-ups and downloads online, set 'local_files_only'"""
										    """ to False."""      )
								return None

    # From now on, etag is not None.
		if os.path.exists(__UpperCAmelCase      ) and not force_download:
				return cache_path

		# Prevent parallel downloads of the same file with a lock.
		_lowercase				: int     =   cache_path + """.lock"""
		with FileLock(__UpperCAmelCase      ):
				# If the download just completed while the lock was activated.
				if os.path.exists(__UpperCAmelCase      ) and not force_download:
						# Even if returning early like here, the lock will be released.
						return cache_path

				if resume_download:
						_lowercase				: Optional[Any]     =   cache_path + """.incomplete"""

						@contextmanager
						def _resumable_file_manager():
								with open(__UpperCAmelCase   ,				"""a+b"""      ) as f:
										yield f

						_lowercase				: List[str]     =   _resumable_file_manager
						if os.path.exists(__UpperCAmelCase      ):
								_lowercase				: List[Any]     =   os.stat(__UpperCAmelCase      ).st_size
						else:
								_lowercase				: List[str]     =   0
				else:
						_lowercase				: Any     =   partial(tempfile.NamedTemporaryFile   ,				dir=__UpperCAmelCase   ,				delete=__UpperCAmelCase      )
						_lowercase				: Union[str, Any]     =   0

				# Download to temporary file, then copy to cache dir once finished.
				# Otherwise you get corrupt cache entries if the download gets interrupted.
				with temp_file_manager() as temp_file:
						print(
						    """%s not found in cache or force_download set to True, downloading to %s"""   ,				__UpperCAmelCase   ,				temp_file.name   ,				)

						http_get(
						    __UpperCAmelCase   ,				__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				resume_size=__UpperCAmelCase   ,				user_agent=__UpperCAmelCase   ,				)

				os.replace(temp_file.name   ,				__UpperCAmelCase      )

				_lowercase				: Optional[Any]     =   {"""url""": url, """etag""": etag}
				_lowercase				: Optional[Any]     =   cache_path + """.json"""
				with open(__UpperCAmelCase   ,				"""w"""      ) as meta_file:
						json.dump(__UpperCAmelCase   ,				__UpperCAmelCase      )

		return cache_path


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=None      ):
		_lowercase				: List[str]     =   url.encode("""utf-8"""      )
		_lowercase				: Dict     =   shaaaa(__UpperCAmelCase      )
		_lowercase				: List[str]     =   url_hash.hexdigest()

		if etag:
				_lowercase				: Dict     =   etag.encode("""utf-8"""      )
				_lowercase				: Optional[int]     =   shaaaa(__UpperCAmelCase      )
				filename += "." + etag_hash.hexdigest()

		if url.endswith(""".h5"""      ):
				filename += ".h5"

		return filename


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=None   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False   ,				):
		if cache_dir is None:
				_lowercase				: Optional[Any]     =   TRANSFORMERS_CACHE
		if isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				_lowercase				: Optional[Any]     =   str(__UpperCAmelCase      )
		if isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				_lowercase				: Optional[Any]     =   str(__UpperCAmelCase      )

		if is_remote_url(__UpperCAmelCase      ):
				# URL, so get it from the cache (downloading if necessary)
				_lowercase				: List[Any]     =   get_from_cache(
				    __UpperCAmelCase   ,				cache_dir=__UpperCAmelCase   ,				force_download=__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				resume_download=__UpperCAmelCase   ,				user_agent=__UpperCAmelCase   ,				local_files_only=__UpperCAmelCase   ,				)
		elif os.path.exists(__UpperCAmelCase      ):
				# File, and it exists.
				_lowercase				: List[str]     =   url_or_filename
		elif urlparse(__UpperCAmelCase      ).scheme == "":
				# File, but it doesn't exist.
				raise EnvironmentError("""file {} not found""".format(__UpperCAmelCase      )      )
		else:
				# Something unknown
				raise ValueError("""unable to parse {} as a URL or as a local path""".format(__UpperCAmelCase      )      )

		if extract_compressed_file:
				if not is_zipfile(__UpperCAmelCase      ) and not tarfile.is_tarfile(__UpperCAmelCase      ):
						return output_path

				# Path where we extract compressed archives
				# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
				_lowercase     ,  _lowercase				: int     =   os.path.split(__UpperCAmelCase      )
				_lowercase				: Dict     =   output_file.replace("""."""   ,				"""-"""      ) + """-extracted"""
				_lowercase				: Union[str, Any]     =   os.path.join(__UpperCAmelCase   ,				__UpperCAmelCase      )

				if os.path.isdir(__UpperCAmelCase      ) and os.listdir(__UpperCAmelCase      ) and not force_extract:
						return output_path_extracted

				# Prevent parallel extractions
				_lowercase				: List[str]     =   output_path + """.lock"""
				with FileLock(__UpperCAmelCase      ):
						shutil.rmtree(__UpperCAmelCase   ,				ignore_errors=__UpperCAmelCase      )
						os.makedirs(__UpperCAmelCase      )
						if is_zipfile(__UpperCAmelCase      ):
								with ZipFile(__UpperCAmelCase   ,				"""r"""      ) as zip_file:
										zip_file.extractall(__UpperCAmelCase      )
										zip_file.close()
						elif tarfile.is_tarfile(__UpperCAmelCase      ):
								_lowercase				: Union[str, Any]     =   tarfile.open(__UpperCAmelCase      )
								tar_file.extractall(__UpperCAmelCase      )
								tar_file.close()
						else:
								raise EnvironmentError("""Archive format of {} could not be identified""".format(__UpperCAmelCase      )      )

				return output_path_extracted

		return output_path


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=","      ):
		assert isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      )
		if os.path.isfile(__UpperCAmelCase      ):
				with open(__UpperCAmelCase      ) as f:
						_lowercase				: Any     =   eval(f.read()      )
		else:
				_lowercase				: int     =   requests.get(__UpperCAmelCase      )
				try:
						_lowercase				: Optional[int]     =   requests.json()
				except Exception:
						_lowercase				: Dict     =   req.content.decode()
						assert data is not None, "could not connect"
						try:
								_lowercase				: str     =   eval(__UpperCAmelCase      )
						except Exception:
								_lowercase				: Optional[Any]     =   data.split("""\n"""      )
				req.close()
		return data


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		_lowercase				: List[Any]     =   requests.get(__UpperCAmelCase      )
		_lowercase				: Tuple     =   np.array(Image.open(BytesIO(response.content      )      )      )
		return img


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		_lowercase				: Tuple     =   url.split("""/"""      )[-1]
		if fn not in os.listdir(os.getcwd()      ):
				wget.download(__UpperCAmelCase      )
		with open(__UpperCAmelCase   ,				"""rb"""      ) as stream:
				_lowercase				: Any     =   pkl.load(__UpperCAmelCase      )
		_lowercase				: str     =   weights.pop("""model"""      )
		_lowercase				: Tuple     =   {}
		for k, v in model.items():
				_lowercase				: Dict     =   torch.from_numpy(__UpperCAmelCase      )
				if "running_var" in k:
						_lowercase				: Union[str, Any]     =   torch.tensor([0]      )
						_lowercase				: int     =   k.replace("""running_var"""   ,				"""num_batches_tracked"""      )
						_lowercase				: List[Any]     =   zero
		return new


def  __SCREAMING_SNAKE_CASE (  ):
		print(F"""{os.path.abspath(os.path.join(__UpperCAmelCase   ,				os.pardir      )      )}/demo.ipynb"""      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase="RGB"      ):
		assert isinstance(__UpperCAmelCase   ,				__UpperCAmelCase      )
		if os.path.isfile(__UpperCAmelCase      ):
				_lowercase				: int     =   cva.imread(__UpperCAmelCase      )
		else:
				_lowercase				: List[Any]     =   get_image_from_url(__UpperCAmelCase      )
				assert img is not None, F"""could not connect to: {im}"""
		_lowercase				: str     =   cva.cvtColor(__UpperCAmelCase   ,				cva.COLOR_BGR2RGB      )
		if input_format == "RGB":
				_lowercase				: Union[str, Any]     =   img[:, :, ::-1]
		return img


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=1      ):
		return (images[i : i + batch] for i in range(0   ,				len(__UpperCAmelCase      )   ,				__UpperCAmelCase      ))










import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_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 DonutSwinModel
      from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST





class   lowercase__     :







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







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_       :							Any			 =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

       lowerCAmelCase_       :							List[Any]			 =		self.get_config()

       return config, pixel_values, labels







  def 						UpperCAmelCase__		(						self    ):
       return DonutSwinConfig(
           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 						UpperCAmelCase__		(						self     ,    _lowercase     ,    _lowercase     ,    _lowercase    ):
       lowerCAmelCase_       :							Optional[Any]			 =		DonutSwinModel(config=_lowercase    )
       model.to(_lowercase    )
       model.eval()
       lowerCAmelCase_       :							Optional[Any]			 =		model(_lowercase    )

       lowerCAmelCase_       :							Optional[int]			 =		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
       lowerCAmelCase_       :							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 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_       :							str			 =		self.prepare_config_and_inputs()
       (
           (
           lowerCAmelCase_
       ) ,	(
           lowerCAmelCase_
       ) ,	(
           lowerCAmelCase_
       ) ,	
       )       :							List[str]			 =		config_and_inputs
       lowerCAmelCase_       :							int			 =		{"""pixel_values""": pixel_values}
       return config, inputs_dict





@require_torch
class   lowercase__     (				__A  ,       __A  ,       unittest.TestCase	):
  __UpperCamelCase						  =	(DonutSwinModel,) if is_torch_available() else ()
  __UpperCamelCase						  =	{"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
  __UpperCamelCase						  =	True

  __UpperCamelCase						  =	False
  __UpperCamelCase						  =	False
  __UpperCamelCase						  =	False







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_       :							Tuple			 =		DonutSwinModelTester(self    )
       lowerCAmelCase_       :							Optional[Any]			 =		ConfigTester(self     ,    config_class=_lowercase     ,    embed_dim=37    )







  def 						UpperCAmelCase__		(						self    ):
       self.create_and_test_config_common_properties()
       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 						UpperCAmelCase__		(						self    ):
       return







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_       :							Tuple			 =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowercase    )







  def 						UpperCAmelCase__		(						self    ):
       # DonutSwin does not use inputs_embeds
       pass







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							str			 =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowerCAmelCase_       :							Optional[Any]			 =		model_class(_lowercase    )
            self.assertIsInstance(model.get_input_embeddings()     ,    (nn.Module)    )
            lowerCAmelCase_       :							int			 =		model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(_lowercase     ,    nn.Linear    )    )







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							List[Any]			 =		self.model_tester.prepare_config_and_inputs_for_common()

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

            lowerCAmelCase_       :							Union[str, Any]			 =		["""pixel_values"""]
            self.assertListEqual(arg_names[:1]     ,    _lowercase    )







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							Optional[Any]			 =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_       :							Tuple			 =		True

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

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            lowerCAmelCase_       :							int			 =		True
            lowerCAmelCase_       :							Union[str, Any]			 =		config.window_size**2
            lowerCAmelCase_       :							Tuple			 =		model_class(_lowercase    )
            model.to(_lowercase    )
            model.eval()
            with torch.no_grad():
                 lowerCAmelCase_       :							Any			 =		model(**self._prepare_for_class(_lowercase     ,    _lowercase    )    )
            lowerCAmelCase_       :							int			 =		outputs.attentions
            self.assertEqual(len(_lowercase    )     ,    _lowercase    )

            self.assertListEqual(
                list(attentions[0].shape[-3:]    )     ,    [self.model_tester.num_heads[0], window_size_squared, window_size_squared]     ,    )
            lowerCAmelCase_       :							Any			 =		len(_lowercase    )

            # Check attention is always last and order is fine
            lowerCAmelCase_       :							int			 =		True
            lowerCAmelCase_       :							str			 =		True
            lowerCAmelCase_       :							Tuple			 =		model_class(_lowercase    )
            model.to(_lowercase    )
            model.eval()
            with torch.no_grad():
                 lowerCAmelCase_       :							Any			 =		model(**self._prepare_for_class(_lowercase     ,    _lowercase    )    )

            if hasattr(self.model_tester     ,    """num_hidden_states_types"""    ):
                 lowerCAmelCase_       :							Optional[Any]			 =		self.model_tester.num_hidden_states_types
            else:
                 # also another +1 for reshaped_hidden_states
                 lowerCAmelCase_       :							Union[str, Any]			 =		2
            self.assertEqual(out_len + added_hidden_states     ,    len(_lowercase    )    )

            lowerCAmelCase_       :							Any			 =		outputs.attentions

            self.assertEqual(len(_lowercase    )     ,    _lowercase    )

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







  def 						UpperCAmelCase__		(						self     ,    _lowercase     ,    _lowercase     ,    _lowercase     ,    _lowercase    ):
       lowerCAmelCase_       :							Optional[Any]			 =		model_class(_lowercase    )
       model.to(_lowercase    )
       model.eval()

       with torch.no_grad():
            lowerCAmelCase_       :							List[str]			 =		model(**self._prepare_for_class(_lowercase     ,    _lowercase    )    )

       lowerCAmelCase_       :							List[Any]			 =		outputs.hidden_states

       lowerCAmelCase_       :							str			 =		getattr(
           self.model_tester     ,    """expected_num_hidden_layers"""     ,    len(self.model_tester.depths    ) + 1    )
       self.assertEqual(len(_lowercase    )     ,    _lowercase    )

       # DonutSwin has a different seq_length
       lowerCAmelCase_       :							int			 =		(
           config.patch_size
           if isinstance(config.patch_size     ,    collections.abc.Iterable    )
           else (config.patch_size, config.patch_size)
       )

       lowerCAmelCase_       :							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]     ,    )

       lowerCAmelCase_       :							List[Any]			 =		outputs.reshaped_hidden_states
       self.assertEqual(len(_lowercase    )     ,    _lowercase    )

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







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							Dict			 =		self.model_tester.prepare_config_and_inputs_for_common()

       lowerCAmelCase_       :							int			 =		(
           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:
            lowerCAmelCase_       :							Any			 =		True
            self.check_hidden_states_output(_lowercase     ,    _lowercase     ,    _lowercase     ,    _lowercase    )

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

            self.check_hidden_states_output(_lowercase     ,    _lowercase     ,    _lowercase     ,    _lowercase    )







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							int			 =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_       :							int			 =		3

       lowerCAmelCase_       :							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)
       )
       lowerCAmelCase_       :							Optional[int]			 =		(
           config.patch_size
           if isinstance(config.patch_size     ,    collections.abc.Iterable    )
           else (config.patch_size, config.patch_size)
       )

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

       for model_class in self.all_model_classes:
            lowerCAmelCase_       :							Tuple			 =		True
            self.check_hidden_states_output(_lowercase     ,    _lowercase     ,    _lowercase     ,    (padded_height, padded_width)    )

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







  @slow
  def 						UpperCAmelCase__		(						self    ):
       for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowerCAmelCase_       :							str			 =		DonutSwinModel.from_pretrained(_lowercase    )
            self.assertIsNotNone(_lowercase    )







  def 						UpperCAmelCase__		(						self    ):
       lowerCAmelCase_ ,	lowerCAmelCase_       :							List[str]			 =		self.model_tester.prepare_config_and_inputs_for_common()

       lowerCAmelCase_       :							str			 =		_config_zero_init(_lowercase    )
       for model_class in self.all_model_classes:
            lowerCAmelCase_       :							Union[str, Any]			 =		model_class(config=_lowercase    )
            for name, param in model.named_parameters():
                 if "embeddings" 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'     ,    )
