



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

__A				    =						logging.get_logger(__name__)

__A				    =						{'''vocab_file''': '''tokenizer.model'''}

__A				    =						{
    '''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''',
    },
}
__A				    =						{
    '''hf-internal-testing/llama-tokenizer''': 2048,
}
__A				    =						'''▁'''

__A    ,			__A				    =						'''[INST]''', '''[/INST]'''
__A    ,			__A				    =						'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
__A				    =						'''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 		lowercase						( lowerCAmelCase__):






	"""simple docstring"""


	a__      :					Union[str, Any]		   =							VOCAB_FILES_NAMES
	a__      :					Union[str, Any]		   =							PRETRAINED_VOCAB_FILES_MAP
	a__      :					Dict		   =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	a__      :					Optional[int]		   =							["input_ids", "attention_mask"]




	def __init__(	self	:						List[str]						,  __UpperCAmelCase	:						List[Any]						,  __UpperCAmelCase	:						str="<unk>"						,  __UpperCAmelCase	:						List[Any]="<s>"						,  __UpperCAmelCase	:						Tuple="</s>"						,  __UpperCAmelCase	:						int=None						,  __UpperCAmelCase	:						List[Any] = None						,  __UpperCAmelCase	:						Union[str, Any]=True						,  __UpperCAmelCase	:						Dict=False						,  __UpperCAmelCase	:						Optional[int]=False						,  __UpperCAmelCase	:						Tuple=True						,  **__UpperCAmelCase	:						int						,  )			-> Dict:
							UpperCAmelCase_=   {} if sp_model_kwargs is None else sp_model_kwargs
							UpperCAmelCase_=   AddedToken(_lowerCamelCase						,  lstrip=_lowerCamelCase						,  rstrip=_lowerCamelCase     ) if isinstance(_lowerCamelCase						,  _lowerCamelCase     ) else bos_token
							UpperCAmelCase_=   AddedToken(_lowerCamelCase						,  lstrip=_lowerCamelCase						,  rstrip=_lowerCamelCase     ) if isinstance(_lowerCamelCase						,  _lowerCamelCase     ) else eos_token
							UpperCAmelCase_=   AddedToken(_lowerCamelCase						,  lstrip=_lowerCamelCase						,  rstrip=_lowerCamelCase     ) if isinstance(_lowerCamelCase						,  _lowerCamelCase     ) else unk_token
							UpperCAmelCase_=   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"""     )
							UpperCAmelCase_=   legacy
							UpperCAmelCase_=   vocab_file
							UpperCAmelCase_=   add_bos_token
							UpperCAmelCase_=   add_eos_token
							UpperCAmelCase_=   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
							self.sp_model.Load(_lowerCamelCase     )




	def __getstate__(	self	:						Tuple     )			-> Union[str, Any]:
							UpperCAmelCase_=   self.__dict__.copy()
							UpperCAmelCase_=   None
							UpperCAmelCase_=   self.sp_model.serialized_model_proto()
							return state




	def __setstate__(	self	:						Union[str, Any]						,  __UpperCAmelCase	:						List[str]     )			-> Optional[Any]:
							UpperCAmelCase_=   d
							UpperCAmelCase_=   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
							self.sp_model.LoadFromSerializedProto(self.sp_model_proto     )




	@property
	def   _SCREAMING_SNAKE_CASE		(	self	:						Optional[int]     )			-> Optional[int]:
							return self.sp_model.get_piece_size()




	def   _SCREAMING_SNAKE_CASE		(	self	:						List[str]     )			-> List[Any]:
							UpperCAmelCase_=   {self.convert_ids_to_tokens(_lowerCamelCase     ): i for i in range(self.vocab_size     )}
							vocab.update(self.added_tokens_encoder     )
							return vocab




	def   _SCREAMING_SNAKE_CASE		(	self	:						int						,  __UpperCAmelCase	:						Dict						,  **__UpperCAmelCase	:						List[Any]     )			-> List[str]:





							if not self.legacy:
													UpperCAmelCase_=   SPIECE_UNDERLINE + text.replace(_lowerCamelCase						,  """ """     )
							return super().tokenize(_lowerCamelCase						,  **_lowerCamelCase     )




	def   _SCREAMING_SNAKE_CASE		(	self	:						List[str]						,  __UpperCAmelCase	:						List[str]     )			-> Tuple:





							if not self.legacy:
													UpperCAmelCase_=   text.startswith(_lowerCamelCase     )
													if is_first:
																			UpperCAmelCase_=   text[1:]

							UpperCAmelCase_=   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     ):
													UpperCAmelCase_=   ([tokens[0][1:]] if len(tokens[0]     ) > 1 else []) + tokens[1:]
							return tokens




	def   _SCREAMING_SNAKE_CASE		(	self	:						List[Any]						,  __UpperCAmelCase	:						Optional[int]     )			-> Tuple:
							return self.sp_model.piece_to_id(_lowerCamelCase     )




	def   _SCREAMING_SNAKE_CASE		(	self	:						Optional[int]						,  __UpperCAmelCase	:						List[str]     )			-> Dict:
							UpperCAmelCase_=   self.sp_model.IdToPiece(_lowerCamelCase     )
							return token




	def   _SCREAMING_SNAKE_CASE		(	self	:						List[str]						,  __UpperCAmelCase	:						int     )			-> Optional[Any]:
							UpperCAmelCase_=   []
							UpperCAmelCase_=   """"""
							UpperCAmelCase_=   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
																			UpperCAmelCase_=   True
																			UpperCAmelCase_=   []
													else:
																			current_sub_tokens.append(_lowerCamelCase     )
																			UpperCAmelCase_=   False
							out_string += self.sp_model.decode(_lowerCamelCase     )
							return out_string




	def   _SCREAMING_SNAKE_CASE		(	self	:						List[str]						,  __UpperCAmelCase	:						Any						,  __UpperCAmelCase	:						Any = None     )			-> Tuple[str]:





							if not os.path.isdir(_lowerCamelCase     ):
													logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""     )
													return
							UpperCAmelCase_=   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:
																			UpperCAmelCase_=   self.sp_model.serialized_model_proto()
																			fi.write(_lowerCamelCase     )

							return (out_vocab_file,)




	def   _SCREAMING_SNAKE_CASE		(	self	:						Union[str, Any]						,  __UpperCAmelCase	:						List[Any]						,  __UpperCAmelCase	:						int=None     )			-> Any:
							UpperCAmelCase_=   [self.bos_token_id] if self.add_bos_token else []
							UpperCAmelCase_=   [self.eos_token_id] if self.add_eos_token else []

							UpperCAmelCase_=   bos_token_id + token_ids_a + eos_token_id

							if token_ids_a is not None:
													UpperCAmelCase_=   output + bos_token_id + token_ids_a + eos_token_id

							return output




	def   _SCREAMING_SNAKE_CASE		(	self	:						Tuple						,  __UpperCAmelCase	:						List[str]						,  __UpperCAmelCase	:						int = None						,  __UpperCAmelCase	:						Tuple = 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     )

							UpperCAmelCase_=   [1] if self.add_bos_token else []
							UpperCAmelCase_=   [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   _SCREAMING_SNAKE_CASE		(	self	:						int						,  __UpperCAmelCase	:						Optional[Any]						,  __UpperCAmelCase	:						Dict = None     )			-> List[int]:
							UpperCAmelCase_=   [self.bos_token_id] if self.add_bos_token else []
							UpperCAmelCase_=   [self.eos_token_id] if self.add_eos_token else []

							UpperCAmelCase_=   [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   _SCREAMING_SNAKE_CASE		(	self	:						List[Any]						,  __UpperCAmelCase	:						Dict     )			-> List[int]:
							UpperCAmelCase_=   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...)"""     )

							UpperCAmelCase_=   []
							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]:
																			UpperCAmelCase_=   (
																			    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]:
													UpperCAmelCase_=   (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











'''simple docstring'''



import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_SCREAMING_SNAKE_CASE    =			'''\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
'''

# TODO: Add description of the dataset here
# You can copy an official description
_SCREAMING_SNAKE_CASE    =			'''\
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
'''

# TODO: Add a link to an official homepage for the dataset here
_SCREAMING_SNAKE_CASE    =			''''''

# TODO: Add the licence for the dataset here if you can find it
_SCREAMING_SNAKE_CASE    =			''''''

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_SCREAMING_SNAKE_CASE    =			{
    '''first_domain''': '''https://huggingface.co/great-new-dataset-first_domain.zip''',
    '''second_domain''': '''https://huggingface.co/great-new-dataset-second_domain.zip''',
}






