



'''simple docstring'''





import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

UpperCamelCase__    :     Tuple			  =   logging.get_logger(__name__)

UpperCamelCase__    :     Union[str, Any]			  =   {
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
}

UpperCamelCase__    :     Any			  =   {
    'vocab_file': {
        'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json',
        'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json',
        'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json',
        'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json',
        'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json',
    },
    'merges_file': {
        'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt',
        'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt',
        'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt',
        'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt',
        'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt',
    },
}

UpperCamelCase__    :     Any			  =   {
    'gpt2': 1_024,
    'gpt2-medium': 1_024,
    'gpt2-large': 1_024,
    'gpt2-xl': 1_024,
    'distilgpt2': 1_024,
}



@lru_cache()
def     UpperCAmelCase     (    )   ->       Tuple:



   """simple docstring"""






   A_  :		int						=					(
       list(range(ord("""!"""		)      ,		ord("""~"""		) + 1		)		) + list(range(ord("""¡"""		)      ,		ord("""¬"""		) + 1		)		) + list(range(ord("""®"""		)      ,		ord("""ÿ"""		) + 1		)		)
   )
   A_  :		Any						=					bs[:]
   A_  :		List[Any]						=					0
   for b in range(2**8		):
      if b not in bs:
         bs.append(a_		)
         cs.append(2**8 + n		)
         n += 1
   A_  :		Tuple						=					[chr(a_		) for n in cs]
   return dict(zip(a_      ,		a_		)		)



def     UpperCAmelCase     (    a_		)   ->       Union[str, Any]:



   """simple docstring"""






   A_  :		Optional[int]						=					set()
   A_  :		Union[str, Any]						=					word[0]
   for char in word[1:]:
      pairs.add((prev_char, char)		)
      A_  :		int						=					char
   return pairs







