





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

  lowerCamelCase_								=		True
except ImportError:
  lowerCamelCase_								=		False


try:
  from torch.hub import _get_torch_home

  lowerCamelCase_								=		_get_torch_home()
except ImportError:
  lowerCamelCase_								=		os.path.expanduser(
      os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch"))
  )

lowerCamelCase_								=		os.path.join(torch_cache_home, "transformers")

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



def      __lowerCamelCase   (							a_     :		Optional[int]=OBJECTS ,   a_     :		Dict=ATTRIBUTES							)			->      Union[str, Any]:
      __SCREAMING_SNAKE_CASE   :int						=  []
      with open(a_							) as f:
            for object in f.readlines():
                  vg_classes.append(object.split(''','''							)[0].lower().strip()							)

      __SCREAMING_SNAKE_CASE   :List[Any]						=  []
      with open(a_							) as f:
            for object in f.readlines():
                  vg_attrs.append(object.split(''','''							)[0].lower().strip()							)
      return vg_classes, vg_attrs



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






class 					_SCREAMING_SNAKE_CASE:
       SCREAMING_SNAKE_CASE_   :      str							=  {}




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = "root"		,SCREAMING_SNAKE_CASE__=0							)			->      int:





             """simple docstring"""






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

             __SCREAMING_SNAKE_CASE   :Tuple						=  d




       def __repr__(						self							)			->      List[Any]:





             """simple docstring"""






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




       def __setattr__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  val
             __SCREAMING_SNAKE_CASE   :Dict						=  val
             __SCREAMING_SNAKE_CASE   :Dict						=  key.split('''.'''							)
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  len(SCREAMING_SNAKE_CASE__							) - 1
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  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:
                               __SCREAMING_SNAKE_CASE   :List[Any]						=  val
                         else:
                               __SCREAMING_SNAKE_CASE   :str						=  pointer[l]




       def     _UpperCamelCase     (						self							)			->      Optional[Any]:





             """simple docstring"""






             return self._pointer




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      Any:





             """simple docstring"""






             with open(f'''{file_name}'''		,'''w'''							) as stream:
                   dump(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      List[Any]:





             """simple docstring"""






             with open(f'''{file_name}'''		,'''w'''							) as stream:
                   json.dump(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @staticmethod
       def     _UpperCamelCase     (						SCREAMING_SNAKE_CASE__							)			->      str:





             """simple docstring"""






             with open(SCREAMING_SNAKE_CASE__							) as stream:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  load(SCREAMING_SNAKE_CASE__		,Loader=SCREAMING_SNAKE_CASE__							)
             return data




       def __str__(						self							)			->      Optional[Any]:





             """simple docstring"""






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




       @classmethod
       def     _UpperCamelCase     (						cls		,SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :str						=  cls.get_config_dict(SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)
             return cls(SCREAMING_SNAKE_CASE__							)




       @classmethod
       def     _UpperCamelCase     (						cls		,SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)			->      List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  kwargs.pop('''cache_dir'''		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  kwargs.pop('''force_download'''		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Any						=  kwargs.pop('''resume_download'''		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  kwargs.pop('''proxies'''		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Any						=  kwargs.pop('''local_files_only'''		,SCREAMING_SNAKE_CASE__							)

             if os.path.isdir(SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  os.path.join(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             elif os.path.isfile(SCREAMING_SNAKE_CASE__							) or is_remote_url(SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :str						=  pretrained_model_name_or_path
             else:
                   __SCREAMING_SNAKE_CASE   :Union[str, 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
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  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

                   __SCREAMING_SNAKE_CASE   :int						=  Config.load_yaml(SCREAMING_SNAKE_CASE__							)

             except EnvironmentError:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  '''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      __lowerCamelCase   (							a_     :		List[Any]							)			->      Optional[int]:
      __SCREAMING_SNAKE_CASE   :int						=  torch.load('''dump.pt''' ,   map_location=in_tensor.device							)
      __SCREAMING_SNAKE_CASE   :Tuple						=  in_tensor.numpy()
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  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()							)*1_00:.4f} %'''
          " element-wise mismatch"
      )
      raise Exception('''tensors are all good'''							)

      # Hugging face functions below



def      __lowerCamelCase   (							a_     :		Any							)			->      int:
      __SCREAMING_SNAKE_CASE   :Any						=  urlparse(a_							)
      return parsed.scheme in ("http", "https")



def      __lowerCamelCase   (							a_     :		str ,   a_     :		str ,   a_     :		Union[str, Any]=True							)			->      str:
      __SCREAMING_SNAKE_CASE   :List[str]						=  CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  '''/''' not in model_id
      if legacy_format:
            return f'''{endpoint}/{model_id}-{filename}'''
      else:
            return f'''{endpoint}/{model_id}/{filename}'''



def      __lowerCamelCase   (							a_     :		List[Any] ,   a_     :		List[str] ,   a_     :		Optional[Any]=None ,   a_     :		Optional[int]=0 ,   a_     :		List[Any]=None ,   )			->      Optional[int]:
      __SCREAMING_SNAKE_CASE   :Tuple						=  '''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
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  {'''user-agent''': ua}
      if resume_size > 0:
            __SCREAMING_SNAKE_CASE   :Optional[int]						=  '''bytes=%d-''' % (resume_size,)
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  requests.get(a_ ,   stream=a_ ,   proxies=a_ ,   headers=a_							)
      if response.status_code == 4_16:  # Range not satisfiable
            return
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  response.headers.get('''Content-Length'''							)
      __SCREAMING_SNAKE_CASE   :Any						=  resume_size + int(a_							) if content_length is not None else None
      __SCREAMING_SNAKE_CASE   :Dict						=  tqdm(
          unit='''B''' ,   unit_scale=a_ ,   total=a_ ,   initial=a_ ,   desc='''Downloading''' ,   )
      for chunk in response.iter_content(chunk_size=10_24							):
            if chunk:  # filter out keep-alive new chunks
                  progress.update(len(a_							)							)
                  temp_file.write(a_							)
      progress.close()



def      __lowerCamelCase   (							a_     :		Optional[int] ,   a_     :		Optional[Any]=None ,   a_     :		Dict=False ,   a_     :		Any=None ,   a_     :		Union[str, Any]=10 ,   a_     :		Optional[Any]=False ,   a_     :		Optional[int]=None ,   a_     :		str=False ,   )			->      Optional[Any]:
      if cache_dir is None:
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TRANSFORMERS_CACHE
      if isinstance(a_ ,   a_							):
            __SCREAMING_SNAKE_CASE   :Dict						=  str(a_							)

      os.makedirs(a_ ,   exist_ok=a_							)

      __SCREAMING_SNAKE_CASE   :Any						=  None
      if not local_files_only:
            try:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  requests.head(a_ ,   allow_redirects=a_ ,   proxies=a_ ,   timeout=a_							)
                  if response.status_code == 2_00:
                        __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  response.headers.get('''ETag'''							)
            except (EnvironmentError, requests.exceptions.Timeout):
                  # etag is already None
                  pass

      __SCREAMING_SNAKE_CASE   :List[str]						=  url_to_filename(a_ ,   a_							)

      # get cache path to put the file
      __SCREAMING_SNAKE_CASE   :int						=  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:
                  __SCREAMING_SNAKE_CASE   :Tuple						=  [
                      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.
      __SCREAMING_SNAKE_CASE   :Tuple						=  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:
                  __SCREAMING_SNAKE_CASE   :Any						=  cache_path + '''.incomplete'''

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

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

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

            os.replace(temp_file.name ,   a_							)

            __SCREAMING_SNAKE_CASE   :int						=  {'''url''': url, '''etag''': etag}
            __SCREAMING_SNAKE_CASE   :List[str]						=  cache_path + '''.json'''
            with open(a_ ,   '''w'''							) as meta_file:
                  json.dump(a_ ,   a_							)

      return cache_path



def      __lowerCamelCase   (							a_     :		Union[str, Any] ,   a_     :		Optional[int]=None							)			->      Any:
      __SCREAMING_SNAKE_CASE   :Any						=  url.encode('''utf-8'''							)
      __SCREAMING_SNAKE_CASE   :List[Any]						=  shaaaa(a_							)
      __SCREAMING_SNAKE_CASE   :List[Any]						=  url_hash.hexdigest()

      if etag:
            __SCREAMING_SNAKE_CASE   :Any						=  etag.encode('''utf-8'''							)
            __SCREAMING_SNAKE_CASE   :List[Any]						=  shaaaa(a_							)
            filename += "." + etag_hash.hexdigest()

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

      return filename



def      __lowerCamelCase   (							a_     :		str ,   a_     :		List[str]=None ,   a_     :		List[str]=False ,   a_     :		int=None ,   a_     :		int=False ,   a_     :		Any=None ,   a_     :		Tuple=False ,   a_     :		str=False ,   a_     :		Any=False ,   )			->      List[str]:
      if cache_dir is None:
            __SCREAMING_SNAKE_CASE   :List[str]						=  TRANSFORMERS_CACHE
      if isinstance(a_ ,   a_							):
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  str(a_							)
      if isinstance(a_ ,   a_							):
            __SCREAMING_SNAKE_CASE   :int						=  str(a_							)

      if is_remote_url(a_							):
            # URL, so get it from the cache (downloading if necessary)
            __SCREAMING_SNAKE_CASE   :Any						=  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.
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  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/"
            __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Any						=  os.path.split(a_							)
            __SCREAMING_SNAKE_CASE   :List[str]						=  output_file.replace('''.''' ,   '''-'''							) + '''-extracted'''
            __SCREAMING_SNAKE_CASE   :Optional[int]						=  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
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  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_							):
                        __SCREAMING_SNAKE_CASE   :List[str]						=  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      __lowerCamelCase   (							a_     :		List[Any] ,   a_     :		int=","							)			->      str:
      assert isinstance(a_ ,   a_							)
      if os.path.isfile(a_							):
            with open(a_							) as f:
                  __SCREAMING_SNAKE_CASE   :List[Any]						=  eval(f.read()							)
      else:
            __SCREAMING_SNAKE_CASE   :List[Any]						=  requests.get(a_							)
            try:
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  requests.json()
            except Exception:
                  __SCREAMING_SNAKE_CASE   :Any						=  req.content.decode()
                  assert data is not None, "could not connect"
                  try:
                        __SCREAMING_SNAKE_CASE   :int						=  eval(a_							)
                  except Exception:
                        __SCREAMING_SNAKE_CASE   :Any						=  data.split('''\n'''							)
            req.close()
      return data



def      __lowerCamelCase   (							a_     :		List[str]							)			->      str:
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  requests.get(a_							)
      __SCREAMING_SNAKE_CASE   :str						=  np.array(Image.open(BytesIO(response.content							)							)							)
      return img



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



def      __lowerCamelCase   (							)			->      Dict:
      print(f'''{os.path.abspath(os.path.join(a_ ,   os.pardir							)							)}/demo.ipynb'''							)



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







def      __lowerCamelCase   (							a_     :		Union[str, Any] ,   a_     :		Optional[int]=1							)			->      Any:
      return (images[i : i + batch] for i in range(0 ,   len(a_							) ,   a_							))






"""simple docstring"""
from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
  from transformers import (
      TFAutoModel,
      TFAutoModelForCausalLM,
      TFAutoModelForMaskedLM,
      TFAutoModelForPreTraining,
      TFAutoModelForQuestionAnswering,
      TFAutoModelForSeqaSeqLM,
      TFAutoModelForSequenceClassification,
      TFAutoModelForTableQuestionAnswering,
      TFAutoModelForTokenClassification,
      TFAutoModelWithLMHead,
      TFBertForMaskedLM,
      TFBertForPreTraining,
      TFBertForQuestionAnswering,
      TFBertForSequenceClassification,
      TFBertModel,
      TFFunnelBaseModel,
      TFFunnelModel,
      TFGPTaLMHeadModel,
      TFRobertaForMaskedLM,
      TFTaForConditionalGeneration,
      TFTapasForQuestionAnswering,
  )
  from transformers.models.auto.modeling_tf_auto import (
      TF_MODEL_FOR_CAUSAL_LM_MAPPING,
      TF_MODEL_FOR_MASKED_LM_MAPPING,
      TF_MODEL_FOR_PRETRAINING_MAPPING,
      TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
      TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
      TF_MODEL_MAPPING,
  )
  from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      int							=  '''new-model'''


if is_tf_available():






  class 					_SCREAMING_SNAKE_CASE(   A  ):
         SCREAMING_SNAKE_CASE_   :      Union[str, Any]							=  NewModelConfig






@require_tf
class 					_SCREAMING_SNAKE_CASE(   unittest.TestCase  ):




       @slow
       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Any						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Optional[int]:





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       @require_tensorflow_probability
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
                   __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(
                       SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny'''							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  copy.deepcopy(model.config							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  ['''FunnelBaseModel''']
             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_config(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             with tempfile.TemporaryDirectory() as tmp_dir:
                   model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self							)			->      Optional[Any]:





             """simple docstring"""






             try:
                   AutoConfig.register('''new-model'''		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  [
                       TFAutoModel,
                       TFAutoModelForCausalLM,
                       TFAutoModelForMaskedLM,
                       TFAutoModelForPreTraining,
                       TFAutoModelForQuestionAnswering,
                       TFAutoModelForSequenceClassification,
                       TFAutoModelForTokenClassification,
                   ]

                   for auto_class in auto_classes:
                         with self.subTest(auto_class.__name__							):
                               # Wrong config class will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               # Trying to register something existing in the Transformers library will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               # Now that the config is registered, it can be used as any other config with the auto-API
                               __SCREAMING_SNAKE_CASE   :Any						=  BertModelTester(self							).get_config()
                               __SCREAMING_SNAKE_CASE   :Dict						=  NewModelConfig(**tiny_config.to_dict()							)
                               __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  auto_class.from_config(SCREAMING_SNAKE_CASE__							)
                               self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               with tempfile.TemporaryDirectory() as tmp_dir:
                                     model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                                     __SCREAMING_SNAKE_CASE   :str						=  auto_class.from_pretrained(SCREAMING_SNAKE_CASE__							)
                                     self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             finally:
                   if "new-model" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["new-model"]
                   for mapping in (
                       TF_MODEL_MAPPING,
                       TF_MODEL_FOR_PRETRAINING_MAPPING,
                       TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
                       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_CAUSAL_LM_MAPPING,
                       TF_MODEL_FOR_MASKED_LM_MAPPING,
                   ):
                         if NewModelConfig in mapping._extra_content:
                               del mapping._extra_content[NewModelConfig]




       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''bert-base is not a local folder and is not a valid model identifier'''							):
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''bert-base'''							)




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''							):
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__		,revision='''aaaaaa'''							)




       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin'''		,):
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model'''							)




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__		,'''Use `from_pt=True` to load this model'''							):
                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only'''							)




       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)

             # With a sharded checkpoint
             __SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)