



"""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						:		Optional[Any]			= True
except ImportError:
       UpperCAmelCase						:		Dict			= False


try:
       from torch.hub import _get_torch_home

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

UpperCAmelCase						:		List[str]			= os.path.join(torch_cache_home, "transformers")

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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase=OBJECTS ,  __lowerCAmelCase=ATTRIBUTES							) ->						str:







  '''simple docstring'''


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

  lowercase_								= []
  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							) ->						Union[str, Any]:







  '''simple docstring'''


  lowercase_								= OrderedDict()
  with open(__lowerCAmelCase ,  """rb"""							) as f:
    lowercase_								= pkl.load(__lowerCAmelCase							)["""model"""]
  for k in copy.deepcopy(list(ckp.keys()							)							):
    lowercase_								= ckp.pop(__lowerCAmelCase							)
    if isinstance(__lowerCAmelCase ,  np.ndarray							):
      lowercase_								= torch.tensor(__lowerCAmelCase							)
    else:
      assert isinstance(__lowerCAmelCase ,  torch.tensor							), type(__lowerCAmelCase							)
    lowercase_								= v
  return r


class    SCREAMING_SNAKE_CASE__ :
    lowercase__      =   {}

    def __init__(				self			:				Union[str, Any] ,  lowerCAmelCase_			:				dict ,  lowerCAmelCase_			:				str = "root" ,  lowerCAmelCase_			:				str=0):







      """simple docstring"""







      lowercase_								= name
      lowercase_								= level
      lowercase_								= {}
      for k, v in dictionary.items():
        if v is None:
          raise ValueError()
        lowercase_								= copy.deepcopy(lowerCAmelCase_)
        lowercase_								= copy.deepcopy(lowerCAmelCase_)
        if isinstance(lowerCAmelCase_ ,  lowerCAmelCase_):
          lowercase_								= Config(lowerCAmelCase_ ,  name=lowerCAmelCase_ ,  level=level + 1)
        lowercase_								= v
        setattr(self ,  lowerCAmelCase_ ,  lowerCAmelCase_)

      lowercase_								= d

    def __repr__(				self			:				Any):







      """simple docstring"""







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

    def __setattr__(				self			:				int ,  lowerCAmelCase_			:				Optional[Any] ,  lowerCAmelCase_			:				int):







      """simple docstring"""







      lowercase_								= val
      lowercase_								= val
      lowercase_								= key.split(""".""")
      lowercase_								= len(lowerCAmelCase_) - 1
      lowercase_								= self._pointer
      if len(lowerCAmelCase_) > 1:
        for i, l in enumerate(lowerCAmelCase_):
          if hasattr(self ,  lowerCAmelCase_) and isinstance(getattr(self ,  lowerCAmelCase_) ,  lowerCAmelCase_):
            setattr(getattr(self ,  lowerCAmelCase_) ,  """.""".join(levels[i:]) ,  lowerCAmelCase_)
          if l == last_level:
            lowercase_								= val
          else:
            lowercase_								= pointer[l]

    def 					_UpperCAmelCase	(				self			:				List[Any]):







      """simple docstring"""







      return self._pointer

    def 					_UpperCAmelCase	(				self			:				Union[str, Any] ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				Union[str, Any]):







      """simple docstring"""







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

    def 					_UpperCAmelCase	(				self			:				List[str] ,  lowerCAmelCase_			:				Any ,  lowerCAmelCase_			:				int):







      """simple docstring"""







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

    @staticmethod
    def 					_UpperCAmelCase	(				lowerCAmelCase_			:				List[str]):







      """simple docstring"""







      with open(lowerCAmelCase_) as stream:
        lowercase_								= load(lowerCAmelCase_ ,  Loader=lowerCAmelCase_)
      return data

    def __str__(				self			:				List[Any]):







      """simple docstring"""







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

    @classmethod
    def 					_UpperCAmelCase	(				cls			:				Union[str, Any] ,  lowerCAmelCase_			:				str ,  **lowerCAmelCase_			:				Tuple):







      """simple docstring"""







      lowercase_					,    lowercase_								= cls.get_config_dict(lowerCAmelCase_ ,  **lowerCAmelCase_)
      return cls(lowerCAmelCase_)




    @classmethod
    def 					_UpperCAmelCase	(				cls			:				Tuple ,  lowerCAmelCase_			:				str ,  **lowerCAmelCase_			:				List[Any]):







      """simple docstring"""







      lowercase_								= kwargs.pop("""cache_dir""" ,  lowerCAmelCase_)
      lowercase_								= kwargs.pop("""force_download""" ,  lowerCAmelCase_)
      lowercase_								= kwargs.pop("""resume_download""" ,  lowerCAmelCase_)
      lowercase_								= kwargs.pop("""proxies""" ,  lowerCAmelCase_)
      lowercase_								= kwargs.pop("""local_files_only""" ,  lowerCAmelCase_)

      if os.path.isdir(lowerCAmelCase_):
        lowercase_								= os.path.join(lowerCAmelCase_ ,  lowerCAmelCase_)
      elif os.path.isfile(lowerCAmelCase_) or is_remote_url(lowerCAmelCase_):
        lowercase_								= pretrained_model_name_or_path
      else:
        lowercase_								= hf_bucket_url(lowerCAmelCase_ ,  filename=lowerCAmelCase_ ,  use_cdn=lowerCAmelCase_)

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

        lowercase_								= Config.load_yaml(lowerCAmelCase_)

      except EnvironmentError:
        lowercase_								= """Can't load config for"""
        raise EnvironmentError(lowerCAmelCase_)

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

      return Config.load_yaml(lowerCAmelCase_), kwargs







