






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

 lowerCamelCase     :							Any    =True
except ImportError:
 lowerCamelCase     :							int    =False


try:
 from torch.hub import _get_torch_home

 lowerCamelCase     :							Optional[int]    =_get_torch_home()
except ImportError:
 lowerCamelCase     :							Optional[Any]    =os.path.expanduser(
     os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
 )

lowerCamelCase     :							Optional[Any]    =os.path.join(torch_cache_home, '''transformers''')

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







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase=OBJECTS ,   __lowerCAmelCase=ATTRIBUTES      )			->     Optional[int]:
     UpperCamelCase__      :       Tuple	    =  []
     with open(__lowerCAmelCase      ) as f:
          for object in f.readlines():
               vg_classes.append(object.split(","      )[0].lower().strip()      )

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







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





class       __a  :
 _lowerCAmelCase	:	List[Any]				=			{}







 def __init__(		self :       Dict							,       SCREAMING_SNAKE_CASE :       dict							,       SCREAMING_SNAKE_CASE :       str = "root"							,       SCREAMING_SNAKE_CASE :       List[str]=0						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[Any]	    =  name
      UpperCamelCase__      :       List[str]	    =  level
      UpperCamelCase__      :       Dict	    =  {}
      for k, v in dictionary.items():
           if v is None:
                raise ValueError()
           UpperCamelCase__      :       Optional[int]	    =  copy.deepcopy(SCREAMING_SNAKE_CASE						)
           UpperCamelCase__      :       List[str]	    =  copy.deepcopy(SCREAMING_SNAKE_CASE						)
           if isinstance(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						):
                UpperCamelCase__      :       Optional[Any]	    =  Config(SCREAMING_SNAKE_CASE							,       name=SCREAMING_SNAKE_CASE							,       level=level + 1						)
           UpperCamelCase__      :       Dict	    =  v
           setattr(self							,       SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						)

      UpperCamelCase__      :       Optional[int]	    =  d







 def __repr__(		self :       int						):


      '''simple docstring'''






      return str(list((self._pointer.keys())						)						)







 def __setattr__(		self :       int							,       SCREAMING_SNAKE_CASE :       List[str]							,       SCREAMING_SNAKE_CASE :       List[Any]						):


      '''simple docstring'''






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







 def  __lowercase (		self :       Tuple						):


      '''simple docstring'''






      return self._pointer







 def  __lowercase (		self :       Any							,       SCREAMING_SNAKE_CASE :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       Tuple						):


      '''simple docstring'''






      with open(F'{file_name}'							,       "w"						) as stream:
           dump(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						)







 def  __lowercase (		self :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[Any]							,       SCREAMING_SNAKE_CASE :       Dict						):


      '''simple docstring'''






      with open(F'{file_name}'							,       "w"						) as stream:
           json.dump(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						)







 @staticmethod
 def  __lowercase (		SCREAMING_SNAKE_CASE :       Union[str, Any]						):


      '''simple docstring'''






      with open(SCREAMING_SNAKE_CASE						) as stream:
           UpperCamelCase__      :       int	    =  load(SCREAMING_SNAKE_CASE							,       Loader=SCREAMING_SNAKE_CASE						)
      return data







 def __str__(		self :       Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  "    "
      if self._name != "root":
           UpperCamelCase__      :       int	    =  F'{t * (self._level-1)}{self._name}:\n'
      else:
           UpperCamelCase__      :       Optional[int]	    =  ""
      UpperCamelCase__      :       Union[str, Any]	    =  self._level
      for i, (k, v) in enumerate(self._pointer.items()						):
           if isinstance(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						):
                r += F'{t * (self._level)}{v}\n'
                self._level += 1
           else:
                r += F'{t * (self._level)}{k}: {v} ({type(SCREAMING_SNAKE_CASE						).__name__})\n'
           UpperCamelCase__      :       Optional[Any]	    =  level
      return r[:-1]







 @classmethod
 def  __lowercase (		cls :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       str							,       **SCREAMING_SNAKE_CASE :       Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__    ,					UpperCamelCase__      :       Dict	    =  cls.get_config_dict(SCREAMING_SNAKE_CASE							,       **SCREAMING_SNAKE_CASE						)
      return cls(SCREAMING_SNAKE_CASE						)







 @classmethod
 def  __lowercase (		cls :       str							,       SCREAMING_SNAKE_CASE :       str							,       **SCREAMING_SNAKE_CASE :       Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[str]	    =  kwargs.pop("cache_dir"							,       SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       int	    =  kwargs.pop("force_download"							,       SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       Union[str, Any]	    =  kwargs.pop("resume_download"							,       SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       Dict	    =  kwargs.pop("proxies"							,       SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       List[str]	    =  kwargs.pop("local_files_only"							,       SCREAMING_SNAKE_CASE						)

      if os.path.isdir(SCREAMING_SNAKE_CASE						):
           UpperCamelCase__      :       Tuple	    =  os.path.join(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						)
      elif os.path.isfile(SCREAMING_SNAKE_CASE						) or is_remote_url(SCREAMING_SNAKE_CASE						):
           UpperCamelCase__      :       Optional[int]	    =  pretrained_model_name_or_path
      else:
           UpperCamelCase__      :       Optional[Any]	    =  hf_bucket_url(SCREAMING_SNAKE_CASE							,       filename=SCREAMING_SNAKE_CASE							,       use_cdn=SCREAMING_SNAKE_CASE						)

      try:
           # Load from URL or cache if already cached
           UpperCamelCase__      :       str	    =  cached_path(
               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							,       )
           # Load config dict
           if resolved_config_file is None:
                raise EnvironmentError

           UpperCamelCase__      :       Union[str, Any]	    =  Config.load_yaml(SCREAMING_SNAKE_CASE						)

      except EnvironmentError:
           UpperCamelCase__      :       Union[str, Any]	    =  "Can't load config for"
           raise EnvironmentError(SCREAMING_SNAKE_CASE						)

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

      return Config.load_yaml(SCREAMING_SNAKE_CASE						), kwargs







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase      )			->     str:
     UpperCamelCase__      :       Tuple	    =  torch.load("dump.pt" ,   map_location=in_tensor.device      )
     UpperCamelCase__      :       Union[str, Any]	    =  in_tensor.numpy()
     UpperCamelCase__      :       List[Any]	    =  out_tensor.numpy()[0]
     print(na.shape ,   na[0, 0, :5]      )
     print(na.shape ,   na[0, 0, :5]      )
     assert np.allclose(__lowerCAmelCase ,   __lowerCAmelCase ,   rtol=0.0_1 ,   atol=0.1      ), (
         f'{sum([1 for x in np.isclose(__lowerCAmelCase ,   __lowerCAmelCase ,   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							( __lowerCAmelCase      )			->     Dict:
     UpperCamelCase__      :       Union[str, Any]	    =  urlparse(__lowerCAmelCase      )
     return parsed.scheme in ("http", "https")







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase ,   __lowerCAmelCase=True      )			->     str:
     UpperCamelCase__      :       List[str]	    =  CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
     UpperCamelCase__      :       int	    =  "/" not in model_id
     if legacy_format:
          return f'{endpoint}/{model_id}-{filename}'
     else:
          return f'{endpoint}/{model_id}/{filename}'







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







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase=None ,   __lowerCAmelCase=False ,   __lowerCAmelCase=None ,   __lowerCAmelCase=10 ,   __lowerCAmelCase=False ,   __lowerCAmelCase=None ,   __lowerCAmelCase=False ,   )			->     List[Any]:
     if cache_dir is None:
          UpperCamelCase__      :       List[str]	    =  TRANSFORMERS_CACHE
     if isinstance(__lowerCAmelCase ,   __lowerCAmelCase      ):
          UpperCamelCase__      :       Union[str, Any]	    =  str(__lowerCAmelCase      )

     os.makedirs(__lowerCAmelCase ,   exist_ok=__lowerCAmelCase      )

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

     UpperCamelCase__      :       Optional[int]	    =  url_to_filename(__lowerCAmelCase ,   __lowerCAmelCase      )

     # get cache path to put the file
     UpperCamelCase__      :       List[str]	    =  os.path.join(__lowerCAmelCase ,   __lowerCAmelCase      )

     # 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(__lowerCAmelCase      ):
               return cache_path
          else:
               UpperCamelCase__      :       Tuple	    =  [
                   file
                   for file in fnmatch.filter(os.listdir(__lowerCAmelCase      ) ,   filename + ".*"      )
                   if not file.endswith(".json"      ) and not file.endswith(".lock"      )
               ]
               if len(__lowerCAmelCase      ) > 0:
                    return os.path.join(__lowerCAmelCase ,   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(__lowerCAmelCase      ) and not force_download:
          return cache_path

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

          if resume_download:
               UpperCamelCase__      :       str	    =  cache_path + ".incomplete"

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

               UpperCamelCase__      :       Optional[int]	    =  _resumable_file_manager
               if os.path.exists(__lowerCAmelCase      ):
                    UpperCamelCase__      :       List[Any]	    =  os.stat(__lowerCAmelCase      ).st_size
               else:
                    UpperCamelCase__      :       Union[str, Any]	    =  0
          else:
               UpperCamelCase__      :       Any	    =  partial(tempfile.NamedTemporaryFile ,   dir=__lowerCAmelCase ,   delete=__lowerCAmelCase      )
               UpperCamelCase__      :       Optional[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" ,   __lowerCAmelCase ,   temp_file.name ,   )

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

          os.replace(temp_file.name ,   __lowerCAmelCase      )

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

     return cache_path







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase=None      )			->     Optional[Any]:
     UpperCamelCase__      :       int	    =  url.encode("utf-8"      )
     UpperCamelCase__      :       Any	    =  shaaaa(__lowerCAmelCase      )
     UpperCamelCase__      :       List[str]	    =  url_hash.hexdigest()

     if etag:
          UpperCamelCase__      :       Tuple	    =  etag.encode("utf-8"      )
          UpperCamelCase__      :       Union[str, Any]	    =  shaaaa(__lowerCAmelCase      )
          filename += "." + etag_hash.hexdigest()

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

     return filename







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase=None ,   __lowerCAmelCase=False ,   __lowerCAmelCase=None ,   __lowerCAmelCase=False ,   __lowerCAmelCase=None ,   __lowerCAmelCase=False ,   __lowerCAmelCase=False ,   __lowerCAmelCase=False ,   )			->     List[str]:
     if cache_dir is None:
          UpperCamelCase__      :       Optional[int]	    =  TRANSFORMERS_CACHE
     if isinstance(__lowerCAmelCase ,   __lowerCAmelCase      ):
          UpperCamelCase__      :       List[str]	    =  str(__lowerCAmelCase      )
     if isinstance(__lowerCAmelCase ,   __lowerCAmelCase      ):
          UpperCamelCase__      :       Optional[int]	    =  str(__lowerCAmelCase      )

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

     if extract_compressed_file:
          if not is_zipfile(__lowerCAmelCase      ) and not tarfile.is_tarfile(__lowerCAmelCase      ):
               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/"
          UpperCamelCase__    ,					UpperCamelCase__      :       Tuple	    =  os.path.split(__lowerCAmelCase      )
          UpperCamelCase__      :       str	    =  output_file.replace("." ,   "-"      ) + "-extracted"
          UpperCamelCase__      :       str	    =  os.path.join(__lowerCAmelCase ,   __lowerCAmelCase      )

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

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

          return output_path_extracted

     return output_path







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase=","      )			->     Any:
     assert isinstance(__lowerCAmelCase ,   __lowerCAmelCase      )
     if os.path.isfile(__lowerCAmelCase      ):
          with open(__lowerCAmelCase      ) as f:
               UpperCamelCase__      :       Tuple	    =  eval(f.read()      )
     else:
          UpperCamelCase__      :       List[Any]	    =  requests.get(__lowerCAmelCase      )
          try:
               UpperCamelCase__      :       str	    =  requests.json()
          except Exception:
               UpperCamelCase__      :       List[Any]	    =  req.content.decode()
               assert data is not None, "could not connect"
               try:
                    UpperCamelCase__      :       Union[str, Any]	    =  eval(__lowerCAmelCase      )
               except Exception:
                    UpperCamelCase__      :       List[Any]	    =  data.split("\n"      )
          req.close()
     return data







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase      )			->     Optional[int]:
     UpperCamelCase__      :       str	    =  requests.get(__lowerCAmelCase      )
     UpperCamelCase__      :       Any	    =  np.array(Image.open(BytesIO(response.content      )      )      )
     return img







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







def 		SCREAMING_SNAKE_CASE							( )			->     Optional[int]:
     print(f'{os.path.abspath(os.path.join(__lowerCAmelCase ,   os.pardir      )      )}/demo.ipynb'      )







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase="RGB"      )			->     Union[str, Any]:
     assert isinstance(__lowerCAmelCase ,   __lowerCAmelCase      )
     if os.path.isfile(__lowerCAmelCase      ):
          UpperCamelCase__      :       Optional[Any]	    =  cva.imread(__lowerCAmelCase      )
     else:
          UpperCamelCase__      :       Any	    =  get_image_from_url(__lowerCAmelCase      )
          assert img is not None, f'could not connect to: {im}'
     UpperCamelCase__      :       Tuple	    =  cva.cvtColor(__lowerCAmelCase ,   cva.COLOR_BGR2RGB      )
     if input_format == "RGB":
          UpperCamelCase__      :       Optional[Any]	    =  img[:, :, ::-1]
     return img







def 		SCREAMING_SNAKE_CASE							( __lowerCAmelCase ,   __lowerCAmelCase=1      )			->     int:
     return (images[i : i + batch] for i in range(0 ,   len(__lowerCAmelCase      ) ,   __lowerCAmelCase      ))







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowerCamelCase     :							Optional[Any]    =False





class       __a  (   unittest.TestCase	):
 pass







@nightly
@require_torch_gpu
class       __a  (   unittest.TestCase	):







 def  __lowercase (		self :       Any						):


      '''simple docstring'''






      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()







 def  __lowercase (		self :       Dict						):


      '''simple docstring'''






      UpperCamelCase__      :       int	    =  VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"							,       torch_dtype=torch.floataa						)
      pipe.to(SCREAMING_SNAKE_CASE						)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

      UpperCamelCase__      :       Optional[int]	    =  load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"						)

      UpperCamelCase__      :       Dict	    =  torch.manual_seed(0						)
      UpperCamelCase__      :       str	    =  pipe.dual_guided(
          prompt="first prompt"							,       image=SCREAMING_SNAKE_CASE							,       text_to_image_strength=0.7_5							,       generator=SCREAMING_SNAKE_CASE							,       guidance_scale=7.5							,       num_inference_steps=2							,       output_type="numpy"							,       ).images

      with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(SCREAMING_SNAKE_CASE						)
           UpperCamelCase__      :       Tuple	    =  VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE							,       torch_dtype=torch.floataa						)
      pipe.to(SCREAMING_SNAKE_CASE						)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

      UpperCamelCase__      :       int	    =  generator.manual_seed(0						)
      UpperCamelCase__      :       Dict	    =  pipe.dual_guided(
          prompt="first prompt"							,       image=SCREAMING_SNAKE_CASE							,       text_to_image_strength=0.7_5							,       generator=SCREAMING_SNAKE_CASE							,       guidance_scale=7.5							,       num_inference_steps=2							,       output_type="numpy"							,       ).images

      assert np.abs(image - new_image						).sum() < 1e-5, "Models don't have the same forward pass"







 def  __lowercase (		self :       Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[int]	    =  VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"							,       torch_dtype=torch.floataa						)
      pipe.to(SCREAMING_SNAKE_CASE						)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

      UpperCamelCase__      :       Tuple	    =  "cyberpunk 2077"
      UpperCamelCase__      :       Any	    =  load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"						)
      UpperCamelCase__      :       int	    =  torch.manual_seed(0						)
      UpperCamelCase__      :       Any	    =  pipe.dual_guided(
          prompt=SCREAMING_SNAKE_CASE							,       image=SCREAMING_SNAKE_CASE							,       text_to_image_strength=0.7_5							,       generator=SCREAMING_SNAKE_CASE							,       guidance_scale=7.5							,       num_inference_steps=50							,       output_type="numpy"							,       ).images

      UpperCamelCase__      :       Tuple	    =  image[0, 2_53:2_56, 2_53:2_56, -1]

      assert image.shape == (1, 5_12, 5_12, 3)
      UpperCamelCase__      :       Optional[int]	    =  np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1]						)

      assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1

      UpperCamelCase__      :       List[str]	    =  "A painting of a squirrel eating a burger "
      UpperCamelCase__      :       List[Any]	    =  torch.manual_seed(0						)
      UpperCamelCase__      :       Dict	    =  pipe.text_to_image(
          prompt=SCREAMING_SNAKE_CASE							,       generator=SCREAMING_SNAKE_CASE							,       guidance_scale=7.5							,       num_inference_steps=50							,       output_type="numpy"						).images

      UpperCamelCase__      :       Union[str, Any]	    =  image[0, 2_53:2_56, 2_53:2_56, -1]

      assert image.shape == (1, 5_12, 5_12, 3)
      UpperCamelCase__      :       Dict	    =  np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8]						)

      assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1

      UpperCamelCase__      :       Any	    =  pipe.image_variation(SCREAMING_SNAKE_CASE							,       generator=SCREAMING_SNAKE_CASE							,       output_type="numpy"						).images

      UpperCamelCase__      :       Optional[Any]	    =  image[0, 2_53:2_56, 2_53:2_56, -1]

      assert image.shape == (1, 5_12, 5_12, 3)
      UpperCamelCase__      :       int	    =  np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6]						)

      assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1