code: 
  
  
  '''simple docstring'''
  
  
  
  
  
  import os
  from shutil import copyfile
  from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  
  import sentencepiece as spm
  
  from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  from ...utils import logging
  
  
  if TYPE_CHECKING:
  					from transformers.pipelines.conversational import Conversation
  
  UpperCAmelCase__      =							logging.get_logger(__name__)
  
  UpperCAmelCase__      =							{'''vocab_file''': '''tokenizer.model'''}
  
  UpperCAmelCase__      =							{
      '''vocab_file''': {
          '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
      },
      '''tokenizer_file''': {
          '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
      },
  }
  UpperCAmelCase__      =							{
      '''hf-internal-testing/llama-tokenizer''': 2_0_4_8,
  }
  UpperCAmelCase__      =							'''▁'''
  
  UpperCAmelCase__ ,     UpperCAmelCase__      =							'''[INST]''', '''[/INST]'''
  UpperCAmelCase__ ,     UpperCAmelCase__      =							'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''
  
  # fmt: off
  UpperCAmelCase__      =							'''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
  answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
  that your responses are socially unbiased and positive in nature.
  
  If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
  correct. If you don\'t know the answer to a question, please don\'t share false information.'''
  class 	a__				(				a_      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			A	:							Dict							= VOCAB_FILES_NAMES
  			A	:							Optional[Any]							= PRETRAINED_VOCAB_FILES_MAP
  			A	:							List[Any]							= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  			A	:							str							= ['''input_ids''', '''attention_mask''']
  			def __init__(     self       : Dict ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : Union[str, Any]="<unk>" ,						lowerCAmelCase_       : str="<s>" ,						lowerCAmelCase_       : Any="</s>" ,						lowerCAmelCase_       : Optional[Any]=None ,						lowerCAmelCase_       : Optional[Dict[str, Any]] = None ,						lowerCAmelCase_       : str=True ,						lowerCAmelCase_       : str=False ,						lowerCAmelCase_       : Any=False ,						lowerCAmelCase_       : Dict=True ,						**lowerCAmelCase_       : List[str] ,						)			->		Optional[int]:
  						__A=  {} if sp_model_kwargs is None else sp_model_kwargs
  						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else bos_token
  						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else eos_token
  						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else unk_token
  						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else pad_token
  						super().__init__(
  						    bos_token=lowerCAmelCase_ ,						eos_token=lowerCAmelCase_ ,						unk_token=lowerCAmelCase_ ,						pad_token=lowerCAmelCase_ ,						add_bos_token=lowerCAmelCase_ ,						add_eos_token=lowerCAmelCase_ ,						sp_model_kwargs=self.sp_model_kwargs ,						clean_up_tokenization_spaces=lowerCAmelCase_ ,						legacy=lowerCAmelCase_ ,						**lowerCAmelCase_ ,						)
  						if legacy:
  									logger.warning_once(
  									    F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
  									    ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'  )
  						__A=  legacy
  						__A=  vocab_file
  						__A=  add_bos_token
  						__A=  add_eos_token
  						__A=  spm.SentencePieceProcessor(**self.sp_model_kwargs  )
  						self.sp_model.Load(lowerCAmelCase_  )
  			def __getstate__(     self       : Optional[Any]  )			->		Optional[Any]:
  						__A=  self.__dict__.copy()
  						__A=  None
  						__A=  self.sp_model.serialized_model_proto()
  						return state
  			def __setstate__(     self       : Union[str, Any] ,						lowerCAmelCase_       : Union[str, Any]  )			->		Dict:
  						__A=  d
  						__A=  spm.SentencePieceProcessor(**self.sp_model_kwargs  )
  						self.sp_model.LoadFromSerializedProto(self.sp_model_proto  )
  			@property
  			def 				lowerCAmelCase    (     self       : Dict  )			->		Union[str, Any]:
  						return self.sp_model.get_piece_size()
  			def 				lowerCAmelCase    (     self       : Dict  )			->		int:
  						__A=  {self.convert_ids_to_tokens(lowerCAmelCase_  ): i for i in range(self.vocab_size  )}
  						vocab.update(self.added_tokens_encoder  )
  						return vocab
  			def 				lowerCAmelCase    (     self       : int ,						lowerCAmelCase_       : Optional[int] ,						**lowerCAmelCase_       : int  )			->		List[str]:
  						# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
  						# the beginning of the text
  						if not self.legacy:
  									__A=  SPIECE_UNDERLINE + text.replace(lowerCAmelCase_ ,						' '  )
  						return super().tokenize(lowerCAmelCase_ ,						**lowerCAmelCase_  )
  			def 				lowerCAmelCase    (     self       : str ,						lowerCAmelCase_       : Union[str, Any]  )			->		int:
  						if not self.legacy:
  									__A=  text.startswith(lowerCAmelCase_  )
  									if is_first:
  												__A=  text[1:]
  
  						__A=  self.sp_model.encode(lowerCAmelCase_ ,						out_type=lowerCAmelCase_  )
  
  						if not self.legacy and not is_first and not text.startswith(' '  ) and tokens[0].startswith(lowerCAmelCase_  ):
  									__A=  ([tokens[0][1:]] if len(tokens[0]  ) > 1 else []) + tokens[1:]
  						return tokens
  			def 				lowerCAmelCase    (     self       : List[Any] ,						lowerCAmelCase_       : List[Any]  )			->		List[str]:
  						return self.sp_model.piece_to_id(lowerCAmelCase_  )
  			def 				lowerCAmelCase    (     self       : Optional[int] ,						lowerCAmelCase_       : Dict  )			->		int:
  						__A=  self.sp_model.IdToPiece(lowerCAmelCase_  )
  						return token
  			def 				lowerCAmelCase    (     self       : Any ,						lowerCAmelCase_       : Optional[Any]  )			->		Optional[Any]:
  						__A=  []
  						__A=  ''
  						__A=  False
  						for i, token in enumerate(lowerCAmelCase_  ):
  									# make sure that special tokens are not decoded using sentencepiece model
  									if token in self.all_special_tokens:
  												if not prev_is_special and i != 0:
  															out_string += " "
  												out_string += self.sp_model.decode(lowerCAmelCase_  ) + token
  												__A=  True
  												__A=  []
  									else:
  												current_sub_tokens.append(lowerCAmelCase_  )
  												__A=  False
  						out_string += self.sp_model.decode(lowerCAmelCase_  )
  						return out_string
  			def 				lowerCAmelCase    (     self       : Union[str, Any] ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : Optional[str] = None  )			->		Tuple[str]:
  						if not os.path.isdir(lowerCAmelCase_  ):
  									logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""  )
  									return
  						__A=  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:
  												__A=  self.sp_model.serialized_model_proto()
  												fi.write(lowerCAmelCase_  )
  
  						return (out_vocab_file,)
  			def 				lowerCAmelCase    (     self       : List[Any] ,						lowerCAmelCase_       : Dict ,						lowerCAmelCase_       : Union[str, Any]=None  )			->		Any:
  						__A=  [self.bos_token_id] if self.add_bos_token else []
  						__A=  [self.eos_token_id] if self.add_eos_token else []
  
  						__A=  bos_token_id + token_ids_a + eos_token_id
  
  						if token_ids_a is not None:
  									__A=  output + bos_token_id + token_ids_a + eos_token_id
  
  						return output
  			def 				lowerCAmelCase    (     self       : Any ,						lowerCAmelCase_       : List[int] ,						lowerCAmelCase_       : Optional[List[int]] = None ,						lowerCAmelCase_       : bool = 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_  )
  
  						__A=  [1] if self.add_bos_token else []
  						__A=  [1] if self.add_eos_token else []
  
  						if token_ids_a is None:
  									return bos_token_id + ([0] * len(lowerCAmelCase_  )) + eos_token_id
  						return (
  						    bos_token_id
  						    + ([0] * len(lowerCAmelCase_  ))
  						    + eos_token_id
  						    + bos_token_id
  						    + ([0] * len(lowerCAmelCase_  ))
  						    + eos_token_id
  						)
  			def 				lowerCAmelCase    (     self       : List[str] ,						lowerCAmelCase_       : List[int] ,						lowerCAmelCase_       : Optional[List[int]] = None  )			->		List[int]:
  						__A=  [self.bos_token_id] if self.add_bos_token else []
  						__A=  [self.eos_token_id] if self.add_eos_token else []
  
  						__A=  [0] * len(bos_token_id + token_ids_a + eos_token_id  )
  
  						if token_ids_a is not None:
  									output += [1] * len(bos_token_id + token_ids_a + eos_token_id  )
  
  						return output
  
  			def 				lowerCAmelCase    (     self       : Dict ,						lowerCAmelCase_       : "Conversation"  )			->		List[int]:
  						__A=  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...)'  )
  
  						__A=  []
  						if len(conversation.past_user_inputs  ) > 0:
  									if not conversation.past_user_inputs[0].startswith(lowerCAmelCase_  ) or E_SYS not in conversation.past_user_inputs[0]:
  												__A=  (
  												    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
  												)
  						elif not dialogue[0][1].startswith(lowerCAmelCase_  ) or E_SYS not in dialogue[0][1]:
  									__A=  (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=lowerCAmelCase_  )
  						        + [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=lowerCAmelCase_  )
  						return dialog_tokens
  
  
  
  
