




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

   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 						snake_case_							(_a     :							Optional[Any]=OBJECTS   ,       _a     :							List[str]=ATTRIBUTES					):
    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 						snake_case_							(_a     :							List[Any]					):
    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       _a  :
       __a    :					Union[str, Any]           = {}
       def __init__(     self						:     Tuple       ,    lowercase						:     Optional[int]       ,    lowercase						:     str = "root"       ,    lowercase						:     List[Any]=0    ):



           '''simple docstring'''

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

           UpperCAmelCase      	=		d
       def __repr__(     self						:     Any    ):



           '''simple docstring'''

           return str(list((self._pointer.keys())    )    )
       def __setattr__(     self						:     List[Any]       ,    lowercase						:     Tuple       ,    lowercase						:     List[Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		val
           UpperCAmelCase      	=		val
           UpperCAmelCase      	=		key.split('''.'''    )
           UpperCAmelCase      	=		len(__SCREAMING_SNAKE_CASE    ) - 1
           UpperCAmelCase      	=		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:
                       UpperCAmelCase      	=		val
                   else:
                       UpperCAmelCase      	=		pointer[l]
       def    A				(     self						:     Tuple    ):



           '''simple docstring'''

           return self._pointer
       def    A				(     self						:     int       ,    lowercase						:     int       ,    lowercase						:     Optional[int]    ):



           '''simple docstring'''

           with open(f"{file_name}"       ,    '''w'''    ) as stream:
               dump(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE    )
       def    A				(     self						:     Dict       ,    lowercase						:     Union[str, Any]       ,    lowercase						:     Optional[int]    ):



           '''simple docstring'''

           with open(f"{file_name}"       ,    '''w'''    ) as stream:
               json.dump(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE    )
       @staticmethod
       def    A				(     lowercase						:     int    ):



           '''simple docstring'''

           with open(__SCREAMING_SNAKE_CASE    ) as stream:
               UpperCAmelCase      	=		load(__SCREAMING_SNAKE_CASE       ,    Loader=__SCREAMING_SNAKE_CASE    )
           return data
       def __str__(     self						:     Tuple    ):



           '''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(__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"
               UpperCAmelCase      	=		level
           return r[:-1]
       @classmethod
       def    A				(     cls						:     Union[str, Any]       ,    lowercase						:     Optional[Any]       ,    **lowercase						:     Tuple    ):



           '''simple docstring'''

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







       @classmethod
       def    A				(     cls						:     int       ,    lowercase						:     Union[str, Any]       ,    **lowercase						:     Tuple    ):



           '''simple docstring'''

           UpperCAmelCase      	=		kwargs.pop('''cache_dir'''       ,    __SCREAMING_SNAKE_CASE    )
           UpperCAmelCase      	=		kwargs.pop('''force_download'''       ,    __SCREAMING_SNAKE_CASE    )
           UpperCAmelCase      	=		kwargs.pop('''resume_download'''       ,    __SCREAMING_SNAKE_CASE    )
           UpperCAmelCase      	=		kwargs.pop('''proxies'''       ,    __SCREAMING_SNAKE_CASE    )
           UpperCAmelCase      	=		kwargs.pop('''local_files_only'''       ,    __SCREAMING_SNAKE_CASE    )

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

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

               UpperCAmelCase      	=		Config.load_yaml(__SCREAMING_SNAKE_CASE    )

           except EnvironmentError:
               UpperCAmelCase      	=		'''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 						snake_case_							(_a     :							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 						snake_case_							(_a     :							Tuple					):
    UpperCAmelCase      	=		urlparse(_lowerCamelCase					)
    return parsed.scheme in ("http", "https")





def 						snake_case_							(_a     :							str   ,       _a     :							str   ,       _a     :							List[str]=True					):
    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 						snake_case_							(_a     :							Dict   ,       _a     :							str   ,       _a     :							Any=None   ,       _a     :							Dict=0   ,       _a     :							Optional[int]=None   ,       ):
    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 						snake_case_							(_a     :							Tuple   ,       _a     :							List[str]=None   ,       _a     :							Any=False   ,       _a     :							Dict=None   ,       _a     :							Union[str, Any]=1_0   ,       _a     :							str=False   ,       _a     :							Dict=None   ,       _a     :							Dict=False   ,       ):





    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 						snake_case_							(_a     :							List[str]   ,       _a     :							Tuple=None					):
    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 						snake_case_							(_a     :							int   ,       _a     :							Dict=None   ,       _a     :							Union[str, Any]=False   ,       _a     :							Union[str, Any]=None   ,       _a     :							Optional[Any]=False   ,       _a     :							str=None   ,       _a     :							List[Any]=False   ,       _a     :							Any=False   ,       _a     :							Optional[int]=False   ,       ):





    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 						snake_case_							(_a     :							Dict   ,       _a     :							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 						snake_case_							(_a     :							str					):
    UpperCAmelCase      	=		requests.get(_lowerCamelCase					)
    UpperCAmelCase      	=		np.array(Image.open(BytesIO(response.content					)					)					)
    return img





def 						snake_case_							(_a     :							Optional[Any]					):
    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 						snake_case_							():
    print(F"{os.path.abspath(os.path.join(_lowerCamelCase   ,       os.pardir					)					)}/demo.ipynb"					)





def 						snake_case_							(_a     :							List[Any]   ,       _a     :							str="RGB"					):
    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 						snake_case_							(_a     :							List[Any]   ,       _a     :							List[Any]=1					):
    return (images[i : i + batch] for i in range(0   ,       len(_lowerCamelCase					)   ,       _lowerCamelCase					))











'''simple docstring'''







import os
import unittest

from transformers import RealmTokenizerFast
from transformers.models.bert.tokenization_bert import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.realm.tokenization_realm import RealmTokenizer
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english


@require_tokenizers
class       _a  (     __a							,							unittest.TestCase			):
       __a    :					Dict           = RealmTokenizer
       __a    :					Dict           = RealmTokenizerFast
       __a    :					Union[str, Any]           = True
       __a    :					Optional[int]           = True
       __a    :					int           = filter_non_english
       def    A				(     self						:     Optional[Any]    ):



           '''simple docstring'''

           super().setUp()

           UpperCAmelCase      	=		[
               '''[UNK]''',
               '''[CLS]''',
               '''[SEP]''',
               '''[PAD]''',
               '''[MASK]''',
               '''want''',
               '''##want''',
               '''##ed''',
               '''wa''',
               '''un''',
               '''runn''',
               '''##ing''',
               ''',''',
               '''low''',
               '''lowest''',
           ]
           UpperCAmelCase      	=		os.path.join(self.tmpdirname       ,    VOCAB_FILES_NAMES['''vocab_file''']    )
           with open(self.vocab_file       ,    '''w'''       ,    encoding='''utf-8'''    ) as vocab_writer:
               vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]    )    )
       def    A				(     self						:     int       ,    lowercase						:     int    ):



           '''simple docstring'''

           UpperCAmelCase      	=		'''UNwant\u00E9d,running'''
           UpperCAmelCase      	=		'''unwanted, running'''
           return input_text, output_text
       def    A				(     self						:     Optional[Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		self.tokenizer_class(self.vocab_file    )

           UpperCAmelCase      	=		tokenizer.tokenize('''UNwant\u00E9d,running'''    )
           self.assertListEqual(lowercase       ,    ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']    )
           self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase    )       ,    [9, 6, 7, 12, 10, 11]    )
       def    A				(     self						:     Union[str, Any]    ):



           '''simple docstring'''

           if not self.test_rust_tokenizer:
               return

           UpperCAmelCase      	=		self.get_tokenizer()
           UpperCAmelCase      	=		self.get_rust_tokenizer()

           UpperCAmelCase      	=		'''UNwant\u00E9d,running'''

           UpperCAmelCase      	=		tokenizer.tokenize(lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.tokenize(lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )

           UpperCAmelCase      	=		tokenizer.encode(lowercase       ,    add_special_tokens=lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.encode(lowercase       ,    add_special_tokens=lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )

           UpperCAmelCase      	=		self.get_rust_tokenizer()
           UpperCAmelCase      	=		tokenizer.encode(lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.encode(lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )

           # With lower casing
           UpperCAmelCase      	=		self.get_tokenizer(do_lower_case=lowercase    )
           UpperCAmelCase      	=		self.get_rust_tokenizer(do_lower_case=lowercase    )

           UpperCAmelCase      	=		'''UNwant\u00E9d,running'''

           UpperCAmelCase      	=		tokenizer.tokenize(lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.tokenize(lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )

           UpperCAmelCase      	=		tokenizer.encode(lowercase       ,    add_special_tokens=lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.encode(lowercase       ,    add_special_tokens=lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )

           UpperCAmelCase      	=		self.get_rust_tokenizer()
           UpperCAmelCase      	=		tokenizer.encode(lowercase    )
           UpperCAmelCase      	=		rust_tokenizer.encode(lowercase    )
           self.assertListEqual(lowercase       ,    lowercase    )
       def    A				(     self						:     Optional[Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer()

           self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz'''    )       ,    ['''ah''', '''\u535A''', '''\u63A8''', '''zz''']    )
       def    A				(     self						:     Union[str, Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''    )       ,    ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']    )
           self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''    )       ,    ['''hello''']    )
       def    A				(     self						:     Tuple    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase       ,    strip_accents=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''    )       ,    ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?''']    )
           self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''    )       ,    ['''h\u00E9llo''']    )
       def    A				(     self						:     Optional[int]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase       ,    strip_accents=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''    )       ,    ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']    )
           self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''    )       ,    ['''hello''']    )
       def    A				(     self						:     Optional[int]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''    )       ,    ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']    )
           self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''    )       ,    ['''hello''']    )
       def    A				(     self						:     Tuple    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''    )       ,    ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']    )
       def    A				(     self						:     str    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase       ,    strip_accents=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''    )       ,    ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']    )
       def    A				(     self						:     List[Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase       ,    strip_accents=lowercase    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''    )       ,    ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']    )
       def    A				(     self						:     str    ):



           '''simple docstring'''

           UpperCAmelCase      	=		BasicTokenizer(do_lower_case=lowercase       ,    never_split=['''[UNK]''']    )

           self.assertListEqual(
               tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU? [UNK]'''    )       ,    ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]''']    )
       def    A				(     self						:     Optional[int]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

           UpperCAmelCase      	=		{}
           for i, token in enumerate(lowercase    ):
               UpperCAmelCase      	=		i
           UpperCAmelCase      	=		WordpieceTokenizer(vocab=lowercase       ,    unk_token='''[UNK]'''    )

           self.assertListEqual(tokenizer.tokenize(''''''    )       ,    []    )

           self.assertListEqual(tokenizer.tokenize('''unwanted running'''    )       ,    ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing''']    )

           self.assertListEqual(tokenizer.tokenize('''unwantedX running'''    )       ,    ['''[UNK]''', '''runn''', '''##ing''']    )
       def    A				(     self						:     List[str]    ):



           '''simple docstring'''

           self.assertTrue(_is_whitespace(''' '''    )    )
           self.assertTrue(_is_whitespace('''\t'''    )    )
           self.assertTrue(_is_whitespace('''\r'''    )    )
           self.assertTrue(_is_whitespace('''\n'''    )    )
           self.assertTrue(_is_whitespace('''\u00A0'''    )    )

           self.assertFalse(_is_whitespace('''A'''    )    )
           self.assertFalse(_is_whitespace('''-'''    )    )
       def    A				(     self						:     Optional[int]    ):



           '''simple docstring'''

           self.assertTrue(_is_control('''\u0005'''    )    )

           self.assertFalse(_is_control('''A'''    )    )
           self.assertFalse(_is_control(''' '''    )    )
           self.assertFalse(_is_control('''\t'''    )    )
           self.assertFalse(_is_control('''\r'''    )    )
       def    A				(     self						:     str    ):



           '''simple docstring'''

           self.assertTrue(_is_punctuation('''-'''    )    )
           self.assertTrue(_is_punctuation('''$'''    )    )
           self.assertTrue(_is_punctuation('''`'''    )    )
           self.assertTrue(_is_punctuation('''.'''    )    )

           self.assertFalse(_is_punctuation('''A'''    )    )
           self.assertFalse(_is_punctuation(''' '''    )    )
       def    A				(     self						:     Union[str, Any]    ):



           '''simple docstring'''

           UpperCAmelCase      	=		self.get_tokenizer()

           # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
           self.assertListEqual([tokenizer.tokenize(lowercase    ) for t in ['''Test''', '''\xad''', '''test''']]       ,    [['''[UNK]'''], [], ['''[UNK]''']]    )

           if self.test_rust_tokenizer:
               UpperCAmelCase      	=		self.get_rust_tokenizer()
               self.assertListEqual(
                   [rust_tokenizer.tokenize(lowercase    ) for t in ['''Test''', '''\xad''', '''test''']]       ,    [['''[UNK]'''], [], ['''[UNK]''']]    )
       @slow
       def    A				(     self						:     int    ):



           '''simple docstring'''

           UpperCAmelCase      	=		self.tokenizer_class.from_pretrained('''bert-base-uncased'''    )

           UpperCAmelCase      	=		tokenizer.encode('''sequence builders'''       ,    add_special_tokens=lowercase    )
           UpperCAmelCase      	=		tokenizer.encode('''multi-sequence build'''       ,    add_special_tokens=lowercase    )

           UpperCAmelCase      	=		tokenizer.build_inputs_with_special_tokens(lowercase    )
           UpperCAmelCase      	=		tokenizer.build_inputs_with_special_tokens(lowercase       ,    lowercase    )

           assert encoded_sentence == [101] + text + [102]
           assert encoded_pair == [101] + text + [102] + text_a + [102]
       def    A				(     self						:     int    ):



           '''simple docstring'''

           for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"    ):
                   UpperCAmelCase      	=		self.rust_tokenizer_class.from_pretrained(lowercase       ,    **lowercase    )

                   UpperCAmelCase      	=		f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence."
                   UpperCAmelCase      	=		tokenizer_r.encode_plus(
                       lowercase       ,    return_attention_mask=lowercase       ,    return_token_type_ids=lowercase       ,    return_offsets_mapping=lowercase       ,    add_special_tokens=lowercase       ,    )

                   UpperCAmelCase      	=		tokenizer_r.do_lower_case if hasattr(lowercase       ,    '''do_lower_case'''    ) else False
                   UpperCAmelCase      	=		(
                       [
                           ((0, 0), tokenizer_r.cls_token),
                           ((0, 1), '''A'''),
                           ((1, 2), ''','''),
                           ((3, 5), '''na'''),
                           ((5, 6), '''##ï'''),
                           ((6, 8), '''##ve'''),
                           ((9, 15), tokenizer_r.mask_token),
                           ((16, 21), '''Allen'''),
                           ((21, 23), '''##NL'''),
                           ((23, 24), '''##P'''),
                           ((25, 33), '''sentence'''),
                           ((33, 34), '''.'''),
                           ((0, 0), tokenizer_r.sep_token),
                       ]
                       if not do_lower_case
                       else [
                           ((0, 0), tokenizer_r.cls_token),
                           ((0, 1), '''a'''),
                           ((1, 2), ''','''),
                           ((3, 8), '''naive'''),
                           ((9, 15), tokenizer_r.mask_token),
                           ((16, 21), '''allen'''),
                           ((21, 23), '''##nl'''),
                           ((23, 24), '''##p'''),
                           ((25, 33), '''sentence'''),
                           ((33, 34), '''.'''),
                           ((0, 0), tokenizer_r.sep_token),
                       ]
                   )

                   self.assertEqual(
                       [e[1] for e in expected_results]       ,    tokenizer_r.convert_ids_to_tokens(tokens['''input_ids''']    )    )
                   self.assertEqual([e[0] for e in expected_results]       ,    tokens['''offset_mapping''']    )







       @slow
       def    A				(     self						:     Any    ):



           '''simple docstring'''

           for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"    ):
                   UpperCAmelCase      	=		self.rust_tokenizer_class.from_pretrained(lowercase       ,    **lowercase    )
                   UpperCAmelCase      	=		self.tokenizer_class.from_pretrained(lowercase       ,    **lowercase    )
                   UpperCAmelCase      	=		[['''Hello world!''', '''Nice to meet you!'''], ['''The cute cat.''', '''The adorable dog.''']]

                   UpperCAmelCase      	=		tokenizer_r.batch_encode_candidates(lowercase       ,    max_length=10       ,    return_tensors='''np'''    )
                   UpperCAmelCase      	=		tokenizer_p.batch_encode_candidates(lowercase       ,    max_length=10       ,    return_tensors='''np'''    )

                   UpperCAmelCase      	=		(2, 2, 10)

                   self.assertEqual(encoded_sentence_r['''input_ids'''].shape       ,    lowercase    )
                   self.assertEqual(encoded_sentence_r['''attention_mask'''].shape       ,    lowercase    )
                   self.assertEqual(encoded_sentence_r['''token_type_ids'''].shape       ,    lowercase    )

                   self.assertEqual(encoded_sentence_p['''input_ids'''].shape       ,    lowercase    )
                   self.assertEqual(encoded_sentence_p['''attention_mask'''].shape       ,    lowercase    )
                   self.assertEqual(encoded_sentence_p['''token_type_ids'''].shape       ,    lowercase    )




