





"""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:
    _lowerCamelCase  					=     None

_lowerCamelCase  					=     logging.get_logger(__name__)
_lowerCamelCase  					=     {'''vocab_file''': '''tokenizer.model''', '''tokenizer_file''': '''tokenizer.json'''}

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

# fmt: off
_lowerCamelCase  					=     '''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 					snake_case		(       snake_case_       ):
      lowerCamelCase__      =			VOCAB_FILES_NAMES
      lowerCamelCase__      =			LlamaTokenizer
      lowerCamelCase__      =			"""left"""
      lowerCamelCase__      =			["""input_ids""", """attention_mask"""]

      def __init__(      self       :List[Any]						,							_lowerCamelCase       :Union[str, Any]=None						,							_lowerCamelCase       :Any=None						,							_lowerCamelCase       :Tuple=False						,							_lowerCamelCase       :List[Any]="<unk>"						,							_lowerCamelCase       :Optional[Any]="<s>"						,							_lowerCamelCase       :Tuple="</s>"						,							_lowerCamelCase       :Optional[int]=True						,							_lowerCamelCase       :Optional[Any]=False						,							**_lowerCamelCase       :Any						,							):
       super().__init__(
           vocab_file=_lowerCamelCase						,							tokenizer_file=_lowerCamelCase						,							clean_up_tokenization_spaces=_lowerCamelCase						,							unk_token=_lowerCamelCase						,							bos_token=_lowerCamelCase						,							eos_token=_lowerCamelCase						,							**_lowerCamelCase						,							)
       __SCREAMING_SNAKE_CASE			:      List[str] 							=	add_bos_token
       __SCREAMING_SNAKE_CASE			:      Union[str, Any] 							=	add_eos_token
       self.update_post_processor()

       __SCREAMING_SNAKE_CASE			:      Optional[int] 							=	vocab_file
       __SCREAMING_SNAKE_CASE			:      Union[str, Any] 							=	False if not self.vocab_file else True

      def 						SCREAMING_SNAKE_CASE_      (      self       :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE			:      Any 							=	self.bos_token
       __SCREAMING_SNAKE_CASE			:      Dict 							=	self.bos_token_id

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

       __SCREAMING_SNAKE_CASE			:      Tuple 							=	f'''{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}'''
       __SCREAMING_SNAKE_CASE			:      int 							=	f'''{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}'''

       __SCREAMING_SNAKE_CASE			:      str 							=	[]
       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			:      List[Any] 							=	processors.TemplateProcessing(
           single=_lowerCamelCase						,							pair=_lowerCamelCase						,							special_tokens=_lowerCamelCase						)

      @property
      def 						SCREAMING_SNAKE_CASE_      (      self       :List[Any]						):
       return self._add_eos_token

      @property
      def 						SCREAMING_SNAKE_CASE_      (      self       :Union[str, Any]						):
       return self._add_bos_token

      @add_eos_token.setter
      def 						SCREAMING_SNAKE_CASE_      (      self       :List[str]						,							_lowerCamelCase       :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE			:      Tuple 							=	value
       self.update_post_processor()

      @add_bos_token.setter
      def 						SCREAMING_SNAKE_CASE_      (      self       :Dict						,							_lowerCamelCase       :List[Any]						):
       __SCREAMING_SNAKE_CASE			:      Any 							=	value
       self.update_post_processor()

      def 						SCREAMING_SNAKE_CASE_      (      self       :List[Any]						,							_lowerCamelCase       :int						,							_lowerCamelCase       :Union[str, Any] = None						):


       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(_lowerCamelCase						):
        logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''						)
        return
       __SCREAMING_SNAKE_CASE			:      Union[str, Any] 							=	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						):
        copyfile(self.vocab_file						,							_lowerCamelCase						)

       return (out_vocab_file,)



      def 						SCREAMING_SNAKE_CASE_      (      self       :List[str]						,							_lowerCamelCase       :Tuple						):
       __SCREAMING_SNAKE_CASE			:      Optional[Any] 							=	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			:      int 							=	[]
       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]:
         __SCREAMING_SNAKE_CASE			:      List[Any] 							=	(
             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]:
        __SCREAMING_SNAKE_CASE			:      Optional[int] 							=	(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"""