style_context: 
  
  
  '''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__(							_SCREAMING_SNAKE_CASE				:   Any,**_SCREAMING_SNAKE_CASE				:   Tuple   ):
  
  
  
  
  
  
  			"""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,**_SCREAMING_SNAKE_CASE,)
  
  
  
  
  
  
  class 	a__				(				a_      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			@staticmethod
  			def 				lowerCAmelCase    (     lowerCAmelCase_       : ArgumentParser  )			->		Tuple:
  						__A=  parser.add_parser('run_beam' ,						help='Run a Beam dataset processing pipeline'  )
  						run_beam_parser.add_argument('dataset' ,						type=lowerCAmelCase_ ,						help='Name of the dataset to download'  )
  						run_beam_parser.add_argument('--name' ,						type=lowerCAmelCase_ ,						default=lowerCAmelCase_ ,						help='Dataset config name'  )
  						run_beam_parser.add_argument(
  						    '--cache_dir' ,						type=lowerCAmelCase_ ,						default=lowerCAmelCase_ ,						help='Cache directory where the datasets are stored' ,						)
  						run_beam_parser.add_argument(
  						    '--beam_pipeline_options' ,						type=lowerCAmelCase_ ,						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=lowerCAmelCase_ ,						default=lowerCAmelCase_ ,						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=lowerCAmelCase_  )
  			def __init__(     self       : Any ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						**lowerCAmelCase_       : 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 				lowerCAmelCase    (     self       : Optional[int]  )			->		Optional[Any]:
  						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(lowerCAmelCase_  )
  						__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=lowerCAmelCase_ ,						cache_dir=self._cache_dir ,						base_path=dataset_module.builder_kwargs.get('base_path'  ) ,						)  )
  						else:
  									builders.append(
  									    builder_cls(
  									        config_name=lowerCAmelCase_ ,						data_dir=self._data_dir ,						beam_options=lowerCAmelCase_ ,						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=lowerCAmelCase_ ,						)
  									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(lowerCAmelCase_  ).name + '.py'
  
  									__A=  os.path.join(lowerCAmelCase_ ,						lowerCAmelCase_  )
  									if os.path.isfile(lowerCAmelCase_  ):
  												__A=  os.path.dirname(lowerCAmelCase_  )
  									elif os.path.isfile(lowerCAmelCase_  ):
  												__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(lowerCAmelCase_ ,						config.DATASETDICT_INFOS_FILENAME  )
  									copyfile(lowerCAmelCase_ ,						lowerCAmelCase_  )
  									print(F"""Dataset Infos file saved at {user_dataset_infos_path}"""  )
  
  
  
  