


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

__snake_case     =		logging.get_logger(__name__)

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

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

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

# fmt: off
__snake_case     =		'''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 					__lowerCamelCase	(_a		):
       _lowercase    							=      VOCAB_FILES_NAMES
       _lowercase    							=      PRETRAINED_VOCAB_FILES_MAP
       _lowercase    							=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       _lowercase    							=      ["""input_ids""", """attention_mask"""]







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






            '''simple docstring'''




            __UpperCamelCase				=	{} if sp_model_kwargs is None else sp_model_kwargs
            __UpperCamelCase				=	AddedToken(A_,lstrip=A_,rstrip=A_			) if isinstance(A_,A_			) else bos_token
            __UpperCamelCase				=	AddedToken(A_,lstrip=A_,rstrip=A_			) if isinstance(A_,A_			) else eos_token
            __UpperCamelCase				=	AddedToken(A_,lstrip=A_,rstrip=A_			) if isinstance(A_,A_			) else unk_token
            __UpperCamelCase				=	AddedToken(A_,lstrip=A_,rstrip=A_			) if isinstance(A_,A_			) else pad_token
            super().__init__(
                bos_token=A_,eos_token=A_,unk_token=A_,pad_token=A_,add_bos_token=A_,add_eos_token=A_,sp_model_kwargs=self.sp_model_kwargs,clean_up_tokenization_spaces=A_,legacy=A_,**A_,)
            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(A_			)







       def __getstate__(	self:				List[str]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.__dict__.copy()
            __UpperCamelCase				=	None
            __UpperCamelCase				=	self.sp_model.serialized_model_proto()
            return state







       def __setstate__(	self:				Optional[Any],A_:				Optional[Any]			):






            '''simple docstring'''




            __UpperCamelCase				=	d
            __UpperCamelCase				=	spm.SentencePieceProcessor(**self.sp_model_kwargs			)
            self.sp_model.LoadFromSerializedProto(self.sp_model_proto			)







       @property
       def 						snake_case_					(	self:				List[str]			):






            '''simple docstring'''




            return self.sp_model.get_piece_size()







       def 						snake_case_					(	self:				List[str]			):






            '''simple docstring'''




            __UpperCamelCase				=	{self.convert_ids_to_tokens(A_			): i for i in range(self.vocab_size			)}
            vocab.update(self.added_tokens_encoder			)
            return vocab







       def 						snake_case_					(	self:				Tuple,A_:				List[str],**A_:				List[Any]			):






            '''simple docstring'''




            if not self.legacy:
                 __UpperCamelCase				=	SPIECE_UNDERLINE + text.replace(A_,' '			)
            return super().tokenize(A_,**A_			)







       def 						snake_case_					(	self:				List[Any],A_:				str			):






            '''simple docstring'''




            if not self.legacy:
                 __UpperCamelCase				=	text.startswith(A_			)
                 if is_first:
                      __UpperCamelCase				=	text[1:]

            __UpperCamelCase				=	self.sp_model.encode(A_,out_type=A_			)

            if not self.legacy and not is_first and not text.startswith(' '			) and tokens[0].startswith(A_			):
                 __UpperCamelCase				=	([tokens[0][1:]] if len(tokens[0]			) > 1 else []) + tokens[1:]
            return tokens







       def 						snake_case_					(	self:				Dict,A_:				List[Any]			):






            '''simple docstring'''




            return self.sp_model.piece_to_id(A_			)







       def 						snake_case_					(	self:				List[Any],A_:				List[Any]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.sp_model.IdToPiece(A_			)
            return token







       def 						snake_case_					(	self:				str,A_:				Optional[int]			):






            '''simple docstring'''




            __UpperCamelCase				=	[]
            __UpperCamelCase				=	''
            __UpperCamelCase				=	False
            for i, token in enumerate(A_			):
                 # 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(A_			) + token
                      __UpperCamelCase				=	True
                      __UpperCamelCase				=	[]
                 else:
                      current_sub_tokens.append(A_			)
                      __UpperCamelCase				=	False
            out_string += self.sp_model.decode(A_			)
            return out_string







       def 						snake_case_					(	self:				Tuple,A_:				Dict,A_:				Optional[str] = None			):






            '''simple docstring'''




            if not os.path.isdir(A_			):
                 logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''			)
                 return
            __UpperCamelCase				=	os.path.join(
                A_,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']			)

            if os.path.abspath(self.vocab_file			) != os.path.abspath(A_			) and os.path.isfile(self.vocab_file			):
                 copyfile(self.vocab_file,A_			)
            elif not os.path.isfile(self.vocab_file			):
                 with open(A_,'wb'			) as fi:
                      __UpperCamelCase				=	self.sp_model.serialized_model_proto()
                      fi.write(A_			)

            return (out_vocab_file,)







       def 						snake_case_					(	self:				str,A_:				List[Any],A_:				Optional[int]=None			):






            '''simple docstring'''




            __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 						snake_case_					(	self:				Any,A_:				List[int],A_:				Optional[List[int]] = None,A_:				bool = False			):






            '''simple docstring'''




            if already_has_special_tokens:
                 return super().get_special_tokens_mask(
                     token_ids_a=A_,token_ids_a=A_,already_has_special_tokens=A_			)

            __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(A_			)) + eos_token_id
            return (
                bos_token_id
                + ([0] * len(A_			))
                + eos_token_id
                + bos_token_id
                + ([0] * len(A_			))
                + eos_token_id
            )







       def 						snake_case_					(	self:				Optional[Any],A_:				List[int],A_:				Optional[List[int]] = None			):






            '''simple docstring'''




            __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 						snake_case_					(	self:				str,A_:				"Conversation"			):






            '''simple docstring'''




            __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(A_			) 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(A_			) 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=A_			)
                    + [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=A_			)
            return dialog_tokens






import inspect
import json
import os
import tempfile
import unittest

from transformers.models.speech_to_text_a import SpeechaTextaTokenizer
from transformers.models.speech_to_text_a.tokenization_speech_to_text_a import VOCAB_FILES_NAMES

from ...test_tokenization_common import TokenizerTesterMixin



class 					__lowerCamelCase	(_a							,     unittest.TestCase		):
       _lowercase    							=      SpeechaTextaTokenizer
       _lowercase    							=      False







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            super().setUp()

            __UpperCamelCase				=	'<s> <pad> </s> <unk> here@@ a couple of@@ words for the he@@ re@@ vocab'.split(' '			)
            __UpperCamelCase				=	['he re</w> 123', 'here a 1456']
            __UpperCamelCase				=	dict(zip(A_,range(len(A_			)			)			)			)

            __UpperCamelCase				=	{'pad_token': '<pad>', 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>'}

            __UpperCamelCase				=	tempfile.mkdtemp()
            __UpperCamelCase				=	os.path.join(self.tmpdirname,VOCAB_FILES_NAMES['vocab_file']			)
            __UpperCamelCase				=	os.path.join(self.tmpdirname,VOCAB_FILES_NAMES['merges_file']			)

            with open(self.vocab_file,'w',encoding='utf-8'			) as fp:
                 fp.write(json.dumps(A_			) + '\n'			)

            with open(self.merges_file,'w'			) as fp:
                 fp.write('\n'.join(A_			)			)







       def 						snake_case_					(	self:				Optional[int]			):






            '''simple docstring'''




            __UpperCamelCase				=	list(self.get_tokenizer().get_vocab().keys()			)

            self.assertEqual(vocab_keys[0],'<s>'			)
            self.assertEqual(vocab_keys[1],'<pad>'			)
            self.assertEqual(vocab_keys[-1],'vocab'			)
            self.assertEqual(len(A_			),14			)







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            self.assertEqual(self.get_tokenizer().vocab_size,14			)







       def 						snake_case_					(	self:				Dict			):






            '''simple docstring'''




            __UpperCamelCase				=	SpeechaTextaTokenizer.from_pretrained(self.tmpdirname			)

            # make sure @@ is correctly concatenated
            __UpperCamelCase				=	[4, 6, 8, 7, 10]  # ["here@@", "couple", "words", "of@@", "the"]
            __UpperCamelCase				=	tokenizer.decode(A_			)

            self.assertTrue(output_string == 'herecouple words ofthe'			)







       def 						snake_case_					(	self:				int			):






            '''simple docstring'''




            __UpperCamelCase				=	SpeechaTextaTokenizer.from_pretrained(self.tmpdirname			)

            with tempfile.TemporaryDirectory() as tmp_dirname:
                 tokenizer.save_pretrained(A_			)
                 os.remove(os.path.join(A_,'merges.txt'			)			)

                 # load tokenizer without merges file should not throw an error
                 __UpperCamelCase				=	SpeechaTextaTokenizer.from_pretrained(A_			)

            with tempfile.TemporaryDirectory() as tmp_dirname:
                 # save tokenizer and load again
                 tokenizer.save_pretrained(A_			)
                 __UpperCamelCase				=	SpeechaTextaTokenizer.from_pretrained(A_			)

            self.assertIsNotNone(A_			)







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            if not self.test_slow_tokenizer:
                 return

            __UpperCamelCase				=	inspect.signature(self.tokenizer_class.__init__			)
            __UpperCamelCase				=	self.get_tokenizer()

            for parameter_name, parameter in signature.parameters.items():
                 if parameter.default != inspect.Parameter.empty and parameter_name != "merges_file":
                      self.assertIn(A_,tokenizer.init_kwargs			)