class 							_lowerCAmelCase	(  __A							):


 """simple docstring"""

 lowerCamelCase									=     VOCAB_FILES_NAMES
 lowerCamelCase									=     PRETRAINED_VOCAB_FILES_MAP
 lowerCamelCase									=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowerCamelCase									=     ['''input_ids''', '''attention_mask''']







 def __init__(      self					,    _lowerCamelCase					,    _lowerCamelCase					,    _lowerCamelCase="replace"					,    _lowerCamelCase="<|endoftext|>"					,    _lowerCamelCase="<|endoftext|>"					,    _lowerCamelCase="<|endoftext|>"					,    _lowerCamelCase=None					,    _lowerCamelCase=False					,    _lowerCamelCase=False					,    **_lowerCamelCase					,    )    ->    Dict:
    A_  :		List[str]						=					AddedToken(_lowerCamelCase					,    lstrip=_lowerCamelCase					,    rstrip=_lowerCamelCase  ) if isinstance(_lowerCamelCase					,    _lowerCamelCase  ) else bos_token
    A_  :		Any						=					AddedToken(_lowerCamelCase					,    lstrip=_lowerCamelCase					,    rstrip=_lowerCamelCase  ) if isinstance(_lowerCamelCase					,    _lowerCamelCase  ) else eos_token
    A_  :		Tuple						=					AddedToken(_lowerCamelCase					,    lstrip=_lowerCamelCase					,    rstrip=_lowerCamelCase  ) if isinstance(_lowerCamelCase					,    _lowerCamelCase  ) else unk_token
    A_  :		Optional[Any]						=					AddedToken(_lowerCamelCase					,    lstrip=_lowerCamelCase					,    rstrip=_lowerCamelCase  ) if isinstance(_lowerCamelCase					,    _lowerCamelCase  ) else pad_token
    super().__init__(
        errors=_lowerCamelCase					,    unk_token=_lowerCamelCase					,    bos_token=_lowerCamelCase					,    eos_token=_lowerCamelCase					,    pad_token=_lowerCamelCase					,    add_prefix_space=_lowerCamelCase					,    add_bos_token=_lowerCamelCase					,    **_lowerCamelCase					,    )
    A_  :		Any						=					add_bos_token

    with open(_lowerCamelCase					,    encoding="""utf-8"""  ) as vocab_handle:
       A_  :		List[str]						=					json.load(_lowerCamelCase  )
    A_  :		Any						=					{v: k for k, v in self.encoder.items()}
    A_  :		Any						=					errors  # how to handle errors in decoding
    A_  :		List[Any]						=					bytes_to_unicode()
    A_  :		int						=					{v: k for k, v in self.byte_encoder.items()}
    with open(_lowerCamelCase					,    encoding="""utf-8"""  ) as merges_handle:
       A_  :		List[Any]						=					merges_handle.read().split("""\n"""  )[1:-1]
    A_  :		List[str]						=					[tuple(merge.split()  ) for merge in bpe_merges]
    A_  :		List[str]						=					dict(zip(_lowerCamelCase					,    range(len(_lowerCamelCase  )  )  )  )
    A_  :		Tuple						=					{}
    A_  :		Optional[Any]						=					add_prefix_space

    # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
    A_  :		Union[str, Any]						=					re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""  )







 @property
 def       UpperCAmelCase_       (      self  )    ->    Dict:
    return len(self.encoder  )







 def       UpperCAmelCase_       (      self  )    ->    str:
    return dict(self.encoder					,    **self.added_tokens_encoder  )







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    Union[str, Any]:
    if token in self.cache:
       return self.cache[token]
    A_  :		Any						=					tuple(_lowerCamelCase  )
    A_  :		List[Any]						=					get_pairs(_lowerCamelCase  )

    if not pairs:
       return token

    while True:
       A_  :		Optional[Any]						=					min(_lowerCamelCase					,    key=lambda _lowerCamelCase  : self.bpe_ranks.get(_lowerCamelCase					,    float("""inf"""  )  )  )
       if bigram not in self.bpe_ranks:
          break
       A_						,  A_  :		int						=					bigram
       A_  :		Optional[int]						=					[]
       A_  :		Any						=					0
       while i < len(_lowerCamelCase  ):
          try:
             A_  :		List[Any]						=					word.index(_lowerCamelCase					,    _lowerCamelCase  )
          except ValueError:
             new_word.extend(word[i:]  )
             break
          else:
             new_word.extend(word[i:j]  )
             A_  :		Any						=					j

          if word[i] == first and i < len(_lowerCamelCase  ) - 1 and word[i + 1] == second:
             new_word.append(first + second  )
             i += 2
          else:
             new_word.append(word[i]  )
             i += 1
       A_  :		List[Any]						=					tuple(_lowerCamelCase  )
       A_  :		Any						=					new_word
       if len(_lowerCamelCase  ) == 1:
          break
       else:
          A_  :		Any						=					get_pairs(_lowerCamelCase  )
    A_  :		int						=					""" """.join(_lowerCamelCase  )
    A_  :		List[str]						=					word
    return word







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase					,    _lowerCamelCase=None  )    ->    List[Any]:
    if self.add_bos_token:
       A_  :		Optional[Any]						=					[self.bos_token_id]
    else:
       A_  :		Optional[Any]						=					[]

    A_  :		str						=					bos_token_ids + token_ids_a

    if token_ids_a is None:
       return output

    return output + bos_token_ids + token_ids_a







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase					,    _lowerCamelCase = None					,    _lowerCamelCase = False  )    ->    List[int]:
    if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=_lowerCamelCase					,    token_ids_a=_lowerCamelCase					,    already_has_special_tokens=_lowerCamelCase  )

    if not self.add_bos_token:
       return super().get_special_tokens_mask(
           token_ids_a=_lowerCamelCase					,    token_ids_a=_lowerCamelCase					,    already_has_special_tokens=_lowerCamelCase  )

    if token_ids_a is None:
       return [1] + ([0] * len(_lowerCamelCase  ))
    return [1] + ([0] * len(_lowerCamelCase  )) + [1] + ([0] * len(_lowerCamelCase  ))







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    Union[str, Any]:
    A_  :		Dict						=					[]
    for token in re.findall(self.pat					,    _lowerCamelCase  ):
       A_  :		Any						=					"""""".join(
           self.byte_encoder[b] for b in token.encode("""utf-8"""  )  )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
       bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase  ).split(""" """  )  )
    return bpe_tokens







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    int:
    return self.encoder.get(_lowerCamelCase					,    self.encoder.get(self.unk_token  )  )







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    str:
    return self.decoder.get(_lowerCamelCase  )







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    Optional[Any]:
    A_  :		Optional[int]						=					"""""".join(_lowerCamelCase  )
    A_  :		Union[str, Any]						=					bytearray([self.byte_decoder[c] for c in text]  ).decode("""utf-8"""					,    errors=self.errors  )
    return text







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase					,    _lowerCamelCase = None  )    ->    Tuple[str]:
    if not os.path.isdir(_lowerCamelCase  ):
       logger.error(F"Vocabulary path ({save_directory}) should be a directory"  )
       return
    A_  :		List[Any]						=					os.path.join(
        _lowerCamelCase					,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]  )
    A_  :		List[Any]						=					os.path.join(
        _lowerCamelCase					,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]  )

    with open(_lowerCamelCase					,    """w"""					,    encoding="""utf-8"""  ) as f:
       f.write(json.dumps(self.encoder					,    indent=2					,    sort_keys=_lowerCamelCase					,    ensure_ascii=_lowerCamelCase  ) + """\n"""  )

    A_  :		Dict						=					0
    with open(_lowerCamelCase					,    """w"""					,    encoding="""utf-8"""  ) as writer:
       writer.write("""#version: 0.2\n"""  )
       for bpe_tokens, token_index in sorted(self.bpe_ranks.items()					,    key=lambda _lowerCamelCase  : kv[1]  ):
          if index != token_index:
             logger.warning(
                 F"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                 """ Please check that the tokenizer is not corrupted!"""  )
             A_  :		List[str]						=					token_index
          writer.write(""" """.join(_lowerCamelCase  ) + """\n"""  )
          index += 1

    return vocab_file, merge_file







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase					,    _lowerCamelCase=False					,    **_lowerCamelCase  )    ->    Tuple:
    A_  :		str						=					kwargs.pop("""add_prefix_space"""					,    self.add_prefix_space  )
    if is_split_into_words or add_prefix_space:
       A_  :		List[Any]						=					""" """ + text
    return (text, kwargs)







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase  )    ->    List[int]:
    A_  :		List[str]						=					[]
    for is_user, text in conversation.iter_texts():
       input_ids.extend(self.encode(_lowerCamelCase					,    add_special_tokens=_lowerCamelCase  ) + [self.eos_token_id]  )
    if len(_lowerCamelCase  ) > self.model_max_length:
       A_  :		Union[str, Any]						=					input_ids[-self.model_max_length :]
    return input_ids





'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCamelCase__    :     List[Any]			  =   {
    'configuration_layoutlm': ['LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMConfig', 'LayoutLMOnnxConfig'],
    'tokenization_layoutlm': ['LayoutLMTokenizer'],
}

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase__    :     Any			  =   ['LayoutLMTokenizerFast']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase__    :     Optional[Any]			  =   [
      'LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST',
      'LayoutLMForMaskedLM',
      'LayoutLMForSequenceClassification',
      'LayoutLMForTokenClassification',
      'LayoutLMForQuestionAnswering',
      'LayoutLMModel',
      'LayoutLMPreTrainedModel',
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase__    :     str			  =   [
      'TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST',
      'TFLayoutLMForMaskedLM',
      'TFLayoutLMForSequenceClassification',
      'TFLayoutLMForTokenClassification',
      'TFLayoutLMForQuestionAnswering',
      'TFLayoutLMMainLayer',
      'TFLayoutLMModel',
      'TFLayoutLMPreTrainedModel',
  ]


if TYPE_CHECKING:
  from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMOnnxConfig
  from .tokenization_layoutlm import LayoutLMTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_layoutlm_fast import LayoutLMTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_layoutlm import (
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
        LayoutLMForMaskedLM,
        LayoutLMForQuestionAnswering,
        LayoutLMForSequenceClassification,
        LayoutLMForTokenClassification,
        LayoutLMModel,
        LayoutLMPreTrainedModel,
    )
  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_layoutlm import (
        TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFLayoutLMForMaskedLM,
        TFLayoutLMForQuestionAnswering,
        TFLayoutLMForSequenceClassification,
        TFLayoutLMForTokenClassification,
        TFLayoutLMMainLayer,
        TFLayoutLMModel,
        TFLayoutLMPreTrainedModel,
    )

else:
  import sys

  UpperCamelCase__    :     List[str]			  =   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