def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Tuple:







  '''simple docstring'''


  lowercase_								= torch.load("""dump.pt""" ,  map_location=in_tensor.device							)
  lowercase_								= in_tensor.numpy()
  lowercase_								= 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.01 ,  atol=0.1							), (
      F'''{sum([1 for x in np.isclose(__lowerCAmelCase ,  __lowerCAmelCase ,  rtol=0.01 ,  atol=0.1							).flatten() if x is False]							)/len(na.flatten()							)*1_00:.4f} %'''
      " element-wise mismatch"
  )
  raise Exception("""tensors are all good"""							)

  # Hugging face functions below


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Optional[Any]:







  '''simple docstring'''


  lowercase_								= urlparse(__lowerCAmelCase							)
  return parsed.scheme in ("http", "https")


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase ,  __lowerCAmelCase=True							) ->						str:







  '''simple docstring'''


  lowercase_								= CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
  lowercase_								= """/""" 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 ,  ) ->						List[Any]:







  '''simple docstring'''


  lowercase_								= """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
  lowercase_								= {"""user-agent""": ua}
  if resume_size > 0:
    lowercase_								= """bytes=%d-""" % (resume_size,)
  lowercase_								= requests.get(__lowerCAmelCase ,  stream=__lowerCAmelCase ,  proxies=__lowerCAmelCase ,  headers=__lowerCAmelCase							)
  if response.status_code == 4_16:  # Range not satisfiable
    return
  lowercase_								= response.headers.get("""Content-Length"""							)
  lowercase_								= resume_size + int(__lowerCAmelCase							) if content_length is not None else None
  lowercase_								= tqdm(
      unit="""B""" ,  unit_scale=__lowerCAmelCase ,  total=__lowerCAmelCase ,  initial=__lowerCAmelCase ,  desc="""Downloading""" ,  )
  for chunk in response.iter_content(chunk_size=10_24							):
    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 ,  ) ->						Optional[int]:







  '''simple docstring'''


  if cache_dir is None:
    lowercase_								= TRANSFORMERS_CACHE
  if isinstance(__lowerCAmelCase ,  __lowerCAmelCase							):
    lowercase_								= str(__lowerCAmelCase							)

  os.makedirs(__lowerCAmelCase ,  exist_ok=__lowerCAmelCase							)

  lowercase_								= None
  if not local_files_only:
    try:
      lowercase_								= requests.head(__lowerCAmelCase ,  allow_redirects=__lowerCAmelCase ,  proxies=__lowerCAmelCase ,  timeout=__lowerCAmelCase							)
      if response.status_code == 2_00:
        lowercase_								= response.headers.get("""ETag"""							)
    except (EnvironmentError, requests.exceptions.Timeout):
      # etag is already None
      pass

  lowercase_								= url_to_filename(__lowerCAmelCase ,  __lowerCAmelCase							)

  # get cache path to put the file
  lowercase_								= 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:
      lowercase_								= [
          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.
  lowercase_								= 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:
      lowercase_								= cache_path + """.incomplete"""

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

      lowercase_								= _resumable_file_manager
      if os.path.exists(__lowerCAmelCase							):
        lowercase_								= os.stat(__lowerCAmelCase							).st_size
      else:
        lowercase_								= 0
    else:
      lowercase_								= partial(tempfile.NamedTemporaryFile ,  dir=__lowerCAmelCase ,  delete=__lowerCAmelCase							)
      lowercase_								= 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							)

    lowercase_								= {"""url""": url, """etag""": etag}
    lowercase_								= cache_path + """.json"""
    with open(__lowerCAmelCase ,  """w"""							) as meta_file:
      json.dump(__lowerCAmelCase ,  __lowerCAmelCase							)

  return cache_path


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase=None							) ->						Union[str, Any]:







  '''simple docstring'''


  lowercase_								= url.encode("""utf-8"""							)
  lowercase_								= shaaaa(__lowerCAmelCase							)
  lowercase_								= url_hash.hexdigest()

  if etag:
    lowercase_								= etag.encode("""utf-8"""							)
    lowercase_								= 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 ,  ) ->						Dict:







  '''simple docstring'''


  if cache_dir is None:
    lowercase_								= TRANSFORMERS_CACHE
  if isinstance(__lowerCAmelCase ,  __lowerCAmelCase							):
    lowercase_								= str(__lowerCAmelCase							)
  if isinstance(__lowerCAmelCase ,  __lowerCAmelCase							):
    lowercase_								= str(__lowerCAmelCase							)

  if is_remote_url(__lowerCAmelCase							):
    # URL, so get it from the cache (downloading if necessary)
    lowercase_								= 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.
    lowercase_								= 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/"
    lowercase_					,    lowercase_								= os.path.split(__lowerCAmelCase							)
    lowercase_								= output_file.replace(""".""" ,  """-"""							) + """-extracted"""
    lowercase_								= 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
    lowercase_								= 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							):
        lowercase_								= 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=","							) ->						List[str]:







  '''simple docstring'''


  assert isinstance(__lowerCAmelCase ,  __lowerCAmelCase							)
  if os.path.isfile(__lowerCAmelCase							):
    with open(__lowerCAmelCase							) as f:
      lowercase_								= eval(f.read()							)
  else:
    lowercase_								= requests.get(__lowerCAmelCase							)
    try:
      lowercase_								= requests.json()
    except Exception:
      lowercase_								= req.content.decode()
      assert data is not None, "could not connect"
      try:
        lowercase_								= eval(__lowerCAmelCase							)
      except Exception:
        lowercase_								= data.split("""\n"""							)
    req.close()
  return data


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Dict:







  '''simple docstring'''


  lowercase_								= requests.get(__lowerCAmelCase							)
  lowercase_								= np.array(Image.open(BytesIO(response.content							)							)							)
  return img


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


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


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







  '''simple docstring'''


  print(F'''{os.path.abspath(os.path.join(__lowerCAmelCase ,  os.pardir							)							)}/demo.ipynb'''							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase="RGB"							) ->						Dict:







  '''simple docstring'''


  assert isinstance(__lowerCAmelCase ,  __lowerCAmelCase							)
  if os.path.isfile(__lowerCAmelCase							):
    lowercase_								= cva.imread(__lowerCAmelCase							)
  else:
    lowercase_								= get_image_from_url(__lowerCAmelCase							)
    assert img is not None, F'''could not connect to: {im}'''
  lowercase_								= cva.cvtColor(__lowerCAmelCase ,  cva.COLOR_BGR2RGB							)
  if input_format == "RGB":
    lowercase_								= img[:, :, ::-1]
  return img


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase=1							) ->						Optional[int]:







  '''simple docstring'''


  return (images[i : i + batch] for i in range(0 ,  len(__lowerCAmelCase							) ,  __lowerCAmelCase							))





"""simple docstring"""
def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						list[list[int]]:







  '''simple docstring'''


  lowercase_								= []
  if len(__lowerCAmelCase							) == 1:
    return [nums.copy()]
  for _ in range(len(__lowerCAmelCase							)							):
    lowercase_								= nums.pop(0							)
    lowercase_								= permute(__lowerCAmelCase							)
    for perm in permutations:
      perm.append(__lowerCAmelCase							)
    result.extend(__lowerCAmelCase							)
    nums.append(__lowerCAmelCase							)
  return result


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Tuple:







  '''simple docstring'''


  def backtrack(__lowerCAmelCase							):
    if start == len(__lowerCAmelCase							) - 1:
      output.append(nums[:]							)
    else:
      for i in range(__lowerCAmelCase ,  len(__lowerCAmelCase							)							):
        lowercase_					,    lowercase_								= nums[i], nums[start]
        backtrack(start + 1							)
        lowercase_					,    lowercase_								= nums[i], nums[start]  # backtrack

  lowercase_								= []
  backtrack(0							)
  return output


if __name__ == "__main__":
       import doctest

       # use res to print the data in permute2 function
       UpperCAmelCase						:		Optional[Any]			= permutea([1, 2, 3])
       print(res)
       doctest.testmod()

