


"""simple docstring"""







import collections
import importlib.util
import os
import re
from pathlib import Path


lowerCAmelCase__      				=   '''src/transformers'''


# Matches is_xxx_available()
lowerCAmelCase__      				=   re.compile(r'''is\_([a-z_]*)_available()''')
# Catches a one-line _import_struct = {xxx}
lowerCAmelCase__      				=   re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
lowerCAmelCase__      				=   re.compile(r'''\s+"\S*":\s+\[([^\]]*)\]''')
# Catches a line if not is_foo_available
lowerCAmelCase__      				=   re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''')
# Catches a line _import_struct["bla"].append("foo")
lowerCAmelCase__      				=   re.compile(r'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
lowerCAmelCase__      				=   re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''')
# Catches a line with an object between quotes and a comma:     "MyModel",
lowerCAmelCase__      				=   re.compile('''^\s+"([^"]+)",''')
# Catches a line with objects between brackets only:    ["foo", "bar"],
lowerCAmelCase__      				=   re.compile('''^\s+\[([^\]]+)\]''')
# Catches a line with from foo import bar, bla, boo
lowerCAmelCase__      				=   re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
# Catches a line with try:
lowerCAmelCase__      				=   re.compile(r'''^\s*try:''')
# Catches a line with else:
lowerCAmelCase__      				=   re.compile(r'''^\s*else:''')
def 					a__			(				SCREAMING_SNAKE_CASE    :    Dict				):


  '''simple docstring'''







  if _re_test_backend.search(SCREAMING_SNAKE_CASE				) is None:
    return None
  lowerCAmelCase     :     Dict								=							[b[0] for b in _re_backend.findall(SCREAMING_SNAKE_CASE				)]
  backends.sort()
  return "_and_".join(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[Any]				):


  '''simple docstring'''







  with open(SCREAMING_SNAKE_CASE				,      "r"				,      encoding="utf-8"				,      newline="\n"				) as f:
    lowerCAmelCase     :     Tuple								=							f.readlines()

  lowerCAmelCase     :     Any								=							0
  while line_index < len(SCREAMING_SNAKE_CASE				) and not lines[line_index].startswith("_import_structure = {"				):
    line_index += 1

  # If this is a traditional init, just return.
  if line_index >= len(SCREAMING_SNAKE_CASE				):
    return None

  # First grab the objects without a specific backend in _import_structure
  lowerCAmelCase     :     List[Any]								=							[]
  while not lines[line_index].startswith("if TYPE_CHECKING"				) and find_backend(lines[line_index]				) is None:
    lowerCAmelCase     :     Any								=							lines[line_index]
    # If we have everything on a single line, let's deal with it.
    if _re_one_line_import_struct.search(SCREAMING_SNAKE_CASE				):
      lowerCAmelCase     :     int								=							_re_one_line_import_struct.search(SCREAMING_SNAKE_CASE				).groups()[0]
      lowerCAmelCase     :     Optional[int]								=							re.findall("\[([^\]]+)\]"				,      SCREAMING_SNAKE_CASE				)
      for imp in imports:
        objects.extend([obj[1:-1] for obj in imp.split(", "				)]				)
      line_index += 1
      continue
    lowerCAmelCase     :     Optional[Any]								=							_re_import_struct_key_value.search(SCREAMING_SNAKE_CASE				)
    if single_line_import_search is not None:
      lowerCAmelCase     :     List[str]								=							[obj[1:-1] for obj in single_line_import_search.groups()[0].split(", "				) if len(SCREAMING_SNAKE_CASE				) > 0]
      objects.extend(SCREAMING_SNAKE_CASE				)
    elif line.startswith(" " * 8 + "\""				):
      objects.append(line[9:-3]				)
    line_index += 1

  lowerCAmelCase     :     Union[str, Any]								=							{"none": objects}
  # Let's continue with backend-specific objects in _import_structure
  while not lines[line_index].startswith("if TYPE_CHECKING"				):
    # If the line is an if not is_backend_available, we grab all objects associated.
    lowerCAmelCase     :     Union[str, Any]								=							find_backend(lines[line_index]				)
    # Check if the backend declaration is inside a try block:
    if _re_try.search(lines[line_index - 1]				) is None:
      lowerCAmelCase     :     Dict								=							None

    if backend is not None:
      line_index += 1

      # Scroll until we hit the else block of try-except-else
      while _re_else.search(lines[line_index]				) is None:
        line_index += 1

      line_index += 1

      lowerCAmelCase     :     int								=							[]
      # Until we unindent, add backend objects to the list
      while len(lines[line_index]				) <= 1 or lines[line_index].startswith(" " * 4				):
        lowerCAmelCase     :     Optional[Any]								=							lines[line_index]
        if _re_import_struct_add_one.search(SCREAMING_SNAKE_CASE				) is not None:
          objects.append(_re_import_struct_add_one.search(SCREAMING_SNAKE_CASE				).groups()[0]				)
        elif _re_import_struct_add_many.search(SCREAMING_SNAKE_CASE				) is not None:
          lowerCAmelCase     :     Optional[int]								=							_re_import_struct_add_many.search(SCREAMING_SNAKE_CASE				).groups()[0].split(", "				)
          lowerCAmelCase     :     str								=							[obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE				) > 0]
          objects.extend(SCREAMING_SNAKE_CASE				)
        elif _re_between_brackets.search(SCREAMING_SNAKE_CASE				) is not None:
          lowerCAmelCase     :     Tuple								=							_re_between_brackets.search(SCREAMING_SNAKE_CASE				).groups()[0].split(", "				)
          lowerCAmelCase     :     List[Any]								=							[obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE				) > 0]
          objects.extend(SCREAMING_SNAKE_CASE				)
        elif _re_quote_object.search(SCREAMING_SNAKE_CASE				) is not None:
          objects.append(_re_quote_object.search(SCREAMING_SNAKE_CASE				).groups()[0]				)
        elif line.startswith(" " * 8 + "\""				):
          objects.append(line[9:-3]				)
        elif line.startswith(" " * 1_2 + "\""				):
          objects.append(line[1_3:-3]				)
        line_index += 1

      lowerCAmelCase     :     Optional[int]								=							objects
    else:
      line_index += 1

    # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
  lowerCAmelCase     :     Optional[Any]								=							[]
  while (
      line_index < len(SCREAMING_SNAKE_CASE				)
      and find_backend(lines[line_index]				) is None
      and not lines[line_index].startswith("else"				)
  ):
    lowerCAmelCase     :     Tuple								=							lines[line_index]
    lowerCAmelCase     :     Dict								=							_re_import.search(SCREAMING_SNAKE_CASE				)
    if single_line_import_search is not None:
      objects.extend(single_line_import_search.groups()[0].split(", "				)				)
    elif line.startswith(" " * 8				):
      objects.append(line[8:-2]				)
    line_index += 1

  lowerCAmelCase     :     Optional[int]								=							{"none": objects}
  # Let's continue with backend-specific objects
  while line_index < len(SCREAMING_SNAKE_CASE				):
    # If the line is an if is_backend_available, we grab all objects associated.
    lowerCAmelCase     :     str								=							find_backend(lines[line_index]				)
    # Check if the backend declaration is inside a try block:
    if _re_try.search(lines[line_index - 1]				) is None:
      lowerCAmelCase     :     Dict								=							None

    if backend is not None:
      line_index += 1

      # Scroll until we hit the else block of try-except-else
      while _re_else.search(lines[line_index]				) is None:
        line_index += 1

      line_index += 1

      lowerCAmelCase     :     Any								=							[]
      # Until we unindent, add backend objects to the list
      while len(lines[line_index]				) <= 1 or lines[line_index].startswith(" " * 8				):
        lowerCAmelCase     :     Union[str, Any]								=							lines[line_index]
        lowerCAmelCase     :     Dict								=							_re_import.search(SCREAMING_SNAKE_CASE				)
        if single_line_import_search is not None:
          objects.extend(single_line_import_search.groups()[0].split(", "				)				)
        elif line.startswith(" " * 1_2				):
          objects.append(line[1_2:-2]				)
        line_index += 1

      lowerCAmelCase     :     int								=							objects
    else:
      line_index += 1

  return import_dict_objects, type_hint_objects
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[int]				,      SCREAMING_SNAKE_CASE    :    Union[str, Any]				):


  '''simple docstring'''







  def find_duplicates(SCREAMING_SNAKE_CASE    :    List[Any]				):
    return [k for k, v in collections.Counter(SCREAMING_SNAKE_CASE				).items() if v > 1]

  if list(import_dict_objects.keys()				) != list(type_hint_objects.keys()				):
    return ["Both sides of the init do not have the same backends!"]

  lowerCAmelCase     :     Dict								=							[]
  for key in import_dict_objects.keys():
    lowerCAmelCase     :     Optional[Any]								=							find_duplicates(import_dict_objects[key]				)
    if duplicate_imports:
      errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}"""				)
    lowerCAmelCase     :     Dict								=							find_duplicates(type_hint_objects[key]				)
    if duplicate_type_hints:
      errors.append(f"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}"""				)

    if sorted(set(import_dict_objects[key]				)				) != sorted(set(type_hint_objects[key]				)				):
      lowerCAmelCase     :     List[Any]								=							"base imports" if key == "none" else f"""{key} backend"""
      errors.append(f"""Differences for {name}:"""				)
      for a in type_hint_objects[key]:
        if a not in import_dict_objects[key]:
          errors.append(f"""  {a} in TYPE_HINT but not in _import_structure."""				)
      for a in import_dict_objects[key]:
        if a not in type_hint_objects[key]:
          errors.append(f"""  {a} in _import_structure but not in TYPE_HINT."""				)
  return errors
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Tuple								=							[]
  for root, _, files in os.walk(SCREAMING_SNAKE_CASE				):
    if "__init__.py" in files:
      lowerCAmelCase     :     Any								=							os.path.join(SCREAMING_SNAKE_CASE				,      "__init__.py"				)
      lowerCAmelCase     :     List[Any]								=							parse_init(SCREAMING_SNAKE_CASE				)
      if objects is not None:
        lowerCAmelCase     :     Any								=							analyze_results(*SCREAMING_SNAKE_CASE				)
        if len(SCREAMING_SNAKE_CASE				) > 0:
          lowerCAmelCase     :     Tuple								=							f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"""
          failures.append("\n".join(SCREAMING_SNAKE_CASE				)				)
  if len(SCREAMING_SNAKE_CASE				) > 0:
    raise ValueError("\n\n".join(SCREAMING_SNAKE_CASE				)				)
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Any								=							[]
  for path, directories, files in os.walk(SCREAMING_SNAKE_CASE				):
    for folder in directories:
      # Ignore private modules
      if folder.startswith("_"				):
        directories.remove(SCREAMING_SNAKE_CASE				)
        continue
      # Ignore leftovers from branches (empty folders apart from pycache)
      if len(list((Path(SCREAMING_SNAKE_CASE				) / folder).glob("*.py"				)				)				) == 0:
        continue
      lowerCAmelCase     :     int								=							str((Path(SCREAMING_SNAKE_CASE				) / folder).relative_to(SCREAMING_SNAKE_CASE				)				)
      lowerCAmelCase     :     Tuple								=							short_path.replace(os.path.sep				,      "."				)
      submodules.append(SCREAMING_SNAKE_CASE				)
    for fname in files:
      if fname == "__init__.py":
        continue
      lowerCAmelCase     :     Dict								=							str((Path(SCREAMING_SNAKE_CASE				) / fname).relative_to(SCREAMING_SNAKE_CASE				)				)
      lowerCAmelCase     :     str								=							short_path.replace(".py"				,      ""				).replace(os.path.sep				,      "."				)
      if len(submodule.split("."				)				) == 1:
        submodules.append(SCREAMING_SNAKE_CASE				)
  return submodules


lowerCAmelCase__      				=   [
    '''convert_pytorch_checkpoint_to_tf2''',
    '''modeling_flax_pytorch_utils''',
]
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     int								=							importlib.util.spec_from_file_location(
      "transformers"				,      os.path.join(SCREAMING_SNAKE_CASE				,      "__init__.py"				)				,      submodule_search_locations=[PATH_TO_TRANSFORMERS]				,      )
  lowerCAmelCase     :     Optional[int]								=							spec.loader.load_module()

  lowerCAmelCase     :     Any								=							[
      module
      for module in get_transformers_submodules()
      if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
  ]
  if len(SCREAMING_SNAKE_CASE				) > 0:
    lowerCAmelCase     :     Tuple								=							"\n".join(f"""- {module}""" for module in module_not_registered				)
    raise ValueError(
        "The following submodules are not properly registered in the main init of Transformers:\n"
        f"""{list_of_modules}\n"""
        "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value."				)


if __name__ == "__main__":
     check_all_inits()
     check_submodules()










'''simple docstring'''





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 __A			(  enum.Enum						):



 '''simple docstring'''







 __lowerCamelCase    :       Optional[int]          =       0
 __lowerCamelCase    :       Any          =       1
 __lowerCamelCase    :       List[Any]          =       2






@add_end_docstrings(A						)
class __A			(  A						):



 '''simple docstring'''







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



 def __init__(self ,   *A ,   **A       )    ->     Tuple:


      """simple docstring"""



      super().__init__(*A ,   **A       )
      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.
           _a      =  None
           if self.model.config.prefix is not None:
                _a      =  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.
                _a      =  self.XL_PREFIX
           if prefix is not None:
                # Recalculate some generate_kwargs linked to prefix.
                _a  ,    _a  ,    _a      =  self._sanitize_parameters(prefix=A ,   **self._forward_params       )
                _a      =  {**self._preprocess_params, **preprocess_params}
                _a      =  {**self._forward_params, **forward_params}



 def 					a__  (self ,   A=None ,   A=None ,   A=None ,   A=None ,   A=None ,   A=None ,   A=None ,   A=None ,   **A ,   )    ->     str:


      """simple docstring"""



      _a      =  {}
      if prefix is not None:
           _a      =  prefix
      if prefix:
           _a      =  self.tokenizer(
               A ,   padding=A ,   add_special_tokens=A ,   return_tensors=self.framework       )
           _a      =  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\']'''       )
           _a      =  handle_long_generation

      preprocess_params.update(A       )
      _a      =  generate_kwargs

      _a      =  {}
      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`'''       )
           _a      =  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`'''       )
           _a      =  ReturnType.TENSORS
      if return_type is not None:
           _a      =  return_type
      if clean_up_tokenization_spaces is not None:
           _a      =  clean_up_tokenization_spaces

      if stop_sequence is not None:
           _a      =  self.tokenizer.encode(A ,   add_special_tokens=A       )
           if len(A       ) > 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.'''       )
           _a      =  stop_sequence_ids[0]

      return preprocess_params, forward_params, postprocess_params



 def 					a__  (self ,   *A ,   **A       )    ->     List[Any]:


      """simple docstring"""



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

      return super()._parse_and_tokenize(*A ,   **A       )



 def __call__(self ,   A ,   **A       )    ->     int:


      """simple docstring"""



      return super().__call__(A ,   **A       )



 def 					a__  (self ,   A ,   A="" ,   A=None ,   **A       )    ->     Any:


      """simple docstring"""



      _a      =  self.tokenizer(
          prefix + prompt_text ,   padding=A ,   add_special_tokens=A ,   return_tensors=self.framework       )
      _a      =  prompt_text

      if handle_long_generation == "hole":
           _a      =  inputs['''input_ids'''].shape[-1]
           if "max_new_tokens" in generate_kwargs:
                _a      =  generate_kwargs['''max_new_tokens''']
           else:
                _a      =  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:
                _a      =  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'''       )

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

      return inputs



 def 					a__  (self ,   A ,   **A       )    ->     Any:


      """simple docstring"""



      _a      =  model_inputs['''input_ids''']
      _a      =  model_inputs.get('''attention_mask''' ,   A       )
      # Allow empty prompts
      if input_ids.shape[1] == 0:
           _a      =  None
           _a      =  None
           _a      =  1
      else:
           _a      =  input_ids.shape[0]
      _a      =  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.
      _a      =  generate_kwargs.pop('''prefix_length''' ,   0       )
      if prefix_length > 0:
           _a      =  '''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:
                _a      =  generate_kwargs.get('''max_length'''       ) or self.model.config.max_length
                generate_kwargs["max_length"] += prefix_length
           _a      =  '''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
      _a      =  self.model.generate(input_ids=A ,   attention_mask=A ,   **A       )
      _a      =  generated_sequence.shape[0]
      if self.framework == "pt":
           _a      =  generated_sequence.reshape(A ,   out_b // in_b ,   *generated_sequence.shape[1:]       )
      elif self.framework == "tf":
           _a      =  tf.reshape(A ,   (in_b, out_b // in_b, *generated_sequence.shape[1:])       )
      return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}



 def 					a__  (self ,   A ,   A=ReturnType.FULL_TEXT ,   A=True       )    ->     str:


      """simple docstring"""



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

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

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

                _a      =  {'''generated_text''': all_text}
           records.append(A       )

      return records



