
"""simple docstring"""







import requests

try:
  from django.contrib.auth import authenticate, login
  from django.shortcuts import redirect, render
except ImportError:
  SCREAMING_SNAKE_CASE_  					= print
def       __UpperCAmelCase		(		a_      :		List[str]					)  ->							Optional[int]:
   _UpperCAmelCase 						=       "secretKey"
   _UpperCAmelCase 						=       "https://www.google.com/recaptcha/api/siteverify"

   # when method is not POST, direct user to login page
   if request.method != "POST":
      return render(A__     ,	"login.html"					)

   # from the frontend, get username, password, and client_key
   _UpperCAmelCase 						=       request.POST.get("username"					)
   _UpperCAmelCase 						=       request.POST.get("password"					)
   _UpperCAmelCase 						=       request.POST.get("g-recaptcha-response"					)

   # post recaptcha response to Google's recaptcha api
   _UpperCAmelCase 						=       requests.post(A__     ,	data={"secret": secret_key, "response": client_key}					)
   # if the recaptcha api verified our keys
   if response.json().get("success"     ,	A__					):
      # authenticate the user
      _UpperCAmelCase 						=       authenticate(A__     ,	username=A__     ,	password=A__					)
      if user_in_database:
         login(A__     ,	A__					)
         return redirect("/your-webpage"					)
   return render(A__     ,	"login.html"					)




