




"""simple docstring"""


import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


_A													=      logging.get_logger(__name__)
_A													=      {"""vocab_file""": """spiece.model"""}

_A													=      {
    """vocab_file""": {
        """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""",
        """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""",
        """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""",
        """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""",
        """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""",
        """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""",
        """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""",
        """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""",
    }
}

_A													=      {
    """albert-base-v1""": 5_1_2,
    """albert-large-v1""": 5_1_2,
    """albert-xlarge-v1""": 5_1_2,
    """albert-xxlarge-v1""": 5_1_2,
    """albert-base-v2""": 5_1_2,
    """albert-large-v2""": 5_1_2,
    """albert-xlarge-v2""": 5_1_2,
    """albert-xxlarge-v2""": 5_1_2,
}

_A													=      """▁"""


class _lowerCamelCase    (					a_						):
   _lowerCamelCase    :int     				=     VOCAB_FILES_NAMES
   _lowerCamelCase    :Union[str, Any]     				=     PRETRAINED_VOCAB_FILES_MAP
   _lowerCamelCase    :Tuple     				=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES






   def __init__(		self       :		Optional[Any]   ,     UpperCamelCase       :		List[str]   ,     UpperCamelCase       :		Tuple=True   ,     UpperCamelCase       :		int=True   ,     UpperCamelCase       :		List[str]=False   ,     UpperCamelCase       :		Optional[int]="[CLS]"   ,     UpperCamelCase       :		str="[SEP]"   ,     UpperCamelCase       :		Tuple="<unk>"   ,     UpperCamelCase       :		int="[SEP]"   ,     UpperCamelCase       :		Union[str, Any]="<pad>"   ,     UpperCamelCase       :		Dict="[CLS]"   ,     UpperCamelCase       :		Union[str, Any]="[MASK]"   ,     UpperCamelCase       :		Optional[Dict[str, Any]] = None   ,     **UpperCamelCase       :		Dict   ,     )			->						None:

         """simple docstring"""
         lowerCAmelCase__      :			Any   =	(
             AddedToken(UpperCamelCase   ,     lstrip=UpperCamelCase   ,     rstrip=UpperCamelCase   ,     normalized=UpperCamelCase   )
             if isinstance(UpperCamelCase   ,     UpperCamelCase   )
             else mask_token
         )

         lowerCAmelCase__      :			Tuple   =	{} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             do_lower_case=UpperCamelCase   ,     remove_space=UpperCamelCase   ,     keep_accents=UpperCamelCase   ,     bos_token=UpperCamelCase   ,     eos_token=UpperCamelCase   ,     unk_token=UpperCamelCase   ,     sep_token=UpperCamelCase   ,     pad_token=UpperCamelCase   ,     cls_token=UpperCamelCase   ,     mask_token=UpperCamelCase   ,     sp_model_kwargs=self.sp_model_kwargs   ,     **UpperCamelCase   ,     )

         lowerCAmelCase__      :			List[Any]   =	do_lower_case
         lowerCAmelCase__      :			str   =	remove_space
         lowerCAmelCase__      :			str   =	keep_accents
         lowerCAmelCase__      :			Union[str, Any]   =	vocab_file

         lowerCAmelCase__      :			List[Any]   =	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
         self.sp_model.Load(UpperCamelCase   )






   @property
   def 	_lowerCAmelCase   (		self       :		Dict   )			->						List[Any]:

         """simple docstring"""
         return len(self.sp_model   )






   def 	_lowerCAmelCase   (		self       :		Optional[int]   )			->						Optional[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Union[str, Any]   =	{self.convert_ids_to_tokens(UpperCamelCase   ): i for i in range(self.vocab_size   )}
         vocab.update(self.added_tokens_encoder   )
         return vocab






   def __getstate__(		self       :		List[Any]   )			->						Tuple:

         """simple docstring"""
         lowerCAmelCase__      :			Tuple   =	self.__dict__.copy()
         lowerCAmelCase__      :			List[Any]   =	None
         return state






   def __setstate__(		self       :		Tuple   ,     UpperCamelCase       :		List[str]   )			->						Optional[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			List[str]   =	d

         # for backward compatibility
         if not hasattr(self   ,     """sp_model_kwargs"""   ):
               lowerCAmelCase__      :			Dict   =	{}

         lowerCAmelCase__      :			Optional[Any]   =	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
         self.sp_model.Load(self.vocab_file   )






   def 	_lowerCAmelCase   (		self       :		Tuple   ,     UpperCamelCase       :		List[str]   )			->						int:

         """simple docstring"""
         if self.remove_space:
               lowerCAmelCase__      :			Union[str, Any]   =	""" """.join(inputs.strip().split()   )
         else:
               lowerCAmelCase__      :			List[Any]   =	inputs
         lowerCAmelCase__      :			int   =	outputs.replace("""``"""   ,     """\""""   ).replace("""''"""   ,     """\""""   )

         if not self.keep_accents:
               lowerCAmelCase__      :			str   =	unicodedata.normalize("""NFKD"""   ,     UpperCamelCase   )
               lowerCAmelCase__      :			Optional[Any]   =	"""""".join([c for c in outputs if not unicodedata.combining(UpperCamelCase   )]   )
         if self.do_lower_case:
               lowerCAmelCase__      :			Optional[Any]   =	outputs.lower()

         return outputs






   def 	_lowerCAmelCase   (		self       :		List[str]   ,     UpperCamelCase       :		str   )			->						List[str]:

         """simple docstring"""
         lowerCAmelCase__      :			Dict   =	self.preprocess_text(UpperCamelCase   )
         lowerCAmelCase__      :			int   =	self.sp_model.encode(UpperCamelCase   ,     out_type=UpperCamelCase   )
         lowerCAmelCase__      :			List[str]   =	[]
         for piece in pieces:
               if len(UpperCamelCase   ) > 1 and piece[-1] == str(""","""   ) and piece[-2].isdigit():
                     lowerCAmelCase__      :			Union[str, Any]   =	self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase   ,     """"""   )   )
                     if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                           if len(cur_pieces[0]   ) == 1:
                                 lowerCAmelCase__      :			Tuple   =	cur_pieces[1:]
                           else:
                                 lowerCAmelCase__      :			Optional[Any]   =	cur_pieces[0][1:]
                     cur_pieces.append(piece[-1]   )
                     new_pieces.extend(UpperCamelCase   )
               else:
                     new_pieces.append(UpperCamelCase   )

         return new_pieces






   def 	_lowerCAmelCase   (		self       :		Any   ,     UpperCamelCase       :		Union[str, Any]   )			->						List[str]:

         """simple docstring"""
         return self.sp_model.PieceToId(UpperCamelCase   )






   def 	_lowerCAmelCase   (		self       :		Optional[int]   ,     UpperCamelCase       :		int   )			->						Optional[int]:

         """simple docstring"""
         return self.sp_model.IdToPiece(UpperCamelCase   )






   def 	_lowerCAmelCase   (		self       :		Union[str, Any]   ,     UpperCamelCase       :		Optional[Any]   )			->						List[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Any   =	[]
         lowerCAmelCase__      :			Dict   =	""""""
         lowerCAmelCase__      :			Union[str, Any]   =	False
         for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                     if not prev_is_special:
                           out_string += " "
                     out_string += self.sp_model.decode(UpperCamelCase   ) + token
                     lowerCAmelCase__      :			Tuple   =	True
                     lowerCAmelCase__      :			Any   =	[]
               else:
                     current_sub_tokens.append(UpperCamelCase   )
                     lowerCAmelCase__      :			Any   =	False
         out_string += self.sp_model.decode(UpperCamelCase   )
         return out_string.strip()






   def 	_lowerCAmelCase   (		self       :		Optional[Any]   ,     UpperCamelCase       :		List[int]   ,     UpperCamelCase       :		Optional[List[int]] = None   )			->						List[int]:

         """simple docstring"""
         lowerCAmelCase__      :			List[Any]   =	[self.sep_token_id]
         lowerCAmelCase__      :			Any   =	[self.cls_token_id]
         if token_ids_a is None:
               return cls + token_ids_a + sep
         return cls + token_ids_a + sep + token_ids_a + sep






   def 	_lowerCAmelCase   (		self       :		Tuple   ,     UpperCamelCase       :		List[int]   ,     UpperCamelCase       :		Optional[List[int]] = None   ,     UpperCamelCase       :		bool = False   )			->						List[int]:

         """simple docstring"""

         if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=UpperCamelCase   ,     token_ids_a=UpperCamelCase   ,     already_has_special_tokens=UpperCamelCase   )

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






   def 	_lowerCAmelCase   (		self       :		int   ,     UpperCamelCase       :		List[int]   ,     UpperCamelCase       :		Optional[List[int]] = None   )			->						List[int]:

         """simple docstring"""
         lowerCAmelCase__      :			Tuple   =	[self.sep_token_id]
         lowerCAmelCase__      :			Optional[int]   =	[self.cls_token_id]

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






   def 	_lowerCAmelCase   (		self       :		Tuple   ,     UpperCamelCase       :		str   ,     UpperCamelCase       :		Optional[str] = None   )			->						Tuple[str]:

         """simple docstring"""
         if not os.path.isdir(UpperCamelCase   ):
               logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""   )
               return
         lowerCAmelCase__      :			List[str]   =	os.path.join(
             UpperCamelCase   ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )

         if os.path.abspath(self.vocab_file   ) != os.path.abspath(UpperCamelCase   ) and os.path.isfile(self.vocab_file   ):
               copyfile(self.vocab_file   ,     UpperCamelCase   )
         elif not os.path.isfile(self.vocab_file   ):
               with open(UpperCamelCase   ,     """wb"""   ) as fi:
                     lowerCAmelCase__      :			int   =	self.sp_model.serialized_model_proto()
                     fi.write(UpperCamelCase   )

         return (out_vocab_file,)











