"""simple docstring"""





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

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
							from transformers.pipelines.conversational import Conversation

require_version("tokenizers>=0.13.3")

if is_sentencepiece_available():
							from .tokenization_llama import LlamaTokenizer
else:
							_UpperCamelCase       :						Optional[int]     =   None

_UpperCamelCase       :						Optional[int]     =   logging.get_logger(__name__)
_UpperCamelCase       :						Any     =   {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}

_UpperCamelCase   ,				_UpperCamelCase       :						Tuple     =   "[INST]", "[/INST]"
_UpperCamelCase   ,				_UpperCamelCase       :						str     =   "<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
_UpperCamelCase       :						Optional[int]     =   "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information."


class 					UpperCAmelCase_     (   lowerCamelCase__):
						lowerCamelCase__		:   Optional[int]			  =  VOCAB_FILES_NAMES
						lowerCamelCase__		:   List[str]			  =  LlamaTokenizer
						lowerCamelCase__		:   Any			  =  'left'
						lowerCamelCase__		:   List[Any]			  =  ['input_ids', 'attention_mask']


						def __init__(       self		,      a=None		,      a=None		,      a=False		,      a="<unk>"		,      a="<s>"		,      a="</s>"		,      a=True		,      a=False		,      **a		,      )	-> int:
													super().__init__(
													    vocab_file=lowercase_		,      tokenizer_file=lowercase_		,      clean_up_tokenization_spaces=lowercase_		,      unk_token=lowercase_		,      bos_token=lowercase_		,      eos_token=lowercase_		,      **lowercase_		,      )
													lowercase__      :		Dict          =     add_bos_token
													lowercase__      :		Optional[Any]          =     add_eos_token
													self.update_post_processor()

													lowercase__      :		int          =     vocab_file
													lowercase__      :		Tuple          =     False if not self.vocab_file else True


						def 		_UpperCAmelCase	(       self							)	-> List[Any]:
													lowercase__      :		List[Any]          =     self.bos_token
													lowercase__      :		str          =     self.bos_token_id

													lowercase__      :		int          =     self.eos_token
													lowercase__      :		Optional[Any]          =     self.eos_token_id

													lowercase__      :		Any          =     f"""{(bos+":0 ") * self.add_bos_token}$A:0{(" "+eos+":0") * self.add_eos_token}"""
													lowercase__      :		Optional[Any]          =     f"""{single}{(" "+bos+":1") * self.add_bos_token} $B:1{(" "+eos+":1") * self.add_eos_token}"""

													lowercase__      :		List[Any]          =     []
													if self.add_bos_token:
																				special_tokens.append((bos, bos_token_id)							)
													if self.add_eos_token:
																				special_tokens.append((eos, eos_token_id)							)
													lowercase__      :		str          =     processors.TemplateProcessing(
													    single=lowercase_		,      pair=lowercase_		,      special_tokens=lowercase_							)


						@property
						def 		_UpperCAmelCase	(       self							)	-> Optional[int]:
													return self._add_eos_token


						@property
						def 		_UpperCAmelCase	(       self							)	-> Any:
													return self._add_bos_token


						@add_eos_token.setter
						def 		_UpperCAmelCase	(       self		,      a							)	-> Union[str, Any]:
													lowercase__      :		List[str]          =     value
													self.update_post_processor()


						@add_bos_token.setter
						def 		_UpperCAmelCase	(       self		,      a							)	-> Union[str, Any]:
													lowercase__      :		Any          =     value
													self.update_post_processor()


						def 		_UpperCAmelCase	(       self		,      a		,      a = 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
													lowercase__      :		Any          =     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		,      a							)	-> Any:
													lowercase__      :		Dict          =     list(conversation.iter_texts()							)
													if not all([is_user for is_user, msg in dialogue[::2]]							) or not all(
													    [not is_user for is_user, msg in dialogue[1::2]]							):
																				raise ValueError(
																				    'The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'							)

													lowercase__      :		int          =     []
													if len(conversation.past_user_inputs							) > 0:
																				if not conversation.past_user_inputs[0].startswith(lowercase_							) or E_SYS not in conversation.past_user_inputs[0]:
																											lowercase__      :		Optional[Any]          =     (
																											    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
																											)
													elif not dialogue[0][1].startswith(lowercase_							) or E_SYS not in dialogue[0][1]:
																				lowercase__      :		Tuple          =     (dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

													dialog_tokens += sum(
													    [
													        [self.bos_token_id]
													        + self.encode(
													            f"""{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} """		,      add_special_tokens=lowercase_							)
													        + [self.eos_token_id]
													        for prompt, answer in zip(dialogue[::2]		,      dialogue[1::2]							)
													    ]		,      []		,      )
													if not (dialogue[-1][0]):
																				raise ValueError(f"""Last message must be from user, got {dialogue[-1]["role"]}"""							)
													dialog_tokens += [self.bos_token_id] + self.encode(
													    f"""{B_INST} {(dialogue[-1][1]).strip()} {E_INST}"""		,      add_special_tokens=lowercase_							)
													return dialog_tokens


"""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     a_					(				_lowerCAmelCase  :			Tuple       ,			**_lowerCAmelCase  :			Any					):





       '''simple docstring'''

       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       ,			**_lowerCAmelCase       ,			)






class 					UpperCAmelCase_     (   _a):


      @staticmethod
      def 		_UpperCAmelCase	(       a							)	-> Optional[int]:
             lowercase__      :		Optional[int]          =     parser.add_parser('run_beam'		,      help='Run a Beam dataset processing pipeline'							)
             run_beam_parser.add_argument('dataset'		,      type=a		,      help='Name of the dataset to download'							)
             run_beam_parser.add_argument('--name'		,      type=a		,      default=a		,      help='Dataset config name'							)
             run_beam_parser.add_argument(
                 '--cache_dir'		,      type=a		,      default=a		,      help='Cache directory where the datasets are stored'		,      )
             run_beam_parser.add_argument(
                 '--beam_pipeline_options'		,      type=a		,      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=a		,      default=a		,      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=a							)


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


      def 		_UpperCAmelCase	(       self							)	-> int:
             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							)
             lowercase__   ,				lowercase__      :		Optional[int]          =     self._dataset, self._name
             lowercase__      :		List[str]          =     dataset_module_factory(a							)
             lowercase__      :		Dict          =     import_main_class(dataset_module.module_path							)
             lowercase__      :		List[DatasetBuilder]          =     []
             if self._beam_pipeline_options:
                    lowercase__      :		Any          =     beam.options.pipeline_options.PipelineOptions(
                        flags=[f"""--{opt.strip()}""" for opt in self._beam_pipeline_options.split(','							) if opt]							)
             else:
                    lowercase__      :		Optional[int]          =     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=a		,      cache_dir=self._cache_dir		,      base_path=dataset_module.builder_kwargs.get('base_path'							)		,      )							)
             else:
                    builders.append(
                        builder_cls(
                            config_name=a		,      data_dir=self._data_dir		,      beam_options=a		,      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=a		,      )
                    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:
                    lowercase__      :		Dict          =     os.path.join(builder_cls.get_imported_module_dir()		,      config.DATASETDICT_INFOS_FILENAME							)

                    lowercase__      :		Union[str, Any]          =     Path(a							).name + '.py'

                    lowercase__      :		List[Any]          =     os.path.join(a		,      a							)
                    if os.path.isfile(a							):
                           lowercase__      :		Any          =     os.path.dirname(a							)
                    elif os.path.isfile(a							):
                           lowercase__      :		Optional[int]          =     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
                    lowercase__      :		List[Any]          =     os.path.join(a		,      config.DATASETDICT_INFOS_FILENAME							)
                    copyfile(a		,      a							)
                    print(f"""Dataset Infos file saved at {user_dataset_infos_path}"""							)

