



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__	:     Any    =			None

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

UpperCamelCase__	:     List[str]    =			"[INST]", "[/INST]"
UpperCamelCase__	:     Optional[Any]    =			"<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
UpperCamelCase__	:     Tuple    =			"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_   ):


			'''simple docstring'''

			_A				:		List[str]         =		VOCAB_FILES_NAMES
			_A				:		Any         =		LlamaTokenizer
			_A				:		Optional[int]         =		'''left'''
			_A				:		List[Any]         =		['''input_ids''', '''attention_mask''']

			def __init__(							self					:			Union[str, Any]							,					lowerCAmelCase__					:			Tuple=None							,					lowerCAmelCase__					:			Optional[Any]=None							,					lowerCAmelCase__					:			Any=False							,					lowerCAmelCase__					:			Union[str, Any]="<unk>"							,					lowerCAmelCase__					:			Optional[Any]="<s>"							,					lowerCAmelCase__					:			Tuple="</s>"							,					lowerCAmelCase__					:			int=True							,					lowerCAmelCase__					:			Any=False							,					**lowerCAmelCase__					:			Tuple							,					):





					"""simple docstring"""






					super().__init__(
					    vocab_file=_snake_case							,					tokenizer_file=_snake_case							,					clean_up_tokenization_spaces=_snake_case							,					unk_token=_snake_case							,					bos_token=_snake_case							,					eos_token=_snake_case							,					**_snake_case							,					)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		add_bos_token
					__SCREAMING_SNAKE_CASE	:		int   	=		add_eos_token
					self.update_post_processor()

					__SCREAMING_SNAKE_CASE	:		Dict   	=		vocab_file
					__SCREAMING_SNAKE_CASE	:		Any   	=		False if not self.vocab_file else True

			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[str]   	=		self.bos_token
					__SCREAMING_SNAKE_CASE	:		str   	=		self.bos_token_id

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.eos_token
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.eos_token_id

					__SCREAMING_SNAKE_CASE	:		int   	=		F"{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}"
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		F"{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}"

					__SCREAMING_SNAKE_CASE	:		Optional[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)						)
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		processors.TemplateProcessing(
					    single=_snake_case							,					pair=_snake_case							,					special_tokens=_snake_case						)

			@property
			def UpperCamelCase__ (							self					:			Dict						):





					"""simple docstring"""






					return self._add_eos_token

			@property
			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					return self._add_bos_token

			@add_eos_token.setter
			def UpperCamelCase__ (							self					:			Optional[Any]							,					lowerCAmelCase__					:			Optional[int]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		value
					self.update_post_processor()

			@add_bos_token.setter
			def UpperCamelCase__ (							self					:			Optional[Any]							,					lowerCAmelCase__					:			Optional[int]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		value
					self.update_post_processor()

			def UpperCamelCase__ (							self					:			List[Any]							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			Optional[str] = None						):





					"""simple docstring"""






					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(_snake_case						):
							logger.error(F"Vocabulary path ({save_directory}) should be a directory"						)
							return
					__SCREAMING_SNAKE_CASE	:		Any   	=		os.path.join(
					    _snake_case							,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]						)

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

					return (out_vocab_file,)



			def UpperCamelCase__ (							self					:			Optional[Any]							,					lowerCAmelCase__					:			"Conversation"						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		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...)"""						)

					__SCREAMING_SNAKE_CASE	:		Tuple   	=		[]
					if len(conversation.past_user_inputs						) > 0:
							if not conversation.past_user_inputs[0].startswith(_snake_case						) or E_SYS not in conversation.past_user_inputs[0]:
									__SCREAMING_SNAKE_CASE	:		List[Any]   	=		(
									    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
									)
					elif not dialogue[0][1].startswith(_snake_case						) or E_SYS not in dialogue[0][1]:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		(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=_snake_case						)
					        + [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=_snake_case						)
					return dialog_tokens




'''simple docstring'''




import argparse
import os
import sys
import urllib.request
import zipfile


UpperCamelCase__	:     str    =			['''CoLA''', '''SST''', '''MRPC''', '''QQP''', '''STS''', '''MNLI''', '''SNLI''', '''QNLI''', '''RTE''', '''WNLI''', '''diagnostic''']
UpperCamelCase__	:     List[Any]    =			{
    '''CoLA''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4''',
    '''SST''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSST-2.zip?alt=media&token=aabc5f6b-e466-44a2-b9b4-cf6337f84ac8''',
    '''MRPC''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2Fmrpc_dev_ids.tsv?alt=media&token=ec5c0836-31d5-48f4-b431-7480817f1adc''',
    '''QQP''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5''',
    '''STS''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSTS-B.zip?alt=media&token=bddb94a7-8706-4e0d-a694-1109e12273b5''',
    '''MNLI''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce''',
    '''SNLI''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df''',
    '''QNLI''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601''',
    '''RTE''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb''',
    '''WNLI''': '''https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf''',
    '''diagnostic''': '''https://storage.googleapis.com/mtl-sentence-representations.appspot.com/tsvsWithoutLabels%2FAX.tsv?GoogleAccessId=firebase-adminsdk-0khhl@mtl-sentence-representations.iam.gserviceaccount.com&Expires=2498860800&Signature=DuQ2CSPt2Yfre0C%2BiISrVYrIFaZH1Lc7hBVZDD4ZyR7fZYOMNOUGpi8QxBmTNOrNPjR3z1cggo7WXFfrgECP6FBJSsURv8Ybrue8Ypt%2FTPxbuJ0Xc2FhDi%2BarnecCBFO77RSbfuz%2Bs95hRrYhTnByqu3U%2FYZPaj3tZt5QdfpH2IUROY8LiBXoXS46LE%2FgOQc%2FKN%2BA9SoscRDYsnxHfG0IjXGwHN%2Bf88q6hOmAxeNPx6moDulUF6XMUAaXCSFU%2BnRO2RDL9CapWxj%2BDl7syNyHhB7987hZ80B%2FwFkQ3MEs8auvt5XW1%2Bd4aCU7ytgM69r8JDCwibfhZxpaa4gd50QXQ%3D%3D''',
}

UpperCamelCase__	:     Optional[int]    =			'''https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt'''
UpperCamelCase__	:     Any    =			'''https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt'''


def     lowerCAmelCase_       (     _lowerCamelCase:       Union[str, Any]	,				_lowerCamelCase:       Dict ):
		print(F"Downloading and extracting {task}..." )
		__SCREAMING_SNAKE_CASE	:		Tuple   	=		F"{task}.zip"
		urllib.request.urlretrieve(TASKaPATH[task]	,				_lowerCamelCase )
		with zipfile.ZipFile(_lowerCamelCase ) as zip_ref:
				zip_ref.extractall(_lowerCamelCase )
		os.remove(_lowerCamelCase )
		print("""\tCompleted!""" )


def     lowerCAmelCase_       (     _lowerCamelCase:       str	,				_lowerCamelCase:       Optional[int] ):
		print("""Processing MRPC...""" )
		__SCREAMING_SNAKE_CASE	:		List[Any]   	=		os.path.join(_lowerCamelCase	,				"""MRPC""" )
		if not os.path.isdir(_lowerCamelCase ):
				os.mkdir(_lowerCamelCase )
		if path_to_data:
				__SCREAMING_SNAKE_CASE	:		Dict   	=		os.path.join(_lowerCamelCase	,				"""msr_paraphrase_train.txt""" )
				__SCREAMING_SNAKE_CASE	:		Tuple   	=		os.path.join(_lowerCamelCase	,				"""msr_paraphrase_test.txt""" )
		else:
				print("""Local MRPC data not specified, downloading data from %s""" % MRPC_TRAIN )
				__SCREAMING_SNAKE_CASE	:		List[Any]   	=		os.path.join(_lowerCamelCase	,				"""msr_paraphrase_train.txt""" )
				__SCREAMING_SNAKE_CASE	:		List[str]   	=		os.path.join(_lowerCamelCase	,				"""msr_paraphrase_test.txt""" )
				urllib.request.urlretrieve(_lowerCamelCase	,				_lowerCamelCase )
				urllib.request.urlretrieve(_lowerCamelCase	,				_lowerCamelCase )
		if not os.path.isfile(_lowerCamelCase ):
				raise ValueError(F"Train data not found at {mrpc_train_file}" )
		if not os.path.isfile(_lowerCamelCase ):
				raise ValueError(F"Test data not found at {mrpc_test_file}" )
		urllib.request.urlretrieve(TASKaPATH["""MRPC"""]	,				os.path.join(_lowerCamelCase	,				"""dev_ids.tsv""" ) )

		__SCREAMING_SNAKE_CASE	:		Tuple   	=		[]
		with open(os.path.join(_lowerCamelCase	,				"""dev_ids.tsv""" )	,				encoding="""utf8""" ) as ids_fh:
				for row in ids_fh:
						dev_ids.append(row.strip().split("""\t""" ) )

		with open(_lowerCamelCase	,				encoding="""utf8""" ) as data_fh, open(
		    os.path.join(_lowerCamelCase	,				"""train.tsv""" )	,				"""w"""	,				encoding="""utf8""" ) as train_fh, open(os.path.join(_lowerCamelCase	,				"""dev.tsv""" )	,				"""w"""	,				encoding="""utf8""" ) as dev_fh:
				__SCREAMING_SNAKE_CASE	:		Any   	=		data_fh.readline()
				train_fh.write(_lowerCamelCase )
				dev_fh.write(_lowerCamelCase )
				for row in data_fh:
						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		int   	=		row.strip().split("""\t""" )
						if [ida, ida] in dev_ids:
								dev_fh.write("""%s\t%s\t%s\t%s\t%s\n""" % (label, ida, ida, sa, sa) )
						else:
								train_fh.write("""%s\t%s\t%s\t%s\t%s\n""" % (label, ida, ida, sa, sa) )

		with open(_lowerCamelCase	,				encoding="""utf8""" ) as data_fh, open(
		    os.path.join(_lowerCamelCase	,				"""test.tsv""" )	,				"""w"""	,				encoding="""utf8""" ) as test_fh:
				__SCREAMING_SNAKE_CASE	:		Dict   	=		data_fh.readline()
				test_fh.write("""index\t#1 ID\t#2 ID\t#1 String\t#2 String\n""" )
				for idx, row in enumerate(_lowerCamelCase ):
						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Dict   	=		row.strip().split("""\t""" )
						test_fh.write("""%d\t%s\t%s\t%s\t%s\n""" % (idx, ida, ida, sa, sa) )
		print("""\tCompleted!""" )


def     lowerCAmelCase_       (     _lowerCamelCase:       Dict ):
		print("""Downloading and extracting diagnostic...""" )
		if not os.path.isdir(os.path.join(_lowerCamelCase	,				"""diagnostic""" ) ):
				os.mkdir(os.path.join(_lowerCamelCase	,				"""diagnostic""" ) )
		__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		os.path.join(_lowerCamelCase	,				"""diagnostic"""	,				"""diagnostic.tsv""" )
		urllib.request.urlretrieve(TASKaPATH["""diagnostic"""]	,				_lowerCamelCase )
		print("""\tCompleted!""" )
		return


def     lowerCAmelCase_       (     _lowerCamelCase:       int ):
		__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		task_names.split(""",""" )
		if "all" in task_names:
				__SCREAMING_SNAKE_CASE	:		List[Any]   	=		TASKS
		else:
				__SCREAMING_SNAKE_CASE	:		Dict   	=		[]
				for task_name in task_names:
						if task_name not in TASKS:
								raise ValueError(F"Task {task_name} not found!" )
						tasks.append(_lowerCamelCase )
		return tasks


def     lowerCAmelCase_       (     _lowerCamelCase:       Tuple ):
		__SCREAMING_SNAKE_CASE	:		int   	=		argparse.ArgumentParser()
		parser.add_argument("""--data_dir"""	,				help="""directory to save data to"""	,				type=_lowerCamelCase	,				default="""glue_data""" )
		parser.add_argument(
		    """--tasks"""	,				help="""tasks to download data for as a comma separated string"""	,				type=_lowerCamelCase	,				default="""all""" )
		parser.add_argument(
		    """--path_to_mrpc"""	,				help="""path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt"""	,				type=_lowerCamelCase	,				default=""""""	,				)
		__SCREAMING_SNAKE_CASE	:		Tuple   	=		parser.parse_args(_lowerCamelCase )

		if not os.path.isdir(args.data_dir ):
				os.mkdir(args.data_dir )
		__SCREAMING_SNAKE_CASE	:		List[str]   	=		get_tasks(args.tasks )

		for task in tasks:
				if task == "MRPC":
						format_mrpc(args.data_dir	,				args.path_to_mrpc )
				elif task == "diagnostic":
						download_diagnostic(args.data_dir )
				else:
						download_and_extract(_lowerCamelCase	,				args.data_dir )


if __name__ == "__main__":
						sys.exit(main(sys.argv[1:]))