"""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

     SCREAMING_SNAKE_CASE_  :      List[str]							=      True
except ImportError:
     SCREAMING_SNAKE_CASE_  :      Tuple							=      False


try:
     from torch.hub import _get_torch_home

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

SCREAMING_SNAKE_CASE_  :      List[str]							=      os.path.join(torch_cache_home, '''transformers''')

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



def 						UpperCAmelCase__ (					A__=OBJECTS						,     A__=ATTRIBUTES )   ->   Union[str, Any]:




   """simple docstring"""
   lowerCamelCase__						       =      []
   with open(A__ ) as f:
      for object in f.readlines():
         vg_classes.append(object.split("," )[0].lower().strip() )

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



def 						UpperCAmelCase__ (					A__ )   ->   List[Any]:




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


class 		_A							:
      __a             =						{}





      def __init__(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__ = "root"     ,    SCREAMING_SNAKE_CASE__=0		) ->       int:
         lowerCamelCase__						       =      name
         lowerCamelCase__						       =      level
         lowerCamelCase__						       =      {}
         for k, v in dictionary.items():
            if v is None:
               raise ValueError()
            lowerCamelCase__						       =      copy.deepcopy(SCREAMING_SNAKE_CASE__		)
            lowerCamelCase__						       =      copy.deepcopy(SCREAMING_SNAKE_CASE__		)
            if isinstance(SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		):
               lowerCamelCase__						       =      Config(SCREAMING_SNAKE_CASE__     ,    name=SCREAMING_SNAKE_CASE__     ,    level=level + 1		)
            lowerCamelCase__						       =      v
            setattr(self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		)

         lowerCamelCase__						       =      d





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





      def __setattr__(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		) ->       int:
         lowerCamelCase__						       =      val
         lowerCamelCase__						       =      val
         lowerCamelCase__						       =      key.split("."		)
         lowerCamelCase__						       =      len(SCREAMING_SNAKE_CASE__		) - 1
         lowerCamelCase__						       =      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:
                  lowerCamelCase__						       =      val
               else:
                  lowerCamelCase__						       =      pointer[l]





      def        _lowerCamelCase	(	self		) ->       Optional[int]:
         return self._pointer





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		) ->       Optional[int]:
         with open(f'{file_name}'     ,    "w"		) as stream:
            dump(SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		)





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		) ->       Optional[Any]:
         with open(f'{file_name}'     ,    "w"		) as stream:
            json.dump(SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		)





      @staticmethod
      def        _lowerCamelCase	(	SCREAMING_SNAKE_CASE__		) ->       int:
         with open(SCREAMING_SNAKE_CASE__		) as stream:
            lowerCamelCase__						       =      load(SCREAMING_SNAKE_CASE__     ,    Loader=SCREAMING_SNAKE_CASE__		)
         return data





      def __str__(	self		) ->       Optional[int]:
         lowerCamelCase__						       =      "    "
         if self._name != "root":
            lowerCamelCase__						       =      f'{t * (self._level-1)}{self._name}:\n'
         else:
            lowerCamelCase__						       =      ""
         lowerCamelCase__						       =      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'
            lowerCamelCase__						       =      level
         return r[:-1]





      @classmethod
      def        _lowerCamelCase	(	cls     ,    SCREAMING_SNAKE_CASE__     ,    **SCREAMING_SNAKE_CASE__		) ->       Tuple:
         lowerCamelCase__       ,							lowerCamelCase__						       =      cls.get_config_dict(SCREAMING_SNAKE_CASE__     ,    **SCREAMING_SNAKE_CASE__		)
         return cls(SCREAMING_SNAKE_CASE__		)





      @classmethod
      def        _lowerCamelCase	(	cls     ,    SCREAMING_SNAKE_CASE__     ,    **SCREAMING_SNAKE_CASE__		) ->       Tuple:
         lowerCamelCase__						       =      kwargs.pop("cache_dir"     ,    SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						       =      kwargs.pop("force_download"     ,    SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						       =      kwargs.pop("resume_download"     ,    SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						       =      kwargs.pop("proxies"     ,    SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						       =      kwargs.pop("local_files_only"     ,    SCREAMING_SNAKE_CASE__		)

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

         try:
            # Load from URL or cache if already cached
            lowerCamelCase__						       =      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

            lowerCamelCase__						       =      Config.load_yaml(SCREAMING_SNAKE_CASE__		)

         except EnvironmentError:
            lowerCamelCase__						       =      "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 						UpperCAmelCase__ (					A__ )   ->   Dict:




   """simple docstring"""
   lowerCamelCase__						       =      torch.load("dump.pt"						,     map_location=in_tensor.device )
   lowerCamelCase__						       =      in_tensor.numpy()
   lowerCamelCase__						       =      out_tensor.numpy()[0]
   print(na.shape						,     na[0, 0, :5] )
   print(na.shape						,     na[0, 0, :5] )
   assert np.allclose(A__						,     A__						,     rtol=0.01						,     atol=0.1 ), (
       f'{sum([1 for x in np.isclose(A__						,     A__						,     rtol=0.01						,     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 						UpperCAmelCase__ (					A__ )   ->   Optional[Any]:




   """simple docstring"""
   lowerCamelCase__						       =      urlparse(A__ )
   return parsed.scheme in ("http", "https")



def 						UpperCAmelCase__ (					A__						,     A__						,     A__=True )   ->   str:




   """simple docstring"""
   lowerCamelCase__						       =      CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
   lowerCamelCase__						       =      "/" not in model_id
   if legacy_format:
      return f'{endpoint}/{model_id}-{filename}'
   else:
      return f'{endpoint}/{model_id}/{filename}'



def 						UpperCAmelCase__ (					A__						,     A__						,     A__=None						,     A__=0						,     A__=None						,     )   ->   Any:




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



def 						UpperCAmelCase__ (					A__						,     A__=None						,     A__=False						,     A__=None						,     A__=10						,     A__=False						,     A__=None						,     A__=False						,     )   ->   Dict:




   """simple docstring"""
   if cache_dir is None:
      lowerCamelCase__						       =      TRANSFORMERS_CACHE
   if isinstance(A__						,     A__ ):
      lowerCamelCase__						       =      str(A__ )

   os.makedirs(A__						,     exist_ok=A__ )

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

   lowerCamelCase__						       =      url_to_filename(A__						,     A__ )

   # get cache path to put the file
   lowerCamelCase__						       =      os.path.join(A__						,     A__ )

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

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

      if resume_download:
         lowerCamelCase__						       =      cache_path + ".incomplete"

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

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

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

      os.replace(temp_file.name						,     A__ )

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

   return cache_path



def 						UpperCAmelCase__ (					A__						,     A__=None )   ->   List[Any]:




   """simple docstring"""
   lowerCamelCase__						       =      url.encode("utf-8" )
   lowerCamelCase__						       =      shaaaa(A__ )
   lowerCamelCase__						       =      url_hash.hexdigest()

   if etag:
      lowerCamelCase__						       =      etag.encode("utf-8" )
      lowerCamelCase__						       =      shaaaa(A__ )
      filename += "." + etag_hash.hexdigest()

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

   return filename



def 						UpperCAmelCase__ (					A__						,     A__=None						,     A__=False						,     A__=None						,     A__=False						,     A__=None						,     A__=False						,     A__=False						,     A__=False						,     )   ->   Dict:




   """simple docstring"""
   if cache_dir is None:
      lowerCamelCase__						       =      TRANSFORMERS_CACHE
   if isinstance(A__						,     A__ ):
      lowerCamelCase__						       =      str(A__ )
   if isinstance(A__						,     A__ ):
      lowerCamelCase__						       =      str(A__ )

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

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

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

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

      return output_path_extracted

   return output_path



def 						UpperCAmelCase__ (					A__						,     A__="," )   ->   Optional[int]:




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



def 						UpperCAmelCase__ (					A__ )   ->   int:




   """simple docstring"""
   lowerCamelCase__						       =      requests.get(A__ )
   lowerCamelCase__						       =      np.array(Image.open(BytesIO(response.content ) ) )
   return img



def 						UpperCAmelCase__ (					A__ )   ->   int:




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



def 						UpperCAmelCase__ (					)   ->   List[Any]:




   """simple docstring"""
   print(f'{os.path.abspath(os.path.join(A__						,     os.pardir ) )}/demo.ipynb' )



def 						UpperCAmelCase__ (					A__						,     A__="RGB" )   ->   Any:




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



def 						UpperCAmelCase__ (					A__						,     A__=1 )   ->   Optional[int]:




   """simple docstring"""
   return (images[i : i + batch] for i in range(0						,     len(A__ )						,     A__ ))




