
import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
    import tensorflow as tf




class 			UpperCAmelCase_     (					enum.Enum	):


  '''simple docstring'''







  a__       			=						0
  a__       			=						1
  a__       			=						2







@add_end_docstrings(_A	)
class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						"""
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    """
  def __init__(					self     :					Optional[Any]     ,				*UpperCamelCase__     :					Tuple     ,				**UpperCamelCase__     :					Optional[Any]       )     ->      int:







    """simple docstring"""






    super().__init__(*UpperCamelCase__     ,				**UpperCamelCase__       )
    self.check_model_type(
        TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING       )
    if "prefix" not in self._preprocess_params:
      # This is very specific. The logic is quite complex and needs to be done
      # as a "default".
      # It also defines both some preprocess_kwargs and generate_kwargs
      # which is why we cannot put them in their respective methods.
      __magic_name__								=			None
      if self.model.config.prefix is not None:
        __magic_name__								=			self.model.config.prefix
      if prefix is None and self.model.__class__.__name__ in [
          "XLNetLMHeadModel",
          "TransfoXLLMHeadModel",
          "TFXLNetLMHeadModel",
          "TFTransfoXLLMHeadModel",
      ]:
        # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
        __magic_name__								=			self.XL_PREFIX
      if prefix is not None:
        # Recalculate some generate_kwargs linked to prefix.
        __magic_name__	,       __magic_name__	,       __magic_name__								=			self._sanitize_parameters(prefix=UpperCamelCase__     ,				**self._forward_params       )
        __magic_name__								=			{**self._preprocess_params, **preprocess_params}
        __magic_name__								=			{**self._forward_params, **forward_params}
  def 				_lowercase				(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					Optional[int]=None     ,				UpperCamelCase__     :					Optional[Any]=None     ,				UpperCamelCase__     :					str=None     ,				UpperCamelCase__     :					Optional[int]=None     ,				UpperCamelCase__     :					int=None     ,				UpperCamelCase__     :					str=None     ,				UpperCamelCase__     :					List[Any]=None     ,				UpperCamelCase__     :					List[Any]=None     ,				**UpperCamelCase__     :					str     ,				)     ->      List[str]:







    """simple docstring"""






    __magic_name__								=			{}
    if prefix is not None:
      __magic_name__								=			prefix
    if prefix:
      __magic_name__								=			self.tokenizer(
          UpperCamelCase__     ,				padding=UpperCamelCase__     ,				add_special_tokens=UpperCamelCase__     ,				return_tensors=self.framework       )
      __magic_name__								=			prefix_inputs["""input_ids"""].shape[-1]

    if handle_long_generation is not None:
      if handle_long_generation not in {"hole"}:
        raise ValueError(
            F'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'''
            """ [None, 'hole']"""       )
      __magic_name__								=			handle_long_generation

    preprocess_params.update(UpperCamelCase__       )
    __magic_name__								=			generate_kwargs

    __magic_name__								=			{}
    if return_full_text is not None and return_type is None:
      if return_text is not None:
        raise ValueError("""`return_text` is mutually exclusive with `return_full_text`"""       )
      if return_tensors is not None:
        raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`"""       )
      __magic_name__								=			ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
    if return_tensors is not None and return_type is None:
      if return_text is not None:
        raise ValueError("""`return_text` is mutually exclusive with `return_tensors`"""       )
      __magic_name__								=			ReturnType.TENSORS
    if return_type is not None:
      __magic_name__								=			return_type
    if clean_up_tokenization_spaces is not None:
      __magic_name__								=			clean_up_tokenization_spaces

    if stop_sequence is not None:
      __magic_name__								=			self.tokenizer.encode(UpperCamelCase__     ,				add_special_tokens=UpperCamelCase__       )
      if len(UpperCamelCase__       ) > 1:
        warnings.warn(
            """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
            """ the stop sequence will be used as the stop sequence string in the interim."""       )
      __magic_name__								=			stop_sequence_ids[0]

    return preprocess_params, forward_params, postprocess_params
  def 				_lowercase				(					self     :					Dict     ,				*UpperCamelCase__     :					Any     ,				**UpperCamelCase__     :					Any       )     ->      Tuple:







    """simple docstring"""






    if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
      kwargs.update({"""add_space_before_punct_symbol""": True}       )

    return super()._parse_and_tokenize(*UpperCamelCase__     ,				**UpperCamelCase__       )
  def __call__(					self     :					List[Any]     ,				UpperCamelCase__     :					Dict     ,				**UpperCamelCase__     :					Optional[Any]       )     ->      str:







    """simple docstring"""






    return super().__call__(UpperCamelCase__     ,				**UpperCamelCase__       )
  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					str     ,				UpperCamelCase__     :					Optional[int]=""     ,				UpperCamelCase__     :					List[Any]=None     ,				**UpperCamelCase__     :					Union[str, Any]       )     ->      Dict:







    """simple docstring"""






    __magic_name__								=			self.tokenizer(
        prefix + prompt_text     ,				padding=UpperCamelCase__     ,				add_special_tokens=UpperCamelCase__     ,				return_tensors=self.framework       )
    __magic_name__								=			prompt_text

    if handle_long_generation == "hole":
      __magic_name__								=			inputs["""input_ids"""].shape[-1]
      if "max_new_tokens" in generate_kwargs:
        __magic_name__								=			generate_kwargs["""max_new_tokens"""]
      else:
        __magic_name__								=			generate_kwargs.get("""max_length"""     ,				self.model.config.max_length       ) - cur_len
        if new_tokens < 0:
          raise ValueError("""We cannot infer how many new tokens are expected"""       )
      if cur_len + new_tokens > self.tokenizer.model_max_length:
        __magic_name__								=			self.tokenizer.model_max_length - new_tokens
        if keep_length <= 0:
          raise ValueError(
              """We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
              """ models max length"""       )

        __magic_name__								=			inputs["""input_ids"""][:, -keep_length:]
        if "attention_mask" in inputs:
          __magic_name__								=			inputs["""attention_mask"""][:, -keep_length:]

    return inputs
  def 				_lowercase				(					self     :					Optional[int]     ,				UpperCamelCase__     :					Any     ,				**UpperCamelCase__     :					int       )     ->      Optional[int]:







    """simple docstring"""






    __magic_name__								=			model_inputs["""input_ids"""]
    __magic_name__								=			model_inputs.get("""attention_mask"""     ,				UpperCamelCase__       )
    # Allow empty prompts
    if input_ids.shape[1] == 0:
      __magic_name__								=			None
      __magic_name__								=			None
      __magic_name__								=			1
    else:
      __magic_name__								=			input_ids.shape[0]
    __magic_name__								=			model_inputs.pop("""prompt_text"""       )

    # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
    # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
    __magic_name__								=			generate_kwargs.pop("""prefix_length"""     ,				0       )
    if prefix_length > 0:
      __magic_name__								=			"""max_new_tokens""" in generate_kwargs or (
          """generation_config""" in generate_kwargs
          and generate_kwargs["""generation_config"""].max_new_tokens is not None
      )
      if not has_max_new_tokens:
        __magic_name__								=			generate_kwargs.get("""max_length"""       ) or self.model.config.max_length
        generate_kwargs["max_length"] += prefix_length
      __magic_name__								=			"""min_new_tokens""" in generate_kwargs or (
          """generation_config""" in generate_kwargs
          and generate_kwargs["""generation_config"""].min_new_tokens is not None
      )
      if not has_min_new_tokens and "min_length" in generate_kwargs:
        generate_kwargs["min_length"] += prefix_length

        # BS x SL
    __magic_name__								=			self.model.generate(input_ids=UpperCamelCase__     ,				attention_mask=UpperCamelCase__     ,				**UpperCamelCase__       )
    __magic_name__								=			generated_sequence.shape[0]
    if self.framework == "pt":
      __magic_name__								=			generated_sequence.reshape(UpperCamelCase__     ,				out_b // in_b     ,				*generated_sequence.shape[1:]       )
    elif self.framework == "tf":
      __magic_name__								=			tf.reshape(UpperCamelCase__     ,				(in_b, out_b // in_b, *generated_sequence.shape[1:])       )
    return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





  def 				_lowercase				(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					str     ,				UpperCamelCase__     :					Dict=ReturnType.FULL_TEXT     ,				UpperCamelCase__     :					int=True       )     ->      Tuple:







    """simple docstring"""






    __magic_name__								=			model_outputs["""generated_sequence"""][0]
    __magic_name__								=			model_outputs["""input_ids"""]
    __magic_name__								=			model_outputs["""prompt_text"""]
    __magic_name__								=			generated_sequence.numpy().tolist()
    __magic_name__								=			[]
    for sequence in generated_sequence:
      if return_type == ReturnType.TENSORS:
        __magic_name__								=			{"""generated_token_ids""": sequence}
      elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
        # Decode text
        __magic_name__								=			self.tokenizer.decode(
            UpperCamelCase__     ,				skip_special_tokens=UpperCamelCase__     ,				clean_up_tokenization_spaces=UpperCamelCase__     ,				)

        # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
        if input_ids is None:
          __magic_name__								=			0
        else:
          __magic_name__								=			len(
              self.tokenizer.decode(
                  input_ids[0]     ,				skip_special_tokens=UpperCamelCase__     ,				clean_up_tokenization_spaces=UpperCamelCase__     ,				)       )

        if return_type == ReturnType.FULL_TEXT:
          __magic_name__								=			prompt_text + text[prompt_length:]
        else:
          __magic_name__								=			text[prompt_length:]

        __magic_name__								=			{"""generated_text""": all_text}
      records.append(UpperCamelCase__       )

    return records



import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# 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
__lowerCAmelCase     :	Dict       			=  'src/transformers'
__lowerCAmelCase     :	List[Any]       			=  'docs/source/en'
__lowerCAmelCase     :	str       			=  '.'

def a__       (			A_,	A_,	A_   ):






  '''simple docstring'''





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

  __magic_name__								=			start_index
  while not lines[end_index].startswith(A_   ):
    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 |
__lowerCAmelCase     :	str       			=  'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
__lowerCAmelCase     :	List[str]       			=  re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
__lowerCAmelCase     :	Any       			=  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.
__lowerCAmelCase     :	Optional[int]       			=  re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# This is to make sure the transformers module imported is the one in the repo.
__lowerCAmelCase     :	Union[str, Any]       			=  direct_transformers_import(TRANSFORMERS_PATH)

def a__       (			A_   ):






  '''simple docstring'''





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

def a__       (			A_,	A_   ):






  '''simple docstring'''





  __magic_name__								=			2 if text == """✅""" or text == """❌""" else len(A_   )
  __magic_name__								=			(width - text_length) // 2
  __magic_name__								=			width - text_length - left_indent
  return " " * left_indent + text + " " * right_indent

def a__       (			):






  '''simple docstring'''





  __magic_name__								=			transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
  __magic_name__								=			{
      name: config_maping_names[code]
      for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
      if code in config_maping_names
  }
  __magic_name__								=			{name: config.replace("""Config""",	""""""   ) 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.
  __magic_name__								=			collections.defaultdict(A_   )
  __magic_name__								=			collections.defaultdict(A_   )
  __magic_name__								=			collections.defaultdict(A_   )
  __magic_name__								=			collections.defaultdict(A_   )
  __magic_name__								=			collections.defaultdict(A_   )

  # Let's lookup through all transformers object (once).
  for attr_name in dir(A_   ):
    __magic_name__								=			None
    if attr_name.endswith("""Tokenizer"""   ):
      __magic_name__								=			slow_tokenizers
      __magic_name__								=			attr_name[:-9]
    elif attr_name.endswith("""TokenizerFast"""   ):
      __magic_name__								=			fast_tokenizers
      __magic_name__								=			attr_name[:-13]
    elif _re_tf_models.match(A_   ) is not None:
      __magic_name__								=			tf_models
      __magic_name__								=			_re_tf_models.match(A_   ).groups()[0]
    elif _re_flax_models.match(A_   ) is not None:
      __magic_name__								=			flax_models
      __magic_name__								=			_re_flax_models.match(A_   ).groups()[0]
    elif _re_pt_models.match(A_   ) is not None:
      __magic_name__								=			pt_models
      __magic_name__								=			_re_pt_models.match(A_   ).groups()[0]

    if lookup_dict is not None:
      while len(A_   ) > 0:
        if attr_name in model_name_to_prefix.values():
          __magic_name__								=			True
          break
        # Try again after removing the last word in the name
        __magic_name__								=			"""""".join(camel_case_split(A_   )[:-1]   )

    # Let's build that table!
  __magic_name__								=			list(model_name_to_config.keys()   )
  model_names.sort(key=str.lower   )
  __magic_name__								=			["""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).
  __magic_name__								=			[len(A_   ) + 2 for c in columns]
  __magic_name__								=			max([len(A_   ) for name in model_names]   ) + 2

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

  __magic_name__								=			{True: """✅""", False: """❌"""}
  for name in model_names:
    __magic_name__								=			model_name_to_prefix[name]
    __magic_name__								=			[
        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(A_,	A_   ) for l, w in zip(A_,	A_   )]   ) + "|\n"
  return table

def a__       (			A_=False   ):






  '''simple docstring'''





  __magic_name__	,       __magic_name__	,       __magic_name__	,       __magic_name__								=			_find_text_in_file(
      filename=os.path.join(A_,	"""index.md"""   ),	start_prompt="""<!--This table is updated automatically from the auto modules""",	end_prompt="""<!-- End table-->""",	)
  __magic_name__								=			get_model_table_from_auto_modules()

  if current_table != new_table:
    if overwrite:
      with open(os.path.join(A_,	"""index.md"""   ),	"""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.md` has not been updated. Run `make fix-copies` to fix this."""   )


if __name__ == "__main__":
    __lowerCAmelCase     :	Tuple       			=  argparse.ArgumentParser()
    parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
    __lowerCAmelCase     :	Optional[Any]       			=  parser.parse_args()

    check_model_table(args.fix_and_overwrite)

