





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

   _lowercase       						=			True
except ImportError:
   _lowercase       						=			False


try:
   from torch.hub import _get_torch_home

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

_lowercase       						=			os.path.join(torch_cache_home, 'transformers')

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

def    __UpperCamelCase	(	a    : Tuple=OBJECTS					,   a    : List[Any]=ATTRIBUTES     ) ->Dict:
 snake_case				=			[]
 with open(_lowercase     ) as f:
  for object in f.readlines():
   vg_classes.append(object.split(''','''     )[0].lower().strip()     )

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

def    __UpperCamelCase	(	a    : int     ) ->Dict:
 snake_case				=			OrderedDict()
 with open(_lowercase					,   '''rb'''     ) as f:
  snake_case				=			pkl.load(_lowercase     )['''model''']
 for k in copy.deepcopy(list(ckp.keys()     )     ):
  snake_case				=			ckp.pop(_lowercase     )
  if isinstance(_lowercase					,   np.ndarray     ):
   snake_case				=			torch.tensor(_lowercase     )
  else:
   assert isinstance(_lowercase					,   torch.tensor     ), type(_lowercase     )
  snake_case				=			v
 return r
class 			_lowercase						:
     _UpperCAmelCase										=					{}







     def __init__( self    ,   A__    ,   A__ = "root"    ,   A__=0    ) ->	List[Any]:
      snake_case				=			name
      snake_case				=			level
      snake_case				=			{}
      for k, v in dictionary.items():
       if v is None:
        raise ValueError()
       snake_case				=			copy.deepcopy(UpperCamelCase__    )
       snake_case				=			copy.deepcopy(UpperCamelCase__    )
       if isinstance(UpperCamelCase__    ,   UpperCamelCase__    ):
        snake_case				=			Config(UpperCamelCase__    ,   name=UpperCamelCase__    ,   level=level + 1    )
       snake_case				=			v
       setattr(self    ,   UpperCamelCase__    ,   UpperCamelCase__    )

      snake_case				=			d







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







     def __setattr__( self    ,   A__    ,   A__    ) ->	List[str]:
      snake_case				=			val
      snake_case				=			val
      snake_case				=			key.split('''.'''    )
      snake_case				=			len(UpperCamelCase__    ) - 1
      snake_case				=			self._pointer
      if len(UpperCamelCase__    ) > 1:
       for i, l in enumerate(UpperCamelCase__    ):
        if hasattr(self    ,   UpperCamelCase__    ) and isinstance(getattr(self    ,   UpperCamelCase__    )    ,   UpperCamelCase__    ):
         setattr(getattr(self    ,   UpperCamelCase__    )    ,   '''.'''.join(levels[i:]    )    ,   UpperCamelCase__    )
        if l == last_level:
         snake_case				=			val
        else:
         snake_case				=			pointer[l]







     def     UpperCamelCase			( self    ) ->	List[Any]:
      return self._pointer







     def     UpperCamelCase			( self    ,   A__    ,   A__    ) ->	Tuple:





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







     def     UpperCamelCase			( self    ,   A__    ,   A__    ) ->	Any:





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







     @staticmethod
     def     UpperCamelCase			( A__    ) ->	Any:





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







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







     @classmethod
     def     UpperCamelCase			( cls    ,   A__    ,   **A__    ) ->	List[Any]:
      snake_case				=			cls.get_config_dict(UpperCamelCase__    ,   **UpperCamelCase__    )
      return cls(UpperCamelCase__    )







     @classmethod
     def     UpperCamelCase			( cls    ,   A__    ,   **A__    ) ->	Union[str, Any]:
      snake_case				=			kwargs.pop('''cache_dir'''    ,   UpperCamelCase__    )
      snake_case				=			kwargs.pop('''force_download'''    ,   UpperCamelCase__    )
      snake_case				=			kwargs.pop('''resume_download'''    ,   UpperCamelCase__    )
      snake_case				=			kwargs.pop('''proxies'''    ,   UpperCamelCase__    )
      snake_case				=			kwargs.pop('''local_files_only'''    ,   UpperCamelCase__    )

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

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

       snake_case				=			Config.load_yaml(UpperCamelCase__    )

      except EnvironmentError:
       snake_case				=			'''Can\'t load config for'''
       raise EnvironmentError(UpperCamelCase__    )

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

      return Config.load_yaml(UpperCamelCase__    ), kwargs




