






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

  UpperCAmelCase_     :				str         =				True
except ImportError:
  UpperCAmelCase_     :				int         =				False


try:
  from torch.hub import _get_torch_home

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

UpperCAmelCase_     :				Optional[int]         =				os.path.join(torch_cache_home, """transformers""")

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



def       _A    (__a=OBJECTS					,       __a=ATTRIBUTES							)				-> List[str]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						str							=	[]
    with open(__a							) as f:
        for object in f.readlines():
            vg_classes.append(object.split(''','''							)[0].lower().strip()							)

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



def       _A    (__a							)				-> Any:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Tuple							=	OrderedDict()
    with open(__a					,       '''rb'''							) as f:
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	pkl.load(__a							)['''model''']
    for k in copy.deepcopy(list(ckp.keys()							)							):
        SCREAMING_SNAKE_CASE_   :						Dict							=	ckp.pop(__a							)
        if isinstance(__a					,       np.ndarray							):
            SCREAMING_SNAKE_CASE_   :						Any							=	torch.tensor(__a							)
        else:
            assert isinstance(__a					,       torch.tensor							), type(__a							)
        SCREAMING_SNAKE_CASE_   :						List[str]							=	v
    return r




class 							lowerCAmelCase__       :






      '''simple docstring'''

      __UpperCamelCase							=						{}
      def __init__(		self  :						List[Any]		,			lowercase_  :						dict		,			lowercase_  :						str = "root"		,			lowercase_  :						Dict=0):




          '''simple docstring'''


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

          SCREAMING_SNAKE_CASE_   :						int							=	d
      def __repr__(		self  :						int):




          '''simple docstring'''


          return str(list((self._pointer.keys())))
      def __setattr__(		self  :						Optional[Any]		,			lowercase_  :						Optional[int]		,			lowercase_  :						int):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	val
          SCREAMING_SNAKE_CASE_   :						int							=	val
          SCREAMING_SNAKE_CASE_   :						List[str]							=	key.split('''.''')
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	len(lowercase_) - 1
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	self._pointer
          if len(lowercase_) > 1:
              for i, l in enumerate(lowercase_):
                  if hasattr(self		,			lowercase_) and isinstance(getattr(self		,			lowercase_)		,			lowercase_):
                      setattr(getattr(self		,			lowercase_)		,			'''.'''.join(levels[i:])		,			lowercase_)
                  if l == last_level:
                      SCREAMING_SNAKE_CASE_   :						Any							=	val
                  else:
                      SCREAMING_SNAKE_CASE_   :						Tuple							=	pointer[l]
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict):




          '''simple docstring'''


          return self._pointer
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Optional[Any]):




          '''simple docstring'''


          with open(F'{file_name}'		,			'''w''') as stream:
              dump(lowercase_		,			lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						List[Any]		,			lowercase_  :						Tuple		,			lowercase_  :						Dict):




          '''simple docstring'''


          with open(F'{file_name}'		,			'''w''') as stream:
              json.dump(lowercase_		,			lowercase_)
      @staticmethod
      def _SCREAMING_SNAKE_CASE				(		lowercase_  :						List[str]):




          '''simple docstring'''


          with open(lowercase_) as stream:
              SCREAMING_SNAKE_CASE_   :						List[Any]							=	load(lowercase_		,			Loader=lowercase_)
          return data
      def __str__(		self  :						Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	'''    '''
          if self._name != "root":
              SCREAMING_SNAKE_CASE_   :						int							=	F'{t * (self._level-1)}{self._name}:\n'
          else:
              SCREAMING_SNAKE_CASE_   :						List[str]							=	''''''
          SCREAMING_SNAKE_CASE_   :						Tuple							=	self._level
          for i, (k, v) in enumerate(self._pointer.items()):
              if isinstance(lowercase_		,			lowercase_):
                  r += F'{t * (self._level)}{v}\n'
                  self._level += 1
              else:
                  r += F'{t * (self._level)}{k}: {v} ({type(lowercase_).__name__})\n'
              SCREAMING_SNAKE_CASE_   :						Dict							=	level
          return r[:-1]
      @classmethod
      def _SCREAMING_SNAKE_CASE				(		cls  :						str		,			lowercase_  :						str		,			**lowercase_  :						Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	cls.get_config_dict(lowercase_		,			**lowercase_)
          return cls(lowercase_)



      @classmethod
      def _SCREAMING_SNAKE_CASE				(		cls  :						Tuple		,			lowercase_  :						str		,			**lowercase_  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Any							=	kwargs.pop('''cache_dir'''		,			lowercase_)
          SCREAMING_SNAKE_CASE_   :						Dict							=	kwargs.pop('''force_download'''		,			lowercase_)
          SCREAMING_SNAKE_CASE_   :						Any							=	kwargs.pop('''resume_download'''		,			lowercase_)
          SCREAMING_SNAKE_CASE_   :						str							=	kwargs.pop('''proxies'''		,			lowercase_)
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	kwargs.pop('''local_files_only'''		,			lowercase_)

          if os.path.isdir(lowercase_):
              SCREAMING_SNAKE_CASE_   :						Optional[int]							=	os.path.join(lowercase_		,			lowercase_)
          elif os.path.isfile(lowercase_) or is_remote_url(lowercase_):
              SCREAMING_SNAKE_CASE_   :						List[Any]							=	pretrained_model_name_or_path
          else:
              SCREAMING_SNAKE_CASE_   :						Any							=	hf_bucket_url(lowercase_		,			filename=lowercase_		,			use_cdn=lowercase_)

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

              SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	Config.load_yaml(lowercase_)

          except EnvironmentError:
              SCREAMING_SNAKE_CASE_   :						List[Any]							=	'''Can\'t load config for'''
              raise EnvironmentError(lowercase_)

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

          return Config.load_yaml(lowercase_), kwargs



def       _A    (__a							)				-> Union[str, Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						str							=	torch.load('''dump.pt'''					,       map_location=in_tensor.device							)
    SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	in_tensor.numpy()
    SCREAMING_SNAKE_CASE_   :						Dict							=	out_tensor.numpy()[0]
    print(na.shape					,       na[0, 0, :5]							)
    print(na.shape					,       na[0, 0, :5]							)
    assert np.allclose(__a					,       __a					,       rtol=0.01					,       atol=0.1							), (
        f'{sum([1 for x in np.isclose(__a					,       __a					,       rtol=0.01					,       atol=0.1							).flatten() if x is False]							)/len(na.flatten()							)*1_00:.4f} %'
        " element-wise mismatch"
    )
    raise Exception('''tensors are all good'''							)

    # Hugging face functions below



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	urlparse(__a							)
    return parsed.scheme in ("http", "https")



def       _A    (__a					,       __a					,       __a=True							)				-> str:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
    SCREAMING_SNAKE_CASE_   :						str							=	'''/''' not in model_id
    if legacy_format:
        return f'{endpoint}/{model_id}-{filename}'
    else:
        return f'{endpoint}/{model_id}/{filename}'



def       _A    (__a					,       __a					,       __a=None					,       __a=0					,       __a=None					,       )				-> Union[str, Any]:
    """simple docstring"""






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



def       _A    (__a					,       __a=None					,       __a=False					,       __a=None					,       __a=10					,       __a=False					,       __a=None					,       __a=False					,       )				-> List[Any]:
    """simple docstring"""






    if cache_dir is None:
        SCREAMING_SNAKE_CASE_   :						List[str]							=	TRANSFORMERS_CACHE
    if isinstance(__a					,       __a							):
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	str(__a							)

    os.makedirs(__a					,       exist_ok=__a							)

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

    SCREAMING_SNAKE_CASE_   :						Any							=	url_to_filename(__a					,       __a							)

    # get cache path to put the file
    SCREAMING_SNAKE_CASE_   :						List[str]							=	os.path.join(__a					,       __a							)

    # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
    # try to get the last downloaded one
    if etag is None:
        if os.path.exists(__a							):
            return cache_path
        else:
            SCREAMING_SNAKE_CASE_   :						Tuple							=	[
                file
                for file in fnmatch.filter(os.listdir(__a							)					,       filename + '''.*'''							)
                if not file.endswith('''.json'''							) and not file.endswith('''.lock'''							)
            ]
            if len(__a							) > 0:
                return os.path.join(__a					,       matching_files[-1]							)
            else:
                # If files cannot be found and local_files_only=True,
                # the models might've been found if local_files_only=False
                # Notify the user about that
                if local_files_only:
                    raise ValueError(
                        '''Cannot find the requested files in the cached path and outgoing traffic has been'''
                        ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
                        ''' to False.'''							)
                return None

    # From now on, etag is not None.
    if os.path.exists(__a							) and not force_download:
        return cache_path

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

        if resume_download:
            SCREAMING_SNAKE_CASE_   :						Tuple							=	cache_path + '''.incomplete'''

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

            SCREAMING_SNAKE_CASE_   :						str							=	_resumable_file_manager
            if os.path.exists(__a							):
                SCREAMING_SNAKE_CASE_   :						List[str]							=	os.stat(__a							).st_size
            else:
                SCREAMING_SNAKE_CASE_   :						List[Any]							=	0
        else:
            SCREAMING_SNAKE_CASE_   :						List[str]							=	partial(tempfile.NamedTemporaryFile					,       dir=__a					,       delete=__a							)
            SCREAMING_SNAKE_CASE_   :						str							=	0

        # Download to temporary file, then copy to cache dir once finished.
        # Otherwise you get corrupt cache entries if the download gets interrupted.
        with temp_file_manager() as temp_file:
            print(
                '''%s not found in cache or force_download set to True, downloading to %s'''					,       __a					,       temp_file.name					,       )

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

        os.replace(temp_file.name					,       __a							)

        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	{'''url''': url, '''etag''': etag}
        SCREAMING_SNAKE_CASE_   :						int							=	cache_path + '''.json'''
        with open(__a					,       '''w'''							) as meta_file:
            json.dump(__a					,       __a							)

    return cache_path



def       _A    (__a					,       __a=None							)				-> Optional[Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Dict							=	url.encode('''utf-8'''							)
    SCREAMING_SNAKE_CASE_   :						Dict							=	shaaaa(__a							)
    SCREAMING_SNAKE_CASE_   :						Any							=	url_hash.hexdigest()

    if etag:
        SCREAMING_SNAKE_CASE_   :						Dict							=	etag.encode('''utf-8'''							)
        SCREAMING_SNAKE_CASE_   :						List[str]							=	shaaaa(__a							)
        filename += "." + etag_hash.hexdigest()

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

    return filename



def       _A    (__a					,       __a=None					,       __a=False					,       __a=None					,       __a=False					,       __a=None					,       __a=False					,       __a=False					,       __a=False					,       )				-> int:
    """simple docstring"""






    if cache_dir is None:
        SCREAMING_SNAKE_CASE_   :						Optional[int]							=	TRANSFORMERS_CACHE
    if isinstance(__a					,       __a							):
        SCREAMING_SNAKE_CASE_   :						str							=	str(__a							)
    if isinstance(__a					,       __a							):
        SCREAMING_SNAKE_CASE_   :						Tuple							=	str(__a							)

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

    if extract_compressed_file:
        if not is_zipfile(__a							) and not tarfile.is_tarfile(__a							):
            return output_path

        # Path where we extract compressed archives
        # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
        SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						int							=	os.path.split(__a							)
        SCREAMING_SNAKE_CASE_   :						Dict							=	output_file.replace('''.'''					,       '''-'''							) + '''-extracted'''
        SCREAMING_SNAKE_CASE_   :						str							=	os.path.join(__a					,       __a							)

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

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

        return output_path_extracted

    return output_path



def       _A    (__a					,       __a=","							)				-> Any:
    """simple docstring"""






    assert isinstance(__a					,       __a							)
    if os.path.isfile(__a							):
        with open(__a							) as f:
            SCREAMING_SNAKE_CASE_   :						List[Any]							=	eval(f.read()							)
    else:
        SCREAMING_SNAKE_CASE_   :						List[str]							=	requests.get(__a							)
        try:
            SCREAMING_SNAKE_CASE_   :						Optional[int]							=	requests.json()
        except Exception:
            SCREAMING_SNAKE_CASE_   :						List[Any]							=	req.content.decode()
            assert data is not None, "could not connect"
            try:
                SCREAMING_SNAKE_CASE_   :						Any							=	eval(__a							)
            except Exception:
                SCREAMING_SNAKE_CASE_   :						Dict							=	data.split('''\n'''							)
        req.close()
    return data



def       _A    (__a							)				-> Optional[Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						int							=	requests.get(__a							)
    SCREAMING_SNAKE_CASE_   :						Any							=	np.array(Image.open(BytesIO(response.content							)							)							)
    return img



def       _A    (__a							)				-> Any:
    """simple docstring"""






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



def       _A    ()				-> Union[str, Any]:
    """simple docstring"""






    print(f'{os.path.abspath(os.path.join(__a					,       os.pardir							)							)}/demo.ipynb'							)



def       _A    (__a					,       __a="RGB"							)				-> List[Any]:
    """simple docstring"""






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





def       _A    (__a					,       __a=1							)				-> Tuple:
    """simple docstring"""






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










"""simple docstring"""






import shutil
import tempfile
import unittest

from transformers import (
    SPIECE_UNDERLINE,
    AddedToken,
    BatchEncoding,
    NllbTokenizer,
    NllbTokenizerFast,
    is_torch_available,
)
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


UpperCAmelCase_     :				List[Any]         =				get_tests_dir("""fixtures/test_sentencepiece.model""")


if is_torch_available():
  from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right

UpperCAmelCase_     :				List[Any]         =				256047
UpperCAmelCase_     :				Dict         =				256145




@require_sentencepiece
@require_tokenizers
class 							lowerCAmelCase__       (    UpperCAmelCase__       ,	unittest.TestCase				):






      '''simple docstring'''

      __UpperCamelCase							=						NllbTokenizer
      __UpperCamelCase							=						NllbTokenizerFast
      __UpperCamelCase							=						True
      __UpperCamelCase							=						True
      __UpperCamelCase							=						{}
      def _SCREAMING_SNAKE_CASE				(		self  :						List[str]):




          '''simple docstring'''


          super().setUp()

          # We have a SentencePiece fixture for testing
          SCREAMING_SNAKE_CASE_   :						int							=	NllbTokenizer(lowercase_		,			keep_accents=lowercase_)
          tokenizer.save_pretrained(self.tmpdirname)
      def _SCREAMING_SNAKE_CASE				(		self  :						List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	NllbTokenizer(lowercase_		,			keep_accents=lowercase_)

          SCREAMING_SNAKE_CASE_   :						int							=	tokenizer.tokenize('''This is a test''')
          self.assertListEqual(lowercase_		,			['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])

          self.assertListEqual(
              tokenizer.convert_tokens_to_ids(lowercase_)		,			[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]		,			)

          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
          self.assertListEqual(
              lowercase_		,			[
                  SPIECE_UNDERLINE + '''I''',
                  SPIECE_UNDERLINE + '''was''',
                  SPIECE_UNDERLINE + '''b''',
                  '''or''',
                  '''n''',
                  SPIECE_UNDERLINE + '''in''',
                  SPIECE_UNDERLINE + '''''',
                  '''9''',
                  '''2''',
                  '''0''',
                  '''0''',
                  '''0''',
                  ''',''',
                  SPIECE_UNDERLINE + '''and''',
                  SPIECE_UNDERLINE + '''this''',
                  SPIECE_UNDERLINE + '''is''',
                  SPIECE_UNDERLINE + '''f''',
                  '''al''',
                  '''s''',
                  '''é''',
                  '''.''',
              ]		,			)
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	tokenizer.convert_tokens_to_ids(lowercase_)
          self.assertListEqual(
              lowercase_		,			[
                  value + tokenizer.fairseq_offset
                  for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
              ]		,			)

          SCREAMING_SNAKE_CASE_   :						List[Any]							=	tokenizer.convert_ids_to_tokens(lowercase_)
          self.assertListEqual(
              lowercase_		,			[
                  SPIECE_UNDERLINE + '''I''',
                  SPIECE_UNDERLINE + '''was''',
                  SPIECE_UNDERLINE + '''b''',
                  '''or''',
                  '''n''',
                  SPIECE_UNDERLINE + '''in''',
                  SPIECE_UNDERLINE + '''''',
                  '''<unk>''',
                  '''2''',
                  '''0''',
                  '''0''',
                  '''0''',
                  ''',''',
                  SPIECE_UNDERLINE + '''and''',
                  SPIECE_UNDERLINE + '''this''',
                  SPIECE_UNDERLINE + '''is''',
                  SPIECE_UNDERLINE + '''f''',
                  '''al''',
                  '''s''',
                  '''<unk>''',
                  '''.''',
              ]		,			)
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	(self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-nllb''', {})
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
              with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'):
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	self.rust_tokenizer_class.from_pretrained(lowercase_		,			**lowercase_)
                  SCREAMING_SNAKE_CASE_   :						List[Any]							=	self.tokenizer_class.from_pretrained(lowercase_		,			**lowercase_)

                  SCREAMING_SNAKE_CASE_   :						Optional[int]							=	tempfile.mkdtemp()

                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tokenizer_r.save_pretrained(lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Dict							=	tokenizer_p.save_pretrained(lowercase_)

                  # Checks it save with the same files + the tokenizer.json file for the fast one
                  self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files))
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f)
                  self.assertSequenceEqual(lowercase_		,			lowercase_)

                  # Checks everything loads correctly in the same way
                  SCREAMING_SNAKE_CASE_   :						str							=	tokenizer_r.from_pretrained(lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tokenizer_p.from_pretrained(lowercase_)

                  # Check special tokens are set accordingly on Rust and Python
                  for key in tokenizer_pp.special_tokens_map:
                      self.assertTrue(hasattr(lowercase_		,			lowercase_))

                  shutil.rmtree(lowercase_)

                  # Save tokenizer rust, legacy_format=True
                  SCREAMING_SNAKE_CASE_   :						Optional[int]							=	tempfile.mkdtemp()

                  SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	tokenizer_r.save_pretrained(lowercase_		,			legacy_format=lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	tokenizer_p.save_pretrained(lowercase_)

                  # Checks it save with the same files
                  self.assertSequenceEqual(lowercase_		,			lowercase_)

                  # Checks everything loads correctly in the same way
                  SCREAMING_SNAKE_CASE_   :						Optional[int]							=	tokenizer_r.from_pretrained(lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tokenizer_p.from_pretrained(lowercase_)

                  # Check special tokens are set accordingly on Rust and Python
                  for key in tokenizer_pp.special_tokens_map:
                      self.assertTrue(hasattr(lowercase_		,			lowercase_))

                  shutil.rmtree(lowercase_)

                  # Save tokenizer rust, legacy_format=False
                  SCREAMING_SNAKE_CASE_   :						List[Any]							=	tempfile.mkdtemp()

                  SCREAMING_SNAKE_CASE_   :						Dict							=	tokenizer_r.save_pretrained(lowercase_		,			legacy_format=lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Any							=	tokenizer_p.save_pretrained(lowercase_)

                  # Checks it saved the tokenizer.json file
                  self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files))

                  # Checks everything loads correctly in the same way
                  SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	tokenizer_r.from_pretrained(lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tokenizer_p.from_pretrained(lowercase_)

                  # Check special tokens are set accordingly on Rust and Python
                  for key in tokenizer_pp.special_tokens_map:
                      self.assertTrue(hasattr(lowercase_		,			lowercase_))

                  shutil.rmtree(lowercase_)
      @require_torch
      def _SCREAMING_SNAKE_CASE				(		self  :						List[str]):




          '''simple docstring'''


          if not self.test_seqaseq:
              return

          SCREAMING_SNAKE_CASE_   :						Any							=	self.get_tokenizers()
          for tokenizer in tokenizers:
              with self.subTest(F'{tokenizer.__class__.__name__}'):
                  # Longer text that will definitely require truncation.
                  SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	[
                      ''' UN Chief Says There Is No Military Solution in Syria''',
                      ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for'''
                      ''' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons'''
                      ''' will only worsen the violence and misery for millions of people.''',
                  ]
                  SCREAMING_SNAKE_CASE_   :						int							=	[
                      '''Şeful ONU declară că nu există o soluţie militară în Siria''',
                      '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al'''
                      ''' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi'''
                      ''' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''',
                  ]
                  try:
                      SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	tokenizer.prepare_seqaseq_batch(
                          src_texts=lowercase_		,			tgt_texts=lowercase_		,			max_length=3		,			max_target_length=10		,			return_tensors='''pt'''		,			src_lang='''eng_Latn'''		,			tgt_lang='''ron_Latn'''		,			)
                  except NotImplementedError:
                      return
                  self.assertEqual(batch.input_ids.shape[1]		,			3)
                  self.assertEqual(batch.labels.shape[1]		,			10)
                  # max_target_length will default to max_length if not specified
                  SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	tokenizer.prepare_seqaseq_batch(
                      lowercase_		,			tgt_texts=lowercase_		,			max_length=3		,			return_tensors='''pt''')
                  self.assertEqual(batch.input_ids.shape[1]		,			3)
                  self.assertEqual(batch.labels.shape[1]		,			3)

                  SCREAMING_SNAKE_CASE_   :						int							=	tokenizer.prepare_seqaseq_batch(
                      src_texts=lowercase_		,			max_length=3		,			max_target_length=10		,			return_tensors='''pt''')
                  self.assertEqual(batch_encoder_only.input_ids.shape[1]		,			3)
                  self.assertEqual(batch_encoder_only.attention_mask.shape[1]		,			3)
                  self.assertNotIn('''decoder_input_ids'''		,			lowercase_)
      @unittest.skip('''Unfortunately way too slow to build a BPE with SentencePiece.''')
      def _SCREAMING_SNAKE_CASE				(		self  :						List[Any]):




          '''simple docstring'''


          pass



      def _SCREAMING_SNAKE_CASE				(		self  :						str):




          '''simple docstring'''


          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
              with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'):
                  SCREAMING_SNAKE_CASE_   :						Optional[int]							=	[AddedToken('''<special>'''		,			lstrip=lowercase_)]

                  SCREAMING_SNAKE_CASE_   :						Dict							=	self.rust_tokenizer_class.from_pretrained(
                      lowercase_		,			additional_special_tokens=lowercase_		,			**lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Tuple							=	tokenizer_r.encode('''Hey this is a <special> token''')

                  SCREAMING_SNAKE_CASE_   :						Any							=	tokenizer_r.encode('''<special>'''		,			add_special_tokens=lowercase_)[0]

                  self.assertTrue(special_token_id in r_output)

                  if self.test_slow_tokenizer:
                      SCREAMING_SNAKE_CASE_   :						List[Any]							=	self.rust_tokenizer_class.from_pretrained(
                          lowercase_		,			additional_special_tokens=lowercase_		,			**lowercase_		,			)
                      SCREAMING_SNAKE_CASE_   :						int							=	self.tokenizer_class.from_pretrained(
                          lowercase_		,			additional_special_tokens=lowercase_		,			**lowercase_)

                      SCREAMING_SNAKE_CASE_   :						Dict							=	tokenizer_p.encode('''Hey this is a <special> token''')

                      SCREAMING_SNAKE_CASE_   :						Any							=	tokenizer_cr.encode('''Hey this is a <special> token''')

                      self.assertEqual(lowercase_		,			lowercase_)
                      self.assertEqual(lowercase_		,			lowercase_)
                      self.assertTrue(special_token_id in p_output)
                      self.assertTrue(special_token_id in cr_output)




@require_torch
@require_sentencepiece
@require_tokenizers
class 							lowerCAmelCase__       (    unittest.TestCase				):






      '''simple docstring'''

      __UpperCamelCase							=						"facebook/nllb-200-distilled-600M"
      __UpperCamelCase							=						[
          " UN Chief Says There Is No Military Solution in Syria",
          " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.",
      ]
      __UpperCamelCase							=						[
          "Şeful ONU declară că nu există o soluţie militară în Siria",
          "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"
          " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor"
          " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.",
      ]
      __UpperCamelCase							=						[
          2_5_6_0_4_7,
          1_6_2_9_7,
          1_3_4_4_0_8,
          8_1_6_5,
          2_4_8_0_6_6,
          1_4_7_3_4,
          9_5_0,
          1_1_3_5,
          1_0_5_7_2_1,
          3_5_7_3,
          8_3,
          2_7_3_5_2,
          1_0_8,
          4_9_4_8_6,
          2,
      ]
      @classmethod
      def _SCREAMING_SNAKE_CASE				(		cls  :						Optional[int]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						NllbTokenizer							=	NllbTokenizer.from_pretrained(
              cls.checkpoint_name		,			src_lang='''eng_Latn'''		,			tgt_lang='''ron_Latn''')
          SCREAMING_SNAKE_CASE_   :						Any							=	1
          return cls
      def _SCREAMING_SNAKE_CASE				(		self  :						str):




          '''simple docstring'''


          self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Arab''']		,			256001)
          self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Latn''']		,			256002)
          self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''fra_Latn''']		,			256057)
      def _SCREAMING_SNAKE_CASE				(		self  :						List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
          self.assertListEqual(self.expected_src_tokens		,			lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          self.assertIn(lowercase_		,			self.tokenizer.all_special_ids)
          # fmt: off
          SCREAMING_SNAKE_CASE_   :						List[str]							=	[RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047]
          # fmt: on

          SCREAMING_SNAKE_CASE_   :						Dict							=	self.tokenizer.decode(lowercase_		,			skip_special_tokens=lowercase_)
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	self.tokenizer.decode(generated_ids[1:]		,			skip_special_tokens=lowercase_)
          self.assertEqual(lowercase_		,			lowercase_)
          self.assertNotIn(self.tokenizer.eos_token		,			lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	['''this is gunna be a long sentence ''' * 20]
          assert isinstance(src_text[0]		,			lowercase_)
          SCREAMING_SNAKE_CASE_   :						int							=	10
          SCREAMING_SNAKE_CASE_   :						Tuple							=	self.tokenizer(lowercase_		,			max_length=lowercase_		,			truncation=lowercase_).input_ids[0]
          self.assertEqual(ids[-1]		,			2)
          self.assertEqual(ids[0]		,			lowercase_)
          self.assertEqual(len(lowercase_)		,			lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						int):




          '''simple docstring'''


          self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''])		,			[256203, 3])
      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						List[str]							=	tempfile.mkdtemp()
          SCREAMING_SNAKE_CASE_   :						List[str]							=	self.tokenizer.fairseq_tokens_to_ids
          self.tokenizer.save_pretrained(lowercase_)
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	NllbTokenizer.from_pretrained(lowercase_)
          self.assertDictEqual(new_tok.fairseq_tokens_to_ids		,			lowercase_)
      @require_torch
      def _SCREAMING_SNAKE_CASE				(		self  :						int):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						int							=	self.tokenizer(
              self.src_text		,			text_target=self.tgt_text		,			padding=lowercase_		,			truncation=lowercase_		,			max_length=len(self.expected_src_tokens)		,			return_tensors='''pt'''		,			)
          SCREAMING_SNAKE_CASE_   :						int							=	shift_tokens_right(
              batch['''labels''']		,			self.tokenizer.pad_token_id		,			self.tokenizer.lang_code_to_id['''ron_Latn'''])

          self.assertIsInstance(lowercase_		,			lowercase_)

          self.assertEqual((2, 15)		,			batch.input_ids.shape)
          self.assertEqual((2, 15)		,			batch.attention_mask.shape)
          SCREAMING_SNAKE_CASE_   :						Any							=	batch.input_ids.tolist()[0]
          self.assertListEqual(self.expected_src_tokens		,			lowercase_)
          self.assertEqual(lowercase_		,			batch.decoder_input_ids[0, 0])  # EOS
          # Test that special tokens are reset
          self.assertEqual(self.tokenizer.prefix_tokens		,			[EN_CODE])
          self.assertEqual(self.tokenizer.suffix_tokens		,			[self.tokenizer.eos_token_id])
      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	self.tokenizer(self.src_text		,			padding=lowercase_		,			truncation=lowercase_		,			max_length=3		,			return_tensors='''pt''')
          SCREAMING_SNAKE_CASE_   :						List[str]							=	self.tokenizer(
              text_target=self.tgt_text		,			padding=lowercase_		,			truncation=lowercase_		,			max_length=10		,			return_tensors='''pt''')
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	targets['''input_ids''']
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	shift_tokens_right(
              lowercase_		,			self.tokenizer.pad_token_id		,			decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang]		,			)

          self.assertEqual(batch.input_ids.shape[1]		,			3)
          self.assertEqual(batch.decoder_input_ids.shape[1]		,			10)
      @require_torch
      def _SCREAMING_SNAKE_CASE				(		self  :						Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	self.tokenizer._build_translation_inputs(
              '''A test'''		,			return_tensors='''pt'''		,			src_lang='''eng_Latn'''		,			tgt_lang='''fra_Latn''')

          self.assertEqual(
              nested_simplify(lowercase_)		,			{
                  # A, test, EOS, en_XX
                  '''input_ids''': [[256047, 70, 7356, 2]],
                  '''attention_mask''': [[1, 1, 1, 1]],
                  # ar_AR
                  '''forced_bos_token_id''': 256057,
              }		,			)



      @require_torch
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Dict							=	True
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	self.tokenizer(
              '''UN Chief says there is no military solution in Syria'''		,			src_lang='''eng_Latn'''		,			tgt_lang='''fra_Latn''')
          self.assertEqual(
              inputs.input_ids		,			[16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047])

          SCREAMING_SNAKE_CASE_   :						Dict							=	False
          SCREAMING_SNAKE_CASE_   :						Any							=	self.tokenizer(
              '''UN Chief says there is no military solution in Syria'''		,			src_lang='''eng_Latn'''		,			tgt_lang='''fra_Latn''')
          self.assertEqual(
              inputs.input_ids		,			[256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2])


