






"""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""": 20_48,
}
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  (		lowercase_       ):





   '''simple docstring'''






   UpperCamelCase__     	=							VOCAB_FILES_NAMES
   UpperCamelCase__     	=							PRETRAINED_VOCAB_FILES_MAP
   UpperCamelCase__     	=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   UpperCamelCase__     	=							["""input_ids""", """attention_mask"""]





   def __init__(       self					, UpperCAmelCase_					, UpperCAmelCase_="<unk>"					, UpperCAmelCase_="<s>"					, UpperCAmelCase_="</s>"					, UpperCAmelCase_=None					, UpperCAmelCase_ = None					, UpperCAmelCase_=True					, UpperCAmelCase_=False					, UpperCAmelCase_=False					, UpperCAmelCase_=True					, **UpperCAmelCase_					, )			->   Union[str, Any]:




          '''simple docstring'''




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





   def __getstate__(       self)			->   Dict:




          '''simple docstring'''




          lowercase__:							Tuple         =     self.__dict__.copy()
          lowercase__:							List[str]         =     None
          lowercase__:							Dict         =     self.sp_model.serialized_model_proto()
          return state





   def __setstate__(       self					, UpperCAmelCase_)			->   Any:




          '''simple docstring'''




          lowercase__:							Dict         =     d
          lowercase__:							List[Any]         =     spm.SentencePieceProcessor(**self.sp_model_kwargs)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto)





   @property
   def __lowercase							(       self)			->   Optional[int]:




          '''simple docstring'''




          return self.sp_model.get_piece_size()





   def __lowercase							(       self)			->   Union[str, Any]:




          '''simple docstring'''




          lowercase__:							int         =     {self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)}
          vocab.update(self.added_tokens_encoder)
          return vocab





   def __lowercase							(       self					, UpperCAmelCase_					, **UpperCAmelCase_)			->   List[str]:




          '''simple docstring'''




          if not self.legacy:
                 lowercase__:							Optional[int]         =     SPIECE_UNDERLINE + text.replace(UpperCAmelCase_					, " ")
          return super().tokenize(UpperCAmelCase_					, **UpperCAmelCase_)





   def __lowercase							(       self					, UpperCAmelCase_)			->   Optional[Any]:




          '''simple docstring'''




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

          lowercase__:							List[str]         =     self.sp_model.encode(UpperCAmelCase_					, out_type=UpperCAmelCase_)

          if not self.legacy and not is_first and not text.startswith(" ") and tokens[0].startswith(UpperCAmelCase_):
                 lowercase__:							Any         =     ([tokens[0][1:]] if len(tokens[0]) > 1 else []) + tokens[1:]
          return tokens





   def __lowercase							(       self					, UpperCAmelCase_)			->   Any:




          '''simple docstring'''




          return self.sp_model.piece_to_id(UpperCAmelCase_)





   def __lowercase							(       self					, UpperCAmelCase_)			->   Optional[Any]:




          '''simple docstring'''




          lowercase__:							List[Any]         =     self.sp_model.IdToPiece(UpperCAmelCase_)
          return token





   def __lowercase							(       self					, UpperCAmelCase_)			->   Any:




          '''simple docstring'''




          lowercase__:							Union[str, Any]         =     []
          lowercase__:							str         =     ""
          lowercase__:							List[str]         =     False
          for i, token in enumerate(UpperCAmelCase_):
                 # 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(UpperCAmelCase_) + token
                        lowercase__:							List[Any]         =     True
                        lowercase__:							Tuple         =     []
                 else:
                        current_sub_tokens.append(UpperCAmelCase_)
                        lowercase__:							Any         =     False
          out_string += self.sp_model.decode(UpperCAmelCase_)
          return out_string





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_ = None)			->   Tuple[str]:




          '''simple docstring'''




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

          if os.path.abspath(self.vocab_file) != os.path.abspath(UpperCAmelCase_) and os.path.isfile(self.vocab_file):
                 copyfile(self.vocab_file					, UpperCAmelCase_)
          elif not os.path.isfile(self.vocab_file):
                 with open(UpperCAmelCase_					, "wb") as fi:
                        lowercase__:							Dict         =     self.sp_model.serialized_model_proto()
                        fi.write(UpperCAmelCase_)

          return (out_vocab_file,)





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_=None)			->   Dict:




          '''simple docstring'''




          lowercase__:							Tuple         =     [self.bos_token_id] if self.add_bos_token else []
          lowercase__:							int         =     [self.eos_token_id] if self.add_eos_token else []

          lowercase__:							List[str]         =     bos_token_id + token_ids_a + eos_token_id

          if token_ids_a is not None:
                 lowercase__:							Dict         =     output + bos_token_id + token_ids_a + eos_token_id

          return output





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_ = None					, UpperCAmelCase_ = False)			->   List[int]:




          '''simple docstring'''




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

          lowercase__:							Any         =     [1] if self.add_bos_token else []
          lowercase__:							Optional[Any]         =     [1] if self.add_eos_token else []

          if token_ids_a is None:
                 return bos_token_id + ([0] * len(UpperCAmelCase_)) + eos_token_id
          return (
              bos_token_id
              + ([0] * len(UpperCAmelCase_))
              + eos_token_id
              + bos_token_id
              + ([0] * len(UpperCAmelCase_))
              + eos_token_id
          )





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_ = None)			->   List[int]:




          '''simple docstring'''




          lowercase__:							Optional[Any]         =     [self.bos_token_id] if self.add_bos_token else []
          lowercase__:							Tuple         =     [self.eos_token_id] if self.add_eos_token else []

          lowercase__:							List[Any]         =     [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 __lowercase							(       self					, UpperCAmelCase_)			->   List[int]:




          '''simple docstring'''




          lowercase__:							List[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...)")

          lowercase__:							List[int]         =     []
          if len(conversation.past_user_inputs) > 0:
                 if not conversation.past_user_inputs[0].startswith(UpperCAmelCase_) or E_SYS not in conversation.past_user_inputs[0]:
                        lowercase__:							int         =     (
                            B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                        )
          elif not dialogue[0][1].startswith(UpperCAmelCase_) or E_SYS not in dialogue[0][1]:
                 lowercase__:							str         =     (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=UpperCAmelCase_)
                  + [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=UpperCAmelCase_)
          return dialog_tokens










"""simple docstring"""






import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata




def        A_					(					UpperCAmelCase__				)     ->     str:
   a   :	Optional[int]						=    min(re.search('^ +'       ,   UpperCAmelCase__				).end() if t.startswith(' '				) else 0 for t in string.splitlines()				)
   return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(UpperCAmelCase__				)]				)


