


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

 __a	 =      True
except ImportError:
 __a	 =      False


try:
 from torch.hub import _get_torch_home

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

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

__a	 =      """https://cdn.huggingface.co"""
__a	 =      """https://s3.amazonaws.com/models.huggingface.co/bert"""
__a	 =      """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
__a	 =      os.path.join(PATH, """config.yaml""")
__a	 =      os.path.join(PATH, """attributes.txt""")
__a	 =      os.path.join(PATH, """objects.txt""")
__a	 =      os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
__a	 =      os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
__a	 =      os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
__a	 =      """pytorch_model.bin"""
__a	 =      """config.yaml"""
def 	_UpperCamelCase					(    lowerCAmelCase_=OBJECTS	,    lowerCAmelCase_=ATTRIBUTES )    ->str:
   UpperCAmelCase      					=  []
   with open(lowerCAmelCase_ ) as f:
      for object in f.readlines():
         vg_classes.append(object.split(""",""" )[0].lower().strip() )

   UpperCAmelCase      					=  []
   with open(lowerCAmelCase_ ) as f:
      for object in f.readlines():
         vg_attrs.append(object.split(""",""" )[0].lower().strip() )
   return vg_classes, vg_attrs
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Tuple:
   UpperCAmelCase      					=  OrderedDict()
   with open(lowerCAmelCase_	,    """rb""" ) as f:
      UpperCAmelCase      					=  pkl.load(lowerCAmelCase_ )["""model"""]
   for k in copy.deepcopy(list(ckp.keys() ) ):
      UpperCAmelCase      					=  ckp.pop(lowerCAmelCase_ )
      if isinstance(lowerCAmelCase_	,    np.ndarray ):
         UpperCAmelCase      					=  torch.tensor(lowerCAmelCase_ )
      else:
         assert isinstance(lowerCAmelCase_	,    torch.tensor ), type(lowerCAmelCase_ )
      UpperCAmelCase      					=  v
   return r






class 	__lowercase					:
      UpperCamelCase										=							{}





      def __init__(		self    :       Union[str, Any]       ,							__lowerCamelCase    :       dict       ,							__lowerCamelCase    :       str = "root"       ,							__lowerCamelCase    :       List[str]=0							)     -> Dict:






         """simple docstring"""







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

         UpperCAmelCase      					=  d





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






         """simple docstring"""







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





      def __setattr__(		self    :       Optional[Any]       ,							__lowerCamelCase    :       Optional[Any]       ,							__lowerCamelCase    :       List[str]							)     -> int:






         """simple docstring"""







         UpperCAmelCase      					=  val
         UpperCAmelCase      					=  val
         UpperCAmelCase      					=  key.split("""."""							)
         UpperCAmelCase      					=  len(__lowerCamelCase							) - 1
         UpperCAmelCase      					=  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:
                  UpperCAmelCase      					=  val
               else:
                  UpperCAmelCase      					=  pointer[l]





      def 							_lowercase					(		self    :       Tuple							)     -> int:






         """simple docstring"""







         return self._pointer





      def 							_lowercase					(		self    :       int       ,							__lowerCamelCase    :       List[str]       ,							__lowerCamelCase    :       str							)     -> str:






         """simple docstring"""







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





      def 							_lowercase					(		self    :       List[str]       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Optional[Any]							)     -> Dict:






         """simple docstring"""







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





      @staticmethod
      def 							_lowercase					(		__lowerCamelCase    :       List[str]							)     -> List[Any]:






         """simple docstring"""







         with open(__lowerCamelCase							) as stream:
            UpperCAmelCase      					=  load(__lowerCamelCase       ,							Loader=__lowerCamelCase							)
         return data





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






         """simple docstring"""







         UpperCAmelCase      					=  """    """
         if self._name != "root":
            UpperCAmelCase      					=  F"""{t * (self._level-1)}{self._name}:\n"""
         else:
            UpperCAmelCase      					=  """"""
         UpperCAmelCase      					=  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"""
            UpperCAmelCase      					=  level
         return r[:-1]





      @classmethod
      def 							_lowercase					(		cls    :       List[Any]       ,							__lowerCamelCase    :       str       ,							**__lowerCamelCase    :       List[Any]							)     -> str:






         """simple docstring"""







         UpperCAmelCase					,	UpperCAmelCase      					=  cls.get_config_dict(__lowerCamelCase       ,							**__lowerCamelCase							)
         return cls(__lowerCamelCase							)





      @classmethod
      def 							_lowercase					(		cls    :       Tuple       ,							__lowerCamelCase    :       str       ,							**__lowerCamelCase    :       Tuple							)     -> Optional[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  kwargs.pop("""cache_dir"""       ,							__lowerCamelCase							)
         UpperCAmelCase      					=  kwargs.pop("""force_download"""       ,							__lowerCamelCase							)
         UpperCAmelCase      					=  kwargs.pop("""resume_download"""       ,							__lowerCamelCase							)
         UpperCAmelCase      					=  kwargs.pop("""proxies"""       ,							__lowerCamelCase							)
         UpperCAmelCase      					=  kwargs.pop("""local_files_only"""       ,							__lowerCamelCase							)

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

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

            UpperCAmelCase      					=  Config.load_yaml(__lowerCamelCase							)

         except EnvironmentError:
            UpperCAmelCase      					=  """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 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Optional[Any]:
   UpperCAmelCase      					=  torch.load("""dump.pt"""	,    map_location=in_tensor.device )
   UpperCAmelCase      					=  in_tensor.numpy()
   UpperCAmelCase      					=  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_0_0:.4f} %"""
       " element-wise mismatch"
   )
   raise Exception("""tensors are all good""" )

   # Hugging face functions below
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Optional[Any]:
   UpperCAmelCase      					=  urlparse(lowerCAmelCase_ )
   return parsed.scheme in ("http", "https")
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_=True )    ->str:
   UpperCAmelCase      					=  CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
   UpperCAmelCase      					=  """/""" not in model_id
   if legacy_format:
      return F"""{endpoint}/{model_id}-{filename}"""
   else:
      return F"""{endpoint}/{model_id}/{filename}"""
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_=None	,    lowerCAmelCase_=0	,    lowerCAmelCase_=None	,    )    ->Optional[Any]:
   UpperCAmelCase      					=  """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      					=  {"""user-agent""": ua}
   if resume_size > 0:
      UpperCAmelCase      					=  """bytes=%d-""" % (resume_size,)
   UpperCAmelCase      					=  requests.get(lowerCAmelCase_	,    stream=lowerCAmelCase_	,    proxies=lowerCAmelCase_	,    headers=lowerCAmelCase_ )
   if response.status_code == 4_1_6:  # Range not satisfiable
      return
   UpperCAmelCase      					=  response.headers.get("""Content-Length""" )
   UpperCAmelCase      					=  resume_size + int(lowerCAmelCase_ ) if content_length is not None else None
   UpperCAmelCase      					=  tqdm(
       unit="""B"""	,    unit_scale=lowerCAmelCase_	,    total=lowerCAmelCase_	,    initial=lowerCAmelCase_	,    desc="""Downloading"""	,    )
   for chunk in response.iter_content(chunk_size=1_0_2_4 ):
      if chunk:  # filter out keep-alive new chunks
         progress.update(len(lowerCAmelCase_ ) )
         temp_file.write(lowerCAmelCase_ )
   progress.close()
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=None	,    lowerCAmelCase_=False	,    lowerCAmelCase_=None	,    lowerCAmelCase_=1_0	,    lowerCAmelCase_=False	,    lowerCAmelCase_=None	,    lowerCAmelCase_=False	,    )    ->Union[str, Any]:
   if cache_dir is None:
      UpperCAmelCase      					=  TRANSFORMERS_CACHE
   if isinstance(lowerCAmelCase_	,    lowerCAmelCase_ ):
      UpperCAmelCase      					=  str(lowerCAmelCase_ )

   os.makedirs(lowerCAmelCase_	,    exist_ok=lowerCAmelCase_ )

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

   UpperCAmelCase      					=  url_to_filename(lowerCAmelCase_	,    lowerCAmelCase_ )

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

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

         UpperCAmelCase      					=  _resumable_file_manager
         if os.path.exists(lowerCAmelCase_ ):
            UpperCAmelCase      					=  os.stat(lowerCAmelCase_ ).st_size
         else:
            UpperCAmelCase      					=  0
      else:
         UpperCAmelCase      					=  partial(tempfile.NamedTemporaryFile	,    dir=lowerCAmelCase_	,    delete=lowerCAmelCase_ )
         UpperCAmelCase      					=  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      					=  {"""url""": url, """etag""": etag}
      UpperCAmelCase      					=  cache_path + """.json"""
      with open(lowerCAmelCase_	,    """w""" ) as meta_file:
         json.dump(lowerCAmelCase_	,    lowerCAmelCase_ )

   return cache_path
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=None )    ->Union[str, Any]:
   UpperCAmelCase      					=  url.encode("""utf-8""" )
   UpperCAmelCase      					=  shaaaa(lowerCAmelCase_ )
   UpperCAmelCase      					=  url_hash.hexdigest()

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

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

   return filename
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=None	,    lowerCAmelCase_=False	,    lowerCAmelCase_=None	,    lowerCAmelCase_=False	,    lowerCAmelCase_=None	,    lowerCAmelCase_=False	,    lowerCAmelCase_=False	,    lowerCAmelCase_=False	,    )    ->List[Any]:
   if cache_dir is None:
      UpperCAmelCase      					=  TRANSFORMERS_CACHE
   if isinstance(lowerCAmelCase_	,    lowerCAmelCase_ ):
      UpperCAmelCase      					=  str(lowerCAmelCase_ )
   if isinstance(lowerCAmelCase_	,    lowerCAmelCase_ ):
      UpperCAmelCase      					=  str(lowerCAmelCase_ )

   if is_remote_url(lowerCAmelCase_ ):
      # URL, so get it from the cache (downloading if necessary)
      UpperCAmelCase      					=  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      					=  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      					=  os.path.split(lowerCAmelCase_ )
      UpperCAmelCase      					=  output_file.replace("""."""	,    """-""" ) + """-extracted"""
      UpperCAmelCase      					=  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      					=  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      					=  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 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_="," )    ->Union[str, Any]:
   assert isinstance(lowerCAmelCase_	,    lowerCAmelCase_ )
   if os.path.isfile(lowerCAmelCase_ ):
      with open(lowerCAmelCase_ ) as f:
         UpperCAmelCase      					=  eval(f.read() )
   else:
      UpperCAmelCase      					=  requests.get(lowerCAmelCase_ )
      try:
         UpperCAmelCase      					=  requests.json()
      except Exception:
         UpperCAmelCase      					=  req.content.decode()
         assert data is not None, "could not connect"
         try:
            UpperCAmelCase      					=  eval(lowerCAmelCase_ )
         except Exception:
            UpperCAmelCase      					=  data.split("""\n""" )
      req.close()
   return data
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   UpperCAmelCase      					=  requests.get(lowerCAmelCase_ )
   UpperCAmelCase      					=  np.array(Image.open(BytesIO(response.content ) ) )
   return img
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Tuple:
   UpperCAmelCase      					=  url.split("""/""" )[-1]
   if fn not in os.listdir(os.getcwd() ):
      wget.download(lowerCAmelCase_ )
   with open(lowerCAmelCase_	,    """rb""" ) as stream:
      UpperCAmelCase      					=  pkl.load(lowerCAmelCase_ )
   UpperCAmelCase      					=  weights.pop("""model""" )
   UpperCAmelCase      					=  {}
   for k, v in model.items():
      UpperCAmelCase      					=  torch.from_numpy(lowerCAmelCase_ )
      if "running_var" in k:
         UpperCAmelCase      					=  torch.tensor([0] )
         UpperCAmelCase      					=  k.replace("""running_var"""	,    """num_batches_tracked""" )
         UpperCAmelCase      					=  zero
   return new
def 	_UpperCamelCase					(    )    ->Any:
   print(F"""{os.path.abspath(os.path.join(lowerCAmelCase_	,    os.pardir ) )}/demo.ipynb""" )
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_="RGB" )    ->List[str]:
   assert isinstance(lowerCAmelCase_	,    lowerCAmelCase_ )
   if os.path.isfile(lowerCAmelCase_ ):
      UpperCAmelCase      					=  cva.imread(lowerCAmelCase_ )
   else:
      UpperCAmelCase      					=  get_image_from_url(lowerCAmelCase_ )
      assert img is not None, F"""could not connect to: {im}"""
   UpperCAmelCase      					=  cva.cvtColor(lowerCAmelCase_	,    cva.COLOR_BGR2RGB )
   if input_format == "RGB":
      UpperCAmelCase      					=  img[:, :, ::-1]
   return img







def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=1 )    ->List[Any]:
   return (images[i : i + batch] for i in range(0	,    len(lowerCAmelCase_ )	,    lowerCAmelCase_ ))







import argparse
import os
import re

import packaging.version


__a	 =      """examples/"""
__a	 =      {
    """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""),
    """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""),
    """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""),
    """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""),
}
__a	 =      {
    """init""": """src/diffusers/__init__.py""",
    """setup""": """setup.py""",
}
__a	 =      """README.md"""
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[Any]:
   with open(lowerCAmelCase_	,    """r"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      UpperCAmelCase      					=  f.read()
   UpperCAmelCase					,	UpperCAmelCase      					=  REPLACE_PATTERNS[pattern]
   UpperCAmelCase      					=  replace.replace("""VERSION"""	,    lowerCAmelCase_ )
   UpperCAmelCase      					=  re_pattern.sub(lowerCAmelCase_	,    lowerCAmelCase_ )
   with open(lowerCAmelCase_	,    """w"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      f.write(lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   for folder, directories, fnames in os.walk(lowerCAmelCase_ ):
      # Removing some of the folders with non-actively maintained examples from the walk
      if "research_projects" in directories:
         directories.remove("""research_projects""" )
      if "legacy" in directories:
         directories.remove("""legacy""" )
      for fname in fnames:
         if fname.endswith(""".py""" ):
            update_version_in_file(os.path.join(lowerCAmelCase_	,    lowerCAmelCase_ )	,    lowerCAmelCase_	,    pattern="""examples""" )
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=False )    ->Optional[int]:
   for pattern, fname in REPLACE_FILES.items():
      update_version_in_file(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
   if not patch:
      update_version_in_examples(lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->List[str]:
   UpperCAmelCase      					=  """🤗 Transformers currently provides the following architectures"""
   UpperCAmelCase      					=  """1. Want to contribute a new model?"""
   with open(lowerCAmelCase_	,    """r"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      UpperCAmelCase      					=  f.readlines()

   # Find the start of the list.
   UpperCAmelCase      					=  0
   while not lines[start_index].startswith(_start_prompt ):
      start_index += 1
   start_index += 1

   UpperCAmelCase      					=  start_index
   # Update the lines in the model list.
   while not lines[index].startswith(_end_prompt ):
      if lines[index].startswith("""1.""" ):
         UpperCAmelCase      					=  lines[index].replace(
             """https://huggingface.co/docs/diffusers/main/model_doc"""	,    """https://huggingface.co/docs/diffusers/model_doc"""	,    )
      index += 1

   with open(lowerCAmelCase_	,    """w"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      f.writelines(lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->List[str]:
   with open(REPLACE_FILES["""init"""]	,    """r""" ) as f:
      UpperCAmelCase      					=  f.read()
   UpperCAmelCase      					=  REPLACE_PATTERNS["""init"""][0].search(lowerCAmelCase_ ).groups()[0]
   return packaging.version.parse(lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_=False )    ->int:
   UpperCAmelCase      					=  get_version()
   if patch and default_version.is_devrelease:
      raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" )
   if default_version.is_devrelease:
      UpperCAmelCase      					=  default_version.base_version
   elif patch:
      UpperCAmelCase      					=  F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
   else:
      UpperCAmelCase      					=  F"""{default_version.major}.{default_version.minor + 1}.0"""

   # Now let's ask nicely if that's the right one.
   UpperCAmelCase      					=  input(F"""Which version are you releasing? [{default_version}]""" )
   if len(lowerCAmelCase_ ) == 0:
      UpperCAmelCase      					=  default_version

   print(F"""Updating version to {version}.""" )
   global_version_update(lowerCAmelCase_	,    patch=lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->int:
   UpperCAmelCase      					=  get_version()
   UpperCAmelCase      					=  F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
   UpperCAmelCase      					=  current_version.base_version

   # Check with the user we got that right.
   UpperCAmelCase      					=  input(F"""Which version are we developing now? [{dev_version}]""" )
   if len(lowerCAmelCase_ ) == 0:
      UpperCAmelCase      					=  dev_version

   print(F"""Updating version to {version}.""" )
   global_version_update(lowerCAmelCase_ )


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
 __a	 =      argparse.ArgumentParser()
 parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""")
 parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""")
 __a	 =      parser.parse_args()
 if not args.post_release:
  pre_release_work(patch=args.patch)
 elif args.patch:
  print("""Nothing to do after a patch :-)""")
 else:
  post_release_work()



