




'''simple docstring'''
import os
import re
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							:				Tuple			     =	logging.get_logger(__name__)
A							:				int			     =	{"""vocab_file""": """spiece.model"""}

A							:				Optional[int]			     =	{
    """vocab_file""": {
        """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/spiece.model""",
        """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/spiece.model""",
    },
}

A							:				Tuple			     =	{
    """google/fnet-base""": 512,
    """google/fnet-large""": 512,
}

A							:				str			     =	"""▁"""






class 	SCREAMING_SNAKE_CASE(    __A					):
       snake_case_			:					str   = VOCAB_FILES_NAMES
       snake_case_			:					List[Any]   = PRETRAINED_VOCAB_FILES_MAP
       snake_case_			:					Any   = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       snake_case_			:					Dict   = ["""input_ids""", """token_type_ids"""]

       def __init__(   self ,		lowerCamelCase__ ,		lowerCamelCase__=False ,		lowerCamelCase__=True ,		lowerCamelCase__=True ,		lowerCamelCase__="<unk>" ,		lowerCamelCase__="[SEP]" ,		lowerCamelCase__="<pad>" ,		lowerCamelCase__="[CLS]" ,		lowerCamelCase__="[MASK]" ,		lowerCamelCase__ = None ,		**lowerCamelCase__ ,		)   -> None:

           """simple docstring"""



           __lowercase          =						(
               AddedToken(lowerCamelCase__ ,		lstrip=lowerCamelCase__ ,		rstrip=lowerCamelCase__ ,		normalized=lowerCamelCase__					)
               if isinstance(lowerCamelCase__ ,		lowerCamelCase__					)
               else mask_token
           )

           __lowercase          =						{} if sp_model_kwargs is None else sp_model_kwargs

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

           __lowercase          =						do_lower_case
           __lowercase          =						remove_space
           __lowercase          =						keep_accents
           __lowercase          =						vocab_file

           __lowercase          =						spm.SentencePieceProcessor(**self.sp_model_kwargs					)
           self.sp_model.Load(lowerCamelCase__					)

       @property
       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           return len(self.sp_model					)

       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           __lowercase          =						{self.convert_ids_to_tokens(lowerCamelCase__					): i for i in range(self.vocab_size					)}
           vocab.update(self.added_tokens_encoder					)
           return vocab

       def __getstate__(   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						self.__dict__.copy()
           __lowercase          =						None
           return state

       def __setstate__(   self ,		lowerCamelCase__					)   -> Any:

           """simple docstring"""



           __lowercase          =						d

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

           __lowercase          =						spm.SentencePieceProcessor(**self.sp_model_kwargs					)
           self.sp_model.Load(self.vocab_file					)

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> Tuple:

           """simple docstring"""



           if self.remove_space:
               __lowercase          =						""" """.join(inputs.strip().split()					)
           else:
               __lowercase          =						inputs
           __lowercase          =						outputs.replace("""``""" ,		"""\""""					).replace("""''""" ,		"""\""""					)

           if not self.keep_accents:
               __lowercase          =						unicodedata.normalize("""NFKD""" ,		lowerCamelCase__					)
               __lowercase          =						"""""".join([c for c in outputs if not unicodedata.combining(lowerCamelCase__					)]					)
           if self.do_lower_case:
               __lowercase          =						outputs.lower()

           return outputs

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						self.preprocess_text(lowerCamelCase__					)
           __lowercase          =						self.sp_model.encode(lowerCamelCase__ ,		out_type=lowerCamelCase__					)
           __lowercase          =						[]
           for piece in pieces:
               if len(lowerCamelCase__					) > 1 and piece[-1] == str(""","""					) and piece[-2].isdigit():
                   __lowercase          =						self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCamelCase__ ,		""""""					)					)
                   if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                       if len(cur_pieces[0]					) == 1:
                           __lowercase          =						cur_pieces[1:]
                       else:
                           __lowercase          =						cur_pieces[0][1:]
                   cur_pieces.append(piece[-1]					)
                   new_pieces.extend(lowerCamelCase__					)
               else:
                   new_pieces.append(lowerCamelCase__					)

           return new_pieces

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> List[str]:

           """simple docstring"""



           return self.sp_model.PieceToId(lowerCamelCase__					)

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> Tuple:

           """simple docstring"""



           return self.sp_model.IdToPiece(lowerCamelCase__					)

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> Dict:

           """simple docstring"""



           __lowercase          =						[]
           __lowercase          =						""""""
           __lowercase          =						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(lowerCamelCase__					) + token
                   __lowercase          =						True
                   __lowercase          =						[]
               else:
                   current_sub_tokens.append(lowerCamelCase__					)
                   __lowercase          =						False
           out_string += self.sp_model.decode(lowerCamelCase__					)
           return out_string.strip()

       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__ = False ,		lowerCamelCase__ = None ,		lowerCamelCase__ = True ,		**lowerCamelCase__ ,		)   -> str:

           """simple docstring"""



           __lowercase          =						kwargs.pop("""use_source_tokenizer""" ,		lowerCamelCase__					)

           __lowercase          =						self.convert_ids_to_tokens(lowerCamelCase__ ,		skip_special_tokens=lowerCamelCase__					)

           # To avoid mixing byte-level and unicode for byte-level BPT
           # we need to build string separately for added tokens and byte-level tokens
           # cf. https://github.com/huggingface/transformers/issues/1133
           __lowercase          =						[]
           __lowercase          =						[]
           for token in filtered_tokens:
               if skip_special_tokens and token in self.all_special_ids:
                   continue
               if token in self.added_tokens_encoder:
                   if current_sub_text:
                       sub_texts.append(self.convert_tokens_to_string(lowerCamelCase__					)					)
                       __lowercase          =						[]
                   sub_texts.append(lowerCamelCase__					)
               else:
                   current_sub_text.append(lowerCamelCase__					)
           if current_sub_text:
               sub_texts.append(self.convert_tokens_to_string(lowerCamelCase__					)					)

           # Mimic the behavior of the Rust tokenizer:
           # No space after <unk>
           if spaces_between_special_tokens:
               __lowercase          =						re.sub(R"""(<unk>) """ ,		R"""\1""" ,		""" """.join(lowerCamelCase__					)					)
           else:
               __lowercase          =						"""""".join(lowerCamelCase__					)

           __lowercase          =						(
               clean_up_tokenization_spaces
               if clean_up_tokenization_spaces is not None
               else self.clean_up_tokenization_spaces
           )
           if clean_up_tokenization_spaces:
               __lowercase          =						self.clean_up_tokenization(lowerCamelCase__					)
               return clean_text
           else:
               return text

       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__ = None					)   -> List[int]:

           """simple docstring"""



           __lowercase          =						[self.sep_token_id]
           __lowercase          =						[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    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__ = None ,		lowerCamelCase__ = False					)   -> List[int]:

           """simple docstring"""



           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 token_ids_a is not None:
               return [1] + ([0] * len(lowerCamelCase__					)) + [1] + ([0] * len(lowerCamelCase__					)) + [1]
           return [1] + ([0] * len(lowerCamelCase__					)) + [1]

       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__ = None					)   -> List[int]:

           """simple docstring"""



           __lowercase          =						[self.sep_token_id]
           __lowercase          =						[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    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__ = None					)   -> Tuple[str]:

           """simple docstring"""



           if not os.path.isdir(lowerCamelCase__					):
               logger.error(F'Vocabulary path ({save_directory}) should be a directory'					)
               return
           __lowercase          =						os.path.join(
               lowerCamelCase__ ,		(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]					)

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

           return (out_vocab_file,)