#
# Sort large text files in a minimum amount of memory
#
import argparse
import os





class       snake_case		:
      lowerCamelCase__      =			'''block_{0}.dat'''

      def __init__(      self       :int						,							_lowerCamelCase       :Dict						):
       __SCREAMING_SNAKE_CASE			:      List[str] 							=	filename
       __SCREAMING_SNAKE_CASE			:      Tuple 							=	[]

      def 						SCREAMING_SNAKE_CASE_      (      self       :List[Any]						,							_lowerCamelCase       :Tuple						,							_lowerCamelCase       :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE			:      Any 							=	self.BLOCK_FILENAME_FORMAT.format(_lowerCamelCase						)
       with open(_lowerCamelCase						,							'''w'''						) as file:
        file.write(_lowerCamelCase						)
       self.block_filenames.append(_lowerCamelCase						)

      def 						SCREAMING_SNAKE_CASE_      (      self       :int						):
       return self.block_filenames

      def 						SCREAMING_SNAKE_CASE_      (      self       :Tuple						,							_lowerCamelCase       :List[str]						,							_lowerCamelCase       :Optional[Any]=None						):
       __SCREAMING_SNAKE_CASE			:      int 							=	0
       with open(self.filename						) as file:
        while True:
         __SCREAMING_SNAKE_CASE			:      Any 							=	file.readlines(_lowerCamelCase						)

         if lines == []:
          break

         if sort_key is None:
          lines.sort()
         else:
          lines.sort(key=_lowerCamelCase						)

         self.write_block(''''''.join(_lowerCamelCase						)						,							_lowerCamelCase						)
         i += 1



      def 						SCREAMING_SNAKE_CASE_      (      self       :Tuple						):
       map(os.remove						,							self.block_filenames						)







class       snake_case		:

      def 						SCREAMING_SNAKE_CASE_      (      self       :int						,							_lowerCamelCase       :Tuple						):
       __SCREAMING_SNAKE_CASE			:      List[str] 							=	-1
       __SCREAMING_SNAKE_CASE			:      List[str] 							=	None

       for i in range(len(_lowerCamelCase						)						):
        if min_str is None or choices[i] < min_str:
         __SCREAMING_SNAKE_CASE			:      Tuple 							=	i

       return min_index







class       snake_case		:

      def __init__(      self       :str						,							_lowerCamelCase       :Tuple						):
       __SCREAMING_SNAKE_CASE			:      Any 							=	files
       __SCREAMING_SNAKE_CASE			:      str 							=	set()
       __SCREAMING_SNAKE_CASE			:      Dict 							=	len(_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE			:      str 							=	{i: None for i in range(self.num_buffers						)}

      def 						SCREAMING_SNAKE_CASE_      (      self       :Optional[Any]						):
       return {
           i: self.buffers[i] for i in range(self.num_buffers						) if i not in self.empty
       }

      def 						SCREAMING_SNAKE_CASE_      (      self       :Union[str, Any]						):
       for i in range(self.num_buffers						):
        if self.buffers[i] is None and i not in self.empty:
         __SCREAMING_SNAKE_CASE			:      int 							=	self.files[i].readline()

         if self.buffers[i] == "":
          self.empty.add(_lowerCamelCase						)
          self.files[i].close()

       if len(self.empty						) == self.num_buffers:
        return False

       return True



      def 						SCREAMING_SNAKE_CASE_      (      self       :Any						,							_lowerCamelCase       :List[str]						):
       __SCREAMING_SNAKE_CASE			:      Dict 							=	self.buffers[index]
       __SCREAMING_SNAKE_CASE			:      List[Any] 							=	None

       return value







class       snake_case		:

      def __init__(      self       :List[Any]						,							_lowerCamelCase       :Optional[int]						):
       __SCREAMING_SNAKE_CASE			:      Optional[int] 							=	merge_strategy

      def 						SCREAMING_SNAKE_CASE_      (      self       :int						,							_lowerCamelCase       :Tuple						,							_lowerCamelCase       :Any						,							_lowerCamelCase       :str						):
       __SCREAMING_SNAKE_CASE			:      List[Any] 							=	FilesArray(self.get_file_handles(_lowerCamelCase						,							_lowerCamelCase						)						)
       with open(_lowerCamelCase						,							'''w'''						,							_lowerCamelCase						) as outfile:
        while buffers.refresh():
         __SCREAMING_SNAKE_CASE			:      List[Any] 							=	self.merge_strategy.select(buffers.get_dict()						)
         outfile.write(buffers.unshift(_lowerCamelCase						)						)



      def 						SCREAMING_SNAKE_CASE_      (      self       :Union[str, Any]						,							_lowerCamelCase       :int						,							_lowerCamelCase       :Optional[Any]						):
       __SCREAMING_SNAKE_CASE			:      Union[str, Any] 							=	{}

       for i in range(len(_lowerCamelCase						)						):
        __SCREAMING_SNAKE_CASE			:      Optional[int] 							=	open(filenames[i]						,							'''r'''						,							_lowerCamelCase						)  # noqa: UP015

       return files







class       snake_case		:

      def __init__(      self       :Dict						,							_lowerCamelCase       :str						):
       __SCREAMING_SNAKE_CASE			:      int 							=	block_size

      def 						SCREAMING_SNAKE_CASE_      (      self       :Optional[Any]						,							_lowerCamelCase       :List[str]						,							_lowerCamelCase       :Dict=None						):
       __SCREAMING_SNAKE_CASE			:      Dict 							=	self.get_number_blocks(_lowerCamelCase						,							self.block_size						)
       __SCREAMING_SNAKE_CASE			:      Dict 							=	FileSplitter(_lowerCamelCase						)
       splitter.split(self.block_size						,							_lowerCamelCase						)

       __SCREAMING_SNAKE_CASE			:      Any 							=	FileMerger(NWayMerge()						)
       __SCREAMING_SNAKE_CASE			:      List[Any] 							=	self.block_size / (num_blocks + 1)
       merger.merge(splitter.get_block_filenames()						,							filename + '''.out'''						,							_lowerCamelCase						)

       splitter.cleanup()



      def 						SCREAMING_SNAKE_CASE_      (      self       :Dict						,							_lowerCamelCase       :str						,							_lowerCamelCase       :List[Any]						):
       return (os.stat(_lowerCamelCase						).st_size / block_size) + 1







def 		lowerCAmelCase_     (  lowercase_       :							str		):

 '''simple docstring'''






 if string[-1].lower() == "k":
  return int(string[:-1]		) * 1024
 elif string[-1].lower() == "m":
  return int(string[:-1]		) * 1024 * 1024
 elif string[-1].lower() == "g":
  return int(string[:-1]		) * 1024 * 1024 * 1024
 else:
  return int(lowercase_		)




def 		lowerCAmelCase_     (  ):

 '''simple docstring'''






 __SCREAMING_SNAKE_CASE			:      Optional[Any] 							=	argparse.ArgumentParser()
 parser.add_argument(
     '''-m'''			,				'''--mem'''			,				help='''amount of memory to use for sorting'''			,				default='''100M'''		)
 parser.add_argument(
     '''filename'''			,				metavar='''<filename>'''			,				nargs=1			,				help='''name of file to sort'''		)
 __SCREAMING_SNAKE_CASE			:      Optional[Any] 							=	parser.parse_args()

 __SCREAMING_SNAKE_CASE			:      List[str] 							=	ExternalSort(parse_memory(args.mem		)		)
 sorter.sort(args.filename[0]		)


if __name__ == "__main__":
    main()

