






'''simple docstring'''







import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils_fast import AddedToken, PreTrainedTokenizerFast
from ...utils import logging


__A   :							str     	=						logging.get_logger(__name__)

__A   :							Dict     	=						{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

__A   :							Union[str, Any]     	=						{
    'vocab_file': {
        'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/tokenizer.json',
    },
}






class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     def __init__(self     :						Union[str, Any]					,					lowercase__     :						str=None					,					lowercase__     :						List[Any]=None					,					lowercase__     :						List[str]=False					,					lowercase__     :						List[Any]=True					,					lowercase__     :						str=False					,					lowercase__     :						Optional[int]="<s>"					,					lowercase__     :						Union[str, Any]="</s>"					,					lowercase__     :						Dict="<unk>"					,					lowercase__     :						Any="<sep>"					,					lowercase__     :						str="<pad>"					,					lowercase__     :						Dict="<cls>"					,					lowercase__     :						Any="<mask>"					,					lowercase__     :						List[Any]=["<eop>", "<eod>"]					,					**lowercase__     :						Tuple					,					)	->							Optional[Any]:
           __A		 =   AddedToken(lowercase__					,					lstrip=lowercase__					,					rstrip=lowercase__       ) if isinstance(lowercase__					,					lowercase__       ) else mask_token

           super().__init__(
               vocab_file=lowercase__					,					tokenizer_file=lowercase__					,					do_lower_case=lowercase__					,					remove_space=lowercase__					,					keep_accents=lowercase__					,					bos_token=lowercase__					,					eos_token=lowercase__					,					unk_token=lowercase__					,					sep_token=lowercase__					,					pad_token=lowercase__					,					cls_token=lowercase__					,					mask_token=lowercase__					,					additional_special_tokens=lowercase__					,					**lowercase__					,					)

           __A		 =   3
           __A		 =   do_lower_case
           __A		 =   remove_space
           __A		 =   keep_accents
           __A		 =   vocab_file
           __A		 =   False if not self.vocab_file else True

           try:
                 import jieba
           except ModuleNotFoundError as error:
                 raise error.__class__(
                     "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
                     "See https://pypi.org/project/jieba/ for installation."       )
           __A		 =   jieba
           __A		 =   str.maketrans(" \n"					,					"\u2582\u2583"       )






     def      _UpperCamelCase (self     :						List[str]					,					lowercase__     :						List[int]					,					lowercase__     :						Optional[List[int]] = None       )	->							List[int]:
           __A		 =   [self.sep_token_id]
           __A		 =   [self.cls_token_id]
           if token_ids_a is None:
                 return token_ids_a + sep + cls
           return token_ids_a + sep + token_ids_a + sep + cls






     def      _UpperCamelCase (self     :						List[str]					,					lowercase__     :						List[int]					,					lowercase__     :						Optional[List[int]] = None       )	->							List[int]:
           __A		 =   [self.sep_token_id]
           __A		 =   [2]

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






     def      _UpperCamelCase (self     :						int					,					lowercase__     :						str					,					lowercase__     :						Optional[str] = None       )	->							Tuple[str]:
           if not self.can_save_slow_tokenizer:
                 raise ValueError(
                     "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
                     "tokenizer."       )

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

           if os.path.abspath(self.vocab_file       ) != os.path.abspath(lowercase__       ):
                 copyfile(self.vocab_file					,					lowercase__       )

           return (out_vocab_file,)






     def      _UpperCamelCase (self     :						Tuple					,					lowercase__     :						List[str]					,					*lowercase__     :						str					,					**lowercase__     :						Tuple       )	->							Optional[int]:
           __A		 =   [
               " ".join([x.translate(self.translator       ) for x in self.jieba.cut(lowercase__					,					cut_all=lowercase__       )]       )
               for text in batch_text_or_text_pairs
           ]
           return super()._batch_encode_plus(lowercase__					,					*lowercase__					,					**lowercase__       )






     def      _UpperCamelCase (self     :						Dict					,					*lowercase__     :						Tuple					,					**lowercase__     :						List[Any]       )	->							List[Any]:
           __A		 =   super()._decode(*lowercase__					,					**lowercase__       )
           __A		 =   text.replace(" "					,					""       ).replace("\u2582"					,					" "       ).replace("\u2583"					,					"\n"       )
           return text










'''simple docstring'''







import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile
from typing import List

from datasets import config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.info_utils import VerificationMode


def     _UpperCamelCase				(  snake_case__				,      **snake_case__				):
      return RunBeamCommand(
          args.dataset				,      args.name				,      args.cache_dir				,      args.beam_pipeline_options				,      args.data_dir				,      args.all_configs				,      args.save_info or args.save_infos				,      args.ignore_verifications				,      args.force_redownload				,      **snake_case__				,      )






class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     @staticmethod
     def      _UpperCamelCase (lowercase__     :						ArgumentParser       )	->							List[Any]:
           __A		 =   parser.add_parser("run_beam"					,					help="Run a Beam dataset processing pipeline"       )
           run_beam_parser.add_argument("dataset"					,					type=lowercase__					,					help="Name of the dataset to download"       )
           run_beam_parser.add_argument("--name"					,					type=lowercase__					,					default=lowercase__					,					help="Dataset config name"       )
           run_beam_parser.add_argument(
               "--cache_dir"					,					type=lowercase__					,					default=lowercase__					,					help="Cache directory where the datasets are stored"					,					)
           run_beam_parser.add_argument(
               "--beam_pipeline_options"					,					type=lowercase__					,					default=""					,					help="Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`"					,					)
           run_beam_parser.add_argument(
               "--data_dir"					,					type=lowercase__					,					default=lowercase__					,					help="Can be used to specify a manual directory to get the files from"					,					)
           run_beam_parser.add_argument("--all_configs"					,					action="store_true"					,					help="Test all dataset configurations"       )
           run_beam_parser.add_argument("--save_info"					,					action="store_true"					,					help="Save the dataset infos file"       )
           run_beam_parser.add_argument(
               "--ignore_verifications"					,					action="store_true"					,					help="Run the test without checksums and splits checks"       )
           run_beam_parser.add_argument("--force_redownload"					,					action="store_true"					,					help="Force dataset redownload"       )
           # aliases
           run_beam_parser.add_argument("--save_infos"					,					action="store_true"					,					help="alias for save_info"       )
           run_beam_parser.set_defaults(func=lowercase__       )






     def __init__(self     :						Any					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						bool					,					lowercase__     :						bool					,					lowercase__     :						bool					,					lowercase__     :						bool					,					**lowercase__     :						Tuple					,					)	->							List[Any]:
           __A		 =   dataset
           __A		 =   name
           __A		 =   cache_dir
           __A		 =   beam_pipeline_options
           __A		 =   data_dir
           __A		 =   all_configs
           __A		 =   save_infos
           __A		 =   ignore_verifications
           __A		 =   force_redownload
           __A		 =   config_kwargs






     def      _UpperCamelCase (self     :						int       )	->							Dict:
           import apache_beam as beam

           if self._name is not None and self._all_configs:
                 print("Both parameters `name` and `all_configs` can't be used at once."       )
                 exit(1       )
           __A ,					__A		 =   self._dataset, self._name
           __A		 =   dataset_module_factory(lowercase__       )
           __A		 =   import_main_class(dataset_module.module_path       )
           __A		 =   []
           if self._beam_pipeline_options:
                 __A		 =   beam.options.pipeline_options.PipelineOptions(
                     flags=[f"--{opt.strip()}" for opt in self._beam_pipeline_options.split(","       ) if opt]       )
           else:
                 __A		 =   None
           if self._all_configs and len(builder_cls.BUILDER_CONFIGS       ) > 0:
                 for builder_config in builder_cls.BUILDER_CONFIGS:
                       builders.append(
                           builder_cls(
                               config_name=builder_config.name					,					data_dir=self._data_dir					,					hash=dataset_module.hash					,					beam_options=lowercase__					,					cache_dir=self._cache_dir					,					base_path=dataset_module.builder_kwargs.get("base_path"       )					,					)       )
           else:
                 builders.append(
                     builder_cls(
                         config_name=lowercase__					,					data_dir=self._data_dir					,					beam_options=lowercase__					,					cache_dir=self._cache_dir					,					base_path=dataset_module.builder_kwargs.get("base_path"       )					,					**self._config_kwargs					,					)       )

           for builder in builders:
                 builder.download_and_prepare(
                     download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                     if not self._force_redownload
                     else DownloadMode.FORCE_REDOWNLOAD					,					download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH       )					,					verification_mode=VerificationMode.NO_CHECKS
                     if self._ignore_verifications
                     else VerificationMode.ALL_CHECKS					,					try_from_hf_gcs=lowercase__					,					)
                 if self._save_infos:
                       builder._save_infos()

           print("Apache beam run successful."       )

           # If save_infos=True, the dataset infos file is created next to the loaded module file.
           # Let's move it to the original directory of the dataset script, to allow the user to
           # upload them on S3 at the same time afterwards.
           if self._save_infos:
                 __A		 =   os.path.join(builder_cls.get_imported_module_dir()					,					config.DATASETDICT_INFOS_FILENAME       )

                 __A		 =   Path(lowercase__       ).name + ".py"

                 __A		 =   os.path.join(lowercase__					,					lowercase__       )
                 if os.path.isfile(lowercase__       ):
                       __A		 =   os.path.dirname(lowercase__       )
                 elif os.path.isfile(lowercase__       ):
                       __A		 =   path
                 else:  # in case of a remote dataset
                       print(f"Dataset Infos file saved at {dataset_infos_path}"       )
                       exit(1       )

                 # Move datasetinfo back to the user
                 __A		 =   os.path.join(lowercase__					,					config.DATASETDICT_INFOS_FILENAME       )
                 copyfile(lowercase__					,					lowercase__       )
                 print(f"Dataset Infos file saved at {user_dataset_infos_path}"       )