class 							__lowercase				(					datasets.GeneratorBasedBuilder  ):







	'''simple docstring'''

	a			: Tuple      =				datasets.Version("1.1.0"  )

	# This is an example of a dataset with multiple configurations.
	# If you don't want/need to define several sub-sets in your dataset,
	# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

	# If you need to make complex sub-parts in the datasets with configurable options
	# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
	# BUILDER_CONFIG_CLASS = MyBuilderConfig

	# You will be able to load one or the other configurations in the following list with
	# data = datasets.load_dataset('my_dataset', 'first_domain')
	# data = datasets.load_dataset('my_dataset', 'second_domain')
	a			: List[Any]      =				[
	    datasets.BuilderConfig(name="first_domain"       ,					version=lowerCAmelCase__       ,					description="This part of my dataset covers a first domain"  ),
	    datasets.BuilderConfig(name="second_domain"       ,					version=lowerCAmelCase__       ,					description="This part of my dataset covers a second domain"  ),
	]

	a			: Dict      =				"first_domain"  # It's not mandatory to have a default configuration. Just use one if it make sense.


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







				'''simple docstring'''





				if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
							__lowercase   =							datasets.Features(
							    {
							        '''sentence''': datasets.Value('''string'''       ),
							        '''option1''': datasets.Value('''string'''       ),
							        '''answer''': datasets.Value('''string'''       )
							        # These are the features of your dataset like images, labels ...
							    }       )
				else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
							__lowercase   =							datasets.Features(
							    {
							        '''sentence''': datasets.Value('''string'''       ),
							        '''option2''': datasets.Value('''string'''       ),
							        '''second_domain_answer''': datasets.Value('''string'''       )
							        # These are the features of your dataset like images, labels ...
							    }       )
				return datasets.DatasetInfo(
				    # This is the description that will appear on the datasets page.
				    description=_DESCRIPTION   ,features=_lowerCamelCase   ,homepage=_HOMEPAGE   ,license=_LICENSE   ,citation=_CITATION   ,)


	def   _UpperCAmelCase   (self   ,_lowerCamelCase       )							->							Dict:







				'''simple docstring'''





				__lowercase   =							_URLS[self.config.name]
				__lowercase   =							dl_manager.download_and_extract(_lowerCamelCase       )
				return [
				    datasets.SplitGenerator(
				        name=datasets.Split.TRAIN   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''train.jsonl'''       ),
				            '''split''': '''train''',
				        }   ,),
				    datasets.SplitGenerator(
				        name=datasets.Split.VALIDATION   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''dev.jsonl'''       ),
				            '''split''': '''dev''',
				        }   ,),
				    datasets.SplitGenerator(
				        name=datasets.Split.TEST   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''test.jsonl'''       ),
				            '''split''': '''test'''
				        }   ,),
				]


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase       )							->							str:







				'''simple docstring'''





				with open(_lowerCamelCase   ,encoding='''utf-8'''       ) as f:
							for key, row in enumerate(_lowerCamelCase       ):
										__lowercase   =							json.loads(_lowerCamelCase       )
										if self.config.name == "first_domain":
													# Yields examples as (key, example) tuples
													yield key, {
													    "sentence": data["sentence"],
													    "option1": data["option1"],
													    "answer": "" if split == "test" else data["answer"],
													}
										else:
													yield key, {
													    "sentence": data["sentence"],
													    "option2": data["option2"],
													    "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
													}