def    __UpperCamelCase	(	a    : Optional[Any]     ) ->Any:
 snake_case				=			torch.load('''dump.pt'''					,   map_location=in_tensor.device     )
 snake_case				=			in_tensor.numpy()
 snake_case				=			out_tensor.numpy()[0]
 print(na.shape					,   na[0, 0, :5]     )
 print(na.shape					,   na[0, 0, :5]     )
 assert np.allclose(_lowercase					,   _lowercase					,   rtol=0.01					,   atol=0.1     ), (
     f"""{sum([1 for x in np.isclose(_lowercase					,   _lowercase					,   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]     ) ->int:
 snake_case				=			urlparse(_lowercase     )
 return parsed.scheme in ("http", "https")

def    __UpperCamelCase	(	a    : Union[str, Any]					,   a    : Tuple					,   a    : Optional[int]=True     ) ->List[str]:
 snake_case				=			CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
 snake_case				=			'''/''' not in model_id
 if legacy_format:
  return f"""{endpoint}/{model_id}-{filename}"""
 else:
  return f"""{endpoint}/{model_id}/{filename}"""

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

def    __UpperCamelCase	(	a    : Dict					,   a    : Tuple=None					,   a    : Tuple=False					,   a    : Tuple=None					,   a    : List[str]=10					,   a    : int=False					,   a    : str=None					,   a    : str=False					,   ) ->Optional[int]:
 if cache_dir is None:
  snake_case				=			TRANSFORMERS_CACHE
 if isinstance(_lowercase					,   _lowercase     ):
  snake_case				=			str(_lowercase     )

 os.makedirs(_lowercase					,   exist_ok=_lowercase     )

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

 snake_case				=			url_to_filename(_lowercase					,   _lowercase     )

 # get cache path to put the file
 snake_case				=			os.path.join(_lowercase					,   _lowercase     )

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

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

  if resume_download:
   snake_case				=			cache_path + '''.incomplete'''

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

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

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

  os.replace(temp_file.name					,   _lowercase     )

  snake_case				=			{'''url''': url, '''etag''': etag}
  snake_case				=			cache_path + '''.json'''
  with open(_lowercase					,   '''w'''     ) as meta_file:
   json.dump(_lowercase					,   _lowercase     )

 return cache_path

def    __UpperCamelCase	(	a    : int					,   a    : Dict=None     ) ->Tuple:
 snake_case				=			url.encode('''utf-8'''     )
 snake_case				=			shaaaa(_lowercase     )
 snake_case				=			url_hash.hexdigest()

 if etag:
  snake_case				=			etag.encode('''utf-8'''     )
  snake_case				=			shaaaa(_lowercase     )
  filename += "." + etag_hash.hexdigest()

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

 return filename

def    __UpperCamelCase	(	a    : List[str]					,   a    : int=None					,   a    : Optional[Any]=False					,   a    : Union[str, Any]=None					,   a    : Optional[int]=False					,   a    : List[str]=None					,   a    : str=False					,   a    : Optional[Any]=False					,   a    : Optional[Any]=False					,   ) ->Union[str, Any]:
 if cache_dir is None:
  snake_case				=			TRANSFORMERS_CACHE
 if isinstance(_lowercase					,   _lowercase     ):
  snake_case				=			str(_lowercase     )
 if isinstance(_lowercase					,   _lowercase     ):
  snake_case				=			str(_lowercase     )

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

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

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

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

  return output_path_extracted

 return output_path

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

def    __UpperCamelCase	(	a    : Any     ) ->List[str]:
 snake_case				=			requests.get(_lowercase     )
 snake_case				=			np.array(Image.open(BytesIO(response.content     )     )     )
 return img

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

def    __UpperCamelCase	(	) ->int:
 print(f"""{os.path.abspath(os.path.join(_lowercase					,   os.pardir     )     )}/demo.ipynb"""     )

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






def    __UpperCamelCase	(	a    : Any					,   a    : int=1     ) ->List[str]:
 return (images[i : i + batch] for i in range(0					,   len(_lowercase     )					,   _lowercase     ))








'''simple docstring'''







from ...processing_utils import ProcessorMixin
class 			_lowercase						(       __a					):
     _UpperCAmelCase										=					'''WhisperFeatureExtractor'''
     _UpperCAmelCase										=					'''WhisperTokenizer'''







     def __init__( self    ,   A__    ,   A__    ) ->	Optional[Any]:
      super().__init__(A__    ,   A__    )
      snake_case				=			self.feature_extractor
      snake_case				=			False







     def     UpperCamelCase			( self    ,   A__=None    ,   A__=None    ,   A__=True    ) ->	Union[str, Any]:
      return self.tokenizer.get_decoder_prompt_ids(task=A__    ,   language=A__    ,   no_timestamps=A__    )







     def __call__( self    ,   *A__    ,   **A__    ) ->	Dict:
      # For backward compatibility
      if self._in_target_context_manager:
       return self.current_processor(*A__    ,   **A__    )

      snake_case				=			kwargs.pop('''audio'''    ,   A__    )
      snake_case				=			kwargs.pop('''sampling_rate'''    ,   A__    )
      snake_case				=			kwargs.pop('''text'''    ,   A__    )
      if len(A__    ) > 0:
       snake_case				=			args[0]
       snake_case				=			args[1:]

      if audio is None and text is None:
       raise ValueError('''You need to specify either an `audio` or `text` input to process.'''    )

      if audio is not None:
       snake_case				=			self.feature_extractor(A__    ,   *A__    ,   sampling_rate=A__    ,   **A__    )
      if text is not None:
       snake_case				=			self.tokenizer(A__    ,   **A__    )

      if text is None:
       return inputs

      elif audio is None:
       return encodings
      else:
       snake_case				=			encodings['''input_ids''']
       return inputs







     def     UpperCamelCase			( self    ,   *A__    ,   **A__    ) ->	Optional[Any]:
      return self.tokenizer.batch_decode(*A__    ,   **A__    )







     def     UpperCamelCase			( self    ,   *A__    ,   **A__    ) ->	str:
      return self.tokenizer.decode(*A__    ,   **A__    )







     def     UpperCamelCase			( self    ,   A__    ,   A__="np"    ) ->	Optional[Any]:
      return self.tokenizer.get_prompt_ids(A__    ,   return_tensors=A__    )

