


"""simple docstring"""







import argparse
import collections
import importlib.util
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
__lowercase          = """src/diffusers"""
__lowercase          = """docs/source/en"""
__lowercase          = """."""


def 	lowercase     (							A_    ,  A_    ,  A_			)-> Optional[int]:
  '''simple docstring'''







  with open(lowerCAmelCase__    ,  "r"    ,  encoding="utf-8"    ,  newline="\n"			) as f:
    a		:						Dict 				=     f.readlines()
  # Find the start prompt.
  a		:						List[Any] 				=     0
  while not lines[start_index].startswith(lowerCAmelCase__			):
    start_index += 1
  start_index += 1

  a		:						List[str] 				=     start_index
  while not lines[end_index].startswith(lowerCAmelCase__			):
    end_index += 1
  end_index -= 1

  while len(lines[start_index]			) <= 1:
    start_index += 1
  while len(lines[end_index]			) <= 1:
    end_index -= 1
  end_index += 1
  return "".join(lines[start_index:end_index]			), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
__lowercase          = """Model|Encoder|Decoder|ForConditionalGeneration"""
# Regexes that match TF/Flax/PT model names.
__lowercase          = re.compile(R"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
__lowercase          = re.compile(R"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
__lowercase          = re.compile(R"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")


# This is to make sure the diffusers module imported is the one in the repo.
__lowercase          = importlib.util.spec_from_file_location(
    """diffusers""",
    os.path.join(TRANSFORMERS_PATH, """__init__.py"""),
    submodule_search_locations=[TRANSFORMERS_PATH],
)
__lowercase          = spec.loader.load_module()


def 	lowercase     (							A_			)-> Dict:
  '''simple docstring'''







  a		:						Optional[Any] 				=     re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)"    ,  lowerCAmelCase__			)
  return [m.group(0			) for m in matches]


def 	lowercase     (							A_    ,  A_			)-> Optional[Any]:
  '''simple docstring'''







  a		:						Any 				=     2 if text == '✅' or text == '❌' else len(lowerCAmelCase__			)
  a		:						int 				=     (width - text_length) // 2
  a		:						str 				=     width - text_length - left_indent
  return " " * left_indent + text + " " * right_indent


def 	lowercase     (							)-> Optional[Any]:
  '''simple docstring'''







  a		:						Optional[Any] 				=     diffusers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
  a		:						Union[str, Any] 				=     {
      name: config_mapping_names[code]
      for code, name in diffusers_module.MODEL_NAMES_MAPPING.items()
      if code in config_mapping_names
  }
  a		:						Union[str, Any] 				=     {name: config.replace("ConfigMixin"    ,  ""			) for name, config in model_name_to_config.items()}

  # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
  a		:						int 				=     collections.defaultdict(lowerCAmelCase__			)
  a		:						List[Any] 				=     collections.defaultdict(lowerCAmelCase__			)
  a		:						Union[str, Any] 				=     collections.defaultdict(lowerCAmelCase__			)
  a		:						str 				=     collections.defaultdict(lowerCAmelCase__			)
  a		:						Dict 				=     collections.defaultdict(lowerCAmelCase__			)

  # Let's lookup through all diffusers object (once).
  for attr_name in dir(lowerCAmelCase__			):
    a		:						List[str] 				=     None
    if attr_name.endswith("Tokenizer"			):
      a		:						List[Any] 				=     slow_tokenizers
      a		:						Dict 				=     attr_name[:-9]
    elif attr_name.endswith("TokenizerFast"			):
      a		:						Any 				=     fast_tokenizers
      a		:						int 				=     attr_name[:-13]
    elif _re_tf_models.match(lowerCAmelCase__			) is not None:
      a		:						List[Any] 				=     tf_models
      a		:						Optional[int] 				=     _re_tf_models.match(lowerCAmelCase__			).groups()[0]
    elif _re_flax_models.match(lowerCAmelCase__			) is not None:
      a		:						List[str] 				=     flax_models
      a		:						int 				=     _re_flax_models.match(lowerCAmelCase__			).groups()[0]
    elif _re_pt_models.match(lowerCAmelCase__			) is not None:
      a		:						Optional[int] 				=     pt_models
      a		:						Any 				=     _re_pt_models.match(lowerCAmelCase__			).groups()[0]

    if lookup_dict is not None:
      while len(lowerCAmelCase__			) > 0:
        if attr_name in model_name_to_prefix.values():
          a		:						Union[str, Any] 				=     True
          break
        # Try again after removing the last word in the name
        a		:						str 				=     ''.join(camel_case_split(lowerCAmelCase__			)[:-1]			)

    # Let's build that table!
  a		:						Union[str, Any] 				=     list(model_name_to_config.keys()			)
  model_names.sort(key=str.lower			)
  a		:						List[Any] 				=     ['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support']
  # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
  a		:						str 				=     [len(lowerCAmelCase__			) + 2 for c in columns]
  a		:						List[Any] 				=     max([len(lowerCAmelCase__			) for name in model_names]			) + 2

  # Build the table per se
  a		:						Dict 				=     '|' + '|'.join([_center_text(lowerCAmelCase__    ,  lowerCAmelCase__			) for c, w in zip(lowerCAmelCase__    ,  lowerCAmelCase__			)]			) + '|\n'
  # Use ":-----:" format to center-aligned table cell texts
  table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths]			) + "|\n"

  a		:						int 				=     {True: '✅', False: '❌'}
  for name in model_names:
    a		:						int 				=     model_name_to_prefix[name]
    a		:						int 				=     [
        name,
        check[slow_tokenizers[prefix]],
        check[fast_tokenizers[prefix]],
        check[pt_models[prefix]],
        check[tf_models[prefix]],
        check[flax_models[prefix]],
    ]
    table += "|" + "|".join([_center_text(lowerCAmelCase__    ,  lowerCAmelCase__			) for l, w in zip(lowerCAmelCase__    ,  lowerCAmelCase__			)]			) + "|\n"
  return table


