





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

   lowercase__		:    Dict =  True
except ImportError:
   lowercase__		:    List[Any] =  False


try:
   from torch.hub import _get_torch_home

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

lowercase__		:    str =  os.path.join(torch_cache_home, 'transformers')

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







def       a__       (       lowercase      :  Dict=OBJECTS,      lowercase      :  Any=ATTRIBUTES   )	->	List[str]:





     """simple docstring"""

     _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       a__       (       lowercase      :  Optional[int]   )	->	Optional[Any]:





     """simple docstring"""

     _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        __lowerCAmelCase  :






       """simple docstring"""
       _snake_case			:  Optional[int]		       =					{}





       def __init__(							self     :	List[str] ,				lowerCAmelCase__     :	int ,				lowerCAmelCase__     :	Any = "root" ,				lowerCAmelCase__     :	Tuple=0  )					->  str:

            '''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__     :	List[str] ,				lowerCAmelCase__     :	str  )					->  List[Any]:

            '''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 snake_case__		(							self     :	Union[str, Any]  )					->  Optional[int]:

            '''simple docstring'''




            return self._pointer





       def snake_case__		(							self     :	Optional[int] ,				lowerCAmelCase__     :	Tuple ,				lowerCAmelCase__     :	int  )					->  str:

            '''simple docstring'''




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





       def snake_case__		(							self     :	Dict ,				lowerCAmelCase__     :	str ,				lowerCAmelCase__     :	Optional[Any]  )					->  Optional[Any]:

            '''simple docstring'''




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





       @staticmethod
       def snake_case__		(							lowerCAmelCase__     :	Any  )					->  Optional[Any]:

            '''simple docstring'''




            with open(_lowerCAmelCase  ) as stream:
                 _UpperCamelCase       					= load(_lowerCAmelCase ,				Loader=_lowerCAmelCase  )
            return data





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

            '''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 snake_case__		(							cls     :	Union[str, Any] ,				lowerCAmelCase__     :	Any ,				**lowerCAmelCase__     :	str  )					->  List[str]:

            '''simple docstring'''




            _UpperCamelCase       					= cls.get_config_dict(_lowerCAmelCase ,				**_lowerCAmelCase  )
            return cls(_lowerCAmelCase  )







       @classmethod
       def snake_case__		(							cls     :	str ,				lowerCAmelCase__     :	Dict ,				**lowerCAmelCase__     :	Dict  )					->  Union[str, 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       a__       (       lowercase      :  Dict   )	->	Dict:





     """simple docstring"""

     _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.0_1,      atol=0.1   ), (
         F"""{sum([1 for x in np.isclose(__lowerCamelCase,      __lowerCamelCase,      rtol=0.0_1,      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       a__       (       lowercase      :  Dict   )	->	List[str]:





     """simple docstring"""

     _UpperCamelCase       					= urlparse(__lowerCamelCase   )
     return parsed.scheme in ("http", "https")







def       a__       (       lowercase      :  Optional[Any],      lowercase      :  str,      lowercase      :  List[str]=True   )	->	str:





     """simple docstring"""

     _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       a__       (       lowercase      :  Any,      lowercase      :  Tuple,      lowercase      :  str=None,      lowercase      :  Tuple=0,      lowercase      :  List[str]=None,      )	->	Optional[int]:





     """simple docstring"""

     _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 == 416:  # 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=1024   ):
          if chunk:  # filter out keep-alive new chunks
               progress.update(len(__lowerCamelCase   )   )
               temp_file.write(__lowerCamelCase   )
     progress.close()







def       a__       (       lowercase      :  List[Any],      lowercase      :  str=None,      lowercase      :  Any=False,      lowercase      :  Dict=None,      lowercase      :  str=10,      lowercase      :  List[str]=False,      lowercase      :  Any=None,      lowercase      :  str=False,      )	->	str:





     """simple docstring"""

     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 == 200:
                    _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       a__       (       lowercase      :  Dict,      lowercase      :  Union[str, Any]=None   )	->	Optional[Any]:





     """simple docstring"""

     _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       a__       (       lowercase      :  List[str],      lowercase      :  Tuple=None,      lowercase      :  Any=False,      lowercase      :  Tuple=None,      lowercase      :  Tuple=False,      lowercase      :  List[str]=None,      lowercase      :  List[Any]=False,      lowercase      :  List[str]=False,      lowercase      :  Dict=False,      )	->	Dict:





     """simple docstring"""

     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       					= 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       a__       (       lowercase      :  List[Any],      lowercase      :  List[Any]=","   )	->	Dict:





     """simple docstring"""

     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       a__       (       lowercase      :  Optional[Any]   )	->	int:





     """simple docstring"""

     _UpperCamelCase       					= requests.get(__lowerCamelCase   )
     _UpperCamelCase       					= np.array(Image.open(BytesIO(response.content   )   )   )
     return img







def       a__       (       lowercase      :  List[Any]   )	->	Dict:





     """simple docstring"""

     _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       a__       (       )	->	str:





     """simple docstring"""

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







def       a__       (       lowercase      :  List[Any],      lowercase      :  int="RGB"   )	->	Optional[int]:





     """simple docstring"""

     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       a__       (       lowercase      :  List[str],      lowercase      :  Dict=1   )	->	Tuple:





     """simple docstring"""

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










'''simple docstring'''

import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata







def       a__       (       lowercase      :  str   )	->	str:





     """simple docstring"""

     _UpperCamelCase       					= min(re.search('''^ +''',      lowercase   ).end() if t.startswith(''' '''   ) else 0 for t in string.splitlines()   )
     return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(lowercase   )]   )


lowercase__		:    List[str] =       '\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n'

lowercase__		:    str =       '\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n'


lowercase__		:    List[Any] =       '\\n# Begin of markdown\n\nSome cool dataset card\n'




class        __lowerCAmelCase  (					unittest.TestCase				):






       """simple docstring"""





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

            '''simple docstring'''




            with tempfile.TemporaryDirectory() as tmp_dir:
                 _UpperCamelCase       					= Path(lowerCAmelCase__  ) / '''README.md'''
                 with open(lowerCAmelCase__ ,				'''w+'''  ) as readme_file:
                      readme_file.write(lowerCAmelCase__  )
                 _UpperCamelCase       					= DatasetMetadata.from_readme(lowerCAmelCase__  )
                 self.assertDictEqual(lowerCAmelCase__ ,				{'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}  )

                 with open(lowerCAmelCase__ ,				'''w+'''  ) as readme_file:
                      readme_file.write(lowerCAmelCase__  )
                 _UpperCamelCase       					= DatasetMetadata.from_readme(lowerCAmelCase__  )
                 self.assertDictEqual(lowerCAmelCase__ ,				{}  )

                 with open(lowerCAmelCase__ ,				'''w+'''  ) as readme_file:
                      readme_file.write(lowerCAmelCase__  )
                 _UpperCamelCase       					= DatasetMetadata.from_readme(lowerCAmelCase__  )
                 self.assertEqual(lowerCAmelCase__ ,				{}  )







       def snake_case__		(							self     :	Dict  )					->  Any:

            '''simple docstring'''




            _UpperCamelCase       					= _dedent(
                '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            '''  )
            assert DatasetMetadata.from_yaml_string(lowerCAmelCase__  )

            _UpperCamelCase       					= _dedent(
                '''\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            '''  )
            with self.assertRaises(lowerCAmelCase__  ):
                 DatasetMetadata.from_yaml_string(lowerCAmelCase__  )

            _UpperCamelCase       					= _dedent(
                '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            '''  )
            assert DatasetMetadata.from_yaml_string(lowerCAmelCase__  )