SCREAMING_SNAKE_CASE__				:  Union[str, Any]						= "\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

SCREAMING_SNAKE_CASE__				:  List[str]						= "\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"


SCREAMING_SNAKE_CASE__				:  Dict						= "\\n# Begin of markdown\n\nSome cool dataset card\n"


class 	A_       (     unittest.TestCase   ):





  """simple docstring"""

  def 							lowercase_     (						self						)				->					Any:
     with tempfile.TemporaryDirectory() as tmp_dir:
        a   :	Optional[Any]						=    Path(__UpperCAmelCase						) / 'README.md'
        with open(__UpperCAmelCase  ,					'w+'						) as readme_file:
           readme_file.write(__UpperCAmelCase						)
        a   :	str						=    DatasetMetadata.from_readme(__UpperCAmelCase						)
        self.assertDictEqual(__UpperCAmelCase  ,					{'language': ['zh', 'en'], 'task_ids': ['sentiment-classification']}						)

        with open(__UpperCAmelCase  ,					'w+'						) as readme_file:
           readme_file.write(__UpperCAmelCase						)
        a   :	Optional[Any]						=    DatasetMetadata.from_readme(__UpperCAmelCase						)
        self.assertDictEqual(__UpperCAmelCase  ,					{}						)

        with open(__UpperCAmelCase  ,					'w+'						) as readme_file:
           readme_file.write(__UpperCAmelCase						)
        a   :	str						=    DatasetMetadata.from_readme(__UpperCAmelCase						)
        self.assertEqual(__UpperCAmelCase  ,					{}						)






  def 							lowercase_     (						self						)				->					Tuple:
     a   :	List[str]						=    _dedent(
         '\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            '						)
     assert DatasetMetadata.from_yaml_string(__UpperCAmelCase						)

     a   :	Optional[Any]						=    _dedent(
         '\\n            annotations_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            task_ids:\n            - open-domain-qa\n            '						)
     with self.assertRaises(__UpperCAmelCase						):
        DatasetMetadata.from_yaml_string(__UpperCAmelCase						)

     a   :	List[Any]						=    _dedent(
         '\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - text-classification\n            task_ids:\n            - multi-class-classification\n            paperswithcode_id:\n            - squad\n            configs:\n            - en\n            train-eval-index:\n            - config: en\n              task: text-classification\n              task_id: multi_class_classification\n              splits:\n                train_split: train\n                eval_split: test\n              col_mapping:\n                text: text\n                label: target\n              metrics:\n                - type: accuracy\n                  name: Accuracy\n            extra_gated_prompt: |\n              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:\n              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:\n              1. Researcher shall use the Database only for non-commercial research and educational purposes.\n            extra_gated_fields:\n              Company: text\n              Country: text\n              I agree to use this model for non-commerical use ONLY: checkbox\n            '						)
     assert DatasetMetadata.from_yaml_string(__UpperCAmelCase						)