def 	lowercase     (							A_=False			)-> int:
  '''simple docstring'''







  a		:						str 				=     _find_text_in_file(
      filename=os.path.join(lowerCAmelCase__    ,  "index.mdx"			)    ,  start_prompt="<!--This table is updated automatically from the auto modules"    ,  end_prompt="<!-- End table-->"    ,  )
  a		:						Tuple 				=     get_model_table_from_auto_modules()

  if current_table != new_table:
    if overwrite:
      with open(os.path.join(lowerCAmelCase__    ,  "index.mdx"			)    ,  "w"    ,  encoding="utf-8"    ,  newline="\n"			) as f:
        f.writelines(lines[:start_index] + [new_table] + lines[end_index:]			)
    else:
      raise ValueError(
          "The model table in the `index.mdx` has not been updated. Run `make fix-copies` to fix this."			)


if __name__ == "__main__":
 __lowercase          = argparse.ArgumentParser()
 parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
 __lowercase          = parser.parse_args()

 check_model_table(args.fix_and_overwrite)














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\\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 				__a				(	__A    ):





		'''simple docstring'''



		UpperCAmelCase__   :					Optional[int]					     =    VOCAB_FILES_NAMES
		UpperCAmelCase__   :					Dict					     =    PRETRAINED_VOCAB_FILES_MAP
		UpperCAmelCase__   :					int					     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		UpperCAmelCase__   :					Union[str, Any]					     =    ["""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__			,     ):
						SCREAMING_SNAKE_CASE_ :						str    				= {} if sp_model_kwargs is None else sp_model_kwargs
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else bos_token
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else eos_token
						SCREAMING_SNAKE_CASE_ :						str    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else unk_token
						SCREAMING_SNAKE_CASE_ :						int    				= 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'							)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= legacy
						SCREAMING_SNAKE_CASE_ :						Dict    				= vocab_file
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= add_bos_token
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= add_eos_token
						SCREAMING_SNAKE_CASE_ :						Any    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(UpperCamelCase__							)


		def __getstate__(    self							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= self.__dict__.copy()
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= None
						SCREAMING_SNAKE_CASE_ :						Any    				= self.sp_model.serialized_model_proto()
						return state


		def __setstate__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= d
						SCREAMING_SNAKE_CASE_ :						str    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)


		@property
		def 	__snake_case      (    self							):
						return self.sp_model.get_piece_size()


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= {self.convert_ids_to_tokens(UpperCamelCase__							): i for i in range(self.vocab_size							)}
						vocab.update(self.added_tokens_encoder							)
						return vocab


		def 	__snake_case      (    self			,     UpperCamelCase__			,     **UpperCamelCase__							):
						# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
						# the beginning of the text
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						List[str]    				= SPIECE_UNDERLINE + text.replace(UpperCamelCase__			,     ' '							)
						return super().tokenize(UpperCamelCase__			,     **UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						Any    				= text.startswith(UpperCamelCase__							)
										if is_first:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= text[1:]

						SCREAMING_SNAKE_CASE_ :						Tuple    				= 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__							):
										SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= ([tokens[0][1:]] if len(tokens[0]							) > 1 else []) + tokens[1:]
						return tokens


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						return self.sp_model.piece_to_id(UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.sp_model.IdToPiece(UpperCamelCase__							)
						return token


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= []
						SCREAMING_SNAKE_CASE_ :						int    				= ''
						SCREAMING_SNAKE_CASE_ :						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
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= True
														SCREAMING_SNAKE_CASE_ :						str    				= []
										else:
														current_sub_tokens.append(UpperCamelCase__							)
														SCREAMING_SNAKE_CASE_ :						int    				= False
						out_string += self.sp_model.decode(UpperCamelCase__							)
						return out_string


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None							):
						if not os.path.isdir(UpperCamelCase__							):
										logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''							)
										return
						SCREAMING_SNAKE_CASE_ :						Union[str, 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:
														SCREAMING_SNAKE_CASE_ :						Dict    				= self.sp_model.serialized_model_proto()
														fi.write(UpperCamelCase__							)

						return (out_vocab_file,)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__=None							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						List[str]    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						int    				= bos_token_id + token_ids_a + eos_token_id

						if token_ids_a is not None:
										SCREAMING_SNAKE_CASE_ :						int    				= output + bos_token_id + token_ids_a + eos_token_id

						return output


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None			,     UpperCamelCase__ = False							):
						if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=UpperCamelCase__			,     token_ids_a=UpperCamelCase__			,     already_has_special_tokens=UpperCamelCase__							)

						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= [1] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Union[str, 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 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None							):
						SCREAMING_SNAKE_CASE_ :						Any    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Tuple    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						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 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= 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_ :						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]:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= (
														    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]:
										SCREAMING_SNAKE_CASE_ :						Tuple    				= (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