"""simple docstring"""


import os
from collections import deque

import torch
from torch.utils.data import Dataset


class _lowerCamelCase    (					a_						):






   def __init__(		self       :		Tuple   ,     UpperCamelCase       :		List[Any]=""   ,     UpperCamelCase       :		List[str]="train"   )			->						List[Any]:

         """simple docstring"""
         assert os.path.isdir(UpperCamelCase   )

         lowerCAmelCase__      :			Union[str, Any]   =	[]
         lowerCAmelCase__      :			List[Any]   =	os.listdir(UpperCamelCase   )
         for story_filename in story_filenames_list:
               if "summary" in story_filename:
                     continue
               lowerCAmelCase__      :			Any   =	os.path.join(UpperCamelCase   ,     UpperCamelCase   )
               if not os.path.isfile(UpperCamelCase   ):
                     continue
               self.documents.append(UpperCamelCase   )






   def __len__(		self       :		List[Any]   )			->						int:

         """simple docstring"""
         return len(self.documents   )






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

         """simple docstring"""
         lowerCAmelCase__      :			Any   =	self.documents[idx]
         lowerCAmelCase__      :			List[Any]   =	document_path.split("""/"""   )[-1]
         with open(UpperCamelCase   ,     encoding="""utf-8"""   ) as source:
               lowerCAmelCase__      :			List[str]   =	source.read()
               lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	process_story(UpperCamelCase   )
         return document_name, story_lines, summary_lines