'''simple docstring'''
from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


A							:				Dict			     =	{
    """id""": """5733be284776f41900661182""",
    """title""": """University_of_Notre_Dame""",
    """context""": """Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.""",
    """question""": """To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?""",
    """answers""": {"""text""": ["""Saint Bernadette Soubirous"""], """answer_start""": [515]},
}
@pytest.mark.parametrize(
    """task_cls"""   ,[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]   ,)
def     snake_case_  (       a__		:     str      ):



    """simple docstring"""




    __lowercase          =						task_cls()
    __lowercase          =						asdict(a__      )
    __lowercase          =						task_template_from_dict(a__      )
    assert task == reloaded






class 	SCREAMING_SNAKE_CASE:

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						LanguageModeling(text_column="""input_text"""					)
           assert {"input_text": "text"} == task.column_mapping




       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text"""}
           __lowercase          =						LanguageModeling.from_dict(lowerCamelCase__					)
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{"""text_column""": """input_text""", """label_column""": """input_labels"""}
           __lowercase          =						TextClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""text-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						QuestionAnsweringExtractive(
               context_column="""input_context""" ,		question_column="""input_question""" ,		answers_column="""input_answers"""					)
           self.assertDictEqual(
               {"""input_context""": """context""", """input_question""": """question""", """input_answers""": """answers"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""question""": Value("""string"""					), """context""": Value("""string"""					)}					)
           __lowercase          =						Features(
               {
                   """answers""": Sequence(
                       {
                           """text""": Value("""string"""					),
                           """answer_start""": Value("""int32"""					),
                       }					)
               }					)
           __lowercase          =						{
               """context_column""": """input_input_context""",
               """question_column""": """input_question""",
               """answers_column""": """input_answers""",
           }
           __lowercase          =						QuestionAnsweringExtractive.from_dict(lowerCamelCase__					)
           self.assertEqual("""question-answering-extractive""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           __lowercase          =						Summarization(text_column="""input_text""" ,		summary_column="""input_summary"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""} ,		task.column_mapping					)




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

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						Features({"""summary""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
           __lowercase          =						Summarization.from_dict(lowerCamelCase__					)
           self.assertEqual("""summarization""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AutomaticSpeechRecognition(audio_column="""input_audio""" ,		transcription_column="""input_transcription"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""transcription""": Value("""string"""					)}					)
           __lowercase          =						{
               """audio_column""": """input_audio""",
               """transcription_column""": """input_transcription""",
           }
           __lowercase          =						AutomaticSpeechRecognition.from_dict(lowerCamelCase__					)
           self.assertEqual("""automatic-speech-recognition""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> List[Any]:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """audio_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						AudioClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""audio-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""image""": Image()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """image_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						ImageClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""image-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
           __lowercase          =						Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()} ,		info=lowerCamelCase__					)
           assert isinstance(dataset.info.task_templates ,		lowerCamelCase__					)
           assert len(dataset.info.task_templates					) == 1

           def keep_task(lowerCamelCase__					):
               return x

           def dont_keep_task(lowerCamelCase__					):
               __lowercase          =						deepcopy(lowerCamelCase__					)
               __lowercase          =						0
               return out

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




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

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					), """label""": ClassLabel(names=("""pos""", """neg""")					)}					)
           __lowercase          =						TextClassification(text_column="""text""" ,		label_column="""label"""					)
           __lowercase          =						DatasetInfo(features=lowerCamelCase__ ,		task_templates=lowerCamelCase__					)
           __lowercase          =						Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]} ,		info=lowerCamelCase__					)

           def process(lowerCamelCase__					):
               return example

           __lowercase          =						dataset.remove_columns("""label"""					)
           __lowercase          =						modified_dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