def 	lowercase_				(			__UpperCAmelCase				)						->    Union[str, Any]:
      lowerCAmelCase__      :			Tuple   =	list(filter(lambda __UpperCAmelCase				: len(__UpperCAmelCase				) != 0    ,		[line.strip() for line in raw_story.split("""\n"""				)]				)				)

      # for some unknown reason some lines miss a period, add it
      lowerCAmelCase__      :			List[str]   =	[_add_missing_period(__UpperCAmelCase				) for line in nonempty_lines]

      # gather article lines
      lowerCAmelCase__      :			Optional[int]   =	[]
      lowerCAmelCase__      :			Optional[int]   =	deque(__UpperCAmelCase				)
      while True:
            try:
                  lowerCAmelCase__      :			List[Any]   =	lines.popleft()
                  if element.startswith("""@highlight"""				):
                        break
                  story_lines.append(__UpperCAmelCase				)
            except IndexError:
                  # if "@highlight" is absent from the file we pop
                  # all elements until there is None, raising an exception.
                  return story_lines, []

    # gather summary lines
      lowerCAmelCase__      :			Any   =	list(filter(lambda __UpperCAmelCase				: not t.startswith("""@highlight"""				)    ,		__UpperCAmelCase				)				)

      return story_lines, summary_lines



def 	lowercase_				(			__UpperCAmelCase				)						->    Optional[int]:
      lowerCAmelCase__      :			List[str]   =	[""".""", """!""", """?""", """...""", """'""", """`""", """\"""", """\u2019""", """\u2019""", """)"""]
      if line.startswith("""@highlight"""				):
            return line
      if line[-1] in END_TOKENS:
            return line
      return line + "."



def 	lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase    ,		__UpperCAmelCase				)						->    List[Any]:
      if len(__UpperCAmelCase				) > block_size:
            return sequence[:block_size]
      else:
            sequence.extend([pad_token_id] * (block_size - len(__UpperCAmelCase				))				)
            return sequence



def 	lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase				)						->    Tuple:
      lowerCAmelCase__      :			List[str]   =	torch.ones_like(__UpperCAmelCase				)
      lowerCAmelCase__      :			List[str]   =	sequence == pad_token_id
      lowerCAmelCase__      :			str   =	0
      return mask



def 	lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase    ,		__UpperCAmelCase				)						->    List[Any]:
      lowerCAmelCase__      :			Tuple   =	[tokenizer.encode(__UpperCAmelCase				) for line in story_lines]
      lowerCAmelCase__      :			List[str]   =	[token for sentence in story_lines_token_ids for token in sentence]
      lowerCAmelCase__      :			int   =	[tokenizer.encode(__UpperCAmelCase				) for line in summary_lines]
      lowerCAmelCase__      :			Union[str, Any]   =	[token for sentence in summary_lines_token_ids for token in sentence]

      return story_token_ids, summary_token_ids



def 	lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase				)						->    List[str]:
      lowerCAmelCase__      :			Tuple   =	[]
      for sequence in batch:
            lowerCAmelCase__      :			Union[str, Any]   =	-1
            lowerCAmelCase__      :			List[str]   =	[]
            for s in sequence:
                  if s == separator_token_id:
                        sentence_num += 1
                  embeddings.append(sentence_num % 2				)
            batch_embeddings.append(__UpperCAmelCase				)
      return torch.tensor(__UpperCAmelCase				)





