
from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFTransfoXLForSequenceClassification,
        TFTransfoXLLMHeadModel,
        TFTransfoXLModel,
    )




class      __A:

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_	,      ):
       UpperCamelCase__				=    parent
       UpperCamelCase__				=    13
       UpperCamelCase__				=    7
       UpperCamelCase__				=    30
       UpperCamelCase__				=    self.seq_length + self.mem_len
       UpperCamelCase__				=    15
       UpperCamelCase__				=    True
       UpperCamelCase__				=    True
       UpperCamelCase__				=    99
       UpperCamelCase__				=    [10, 50, 80]
       UpperCamelCase__				=    32
       UpperCamelCase__				=    32
       UpperCamelCase__				=    4
       UpperCamelCase__				=    8
       UpperCamelCase__				=    1_28
       UpperCamelCase__				=    2
       UpperCamelCase__				=    2
       UpperCamelCase__				=    None
       UpperCamelCase__				=    1
       UpperCamelCase__				=    0
       UpperCamelCase__				=    3
       UpperCamelCase__				=    self.vocab_size - 1
       UpperCamelCase__				=    0.01







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    ids_tensor([self.batch_size, self.seq_length]	,      self.vocab_size						)
       UpperCamelCase__				=    ids_tensor([self.batch_size, self.seq_length]	,      self.vocab_size						)

       UpperCamelCase__				=    None
       if self.use_labels:
            UpperCamelCase__				=    ids_tensor([self.batch_size, self.seq_length]	,      self.vocab_size						)

       UpperCamelCase__				=    TransfoXLConfig(
           vocab_size=self.vocab_size	,      mem_len=self.mem_len	,      clamp_len=self.clamp_len	,      cutoffs=self.cutoffs	,      d_model=self.hidden_size	,      d_embed=self.d_embed	,      n_head=self.num_attention_heads	,      d_head=self.d_head	,      d_inner=self.d_inner	,      div_val=self.div_val	,      n_layer=self.num_hidden_layers	,      eos_token_id=self.eos_token_id	,      pad_token_id=self.vocab_size - 1	,      init_range=self.init_range	,      num_labels=self.num_labels	,      )

       return (config, input_ids_a, input_ids_a, lm_labels)







  def 	UpperCAmelCase_ (self						):
       random.seed(self.seed						)
       tf.random.set_seed(self.seed						)







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    TFTransfoXLModel(SCREAMING_SNAKE_CASE_						)

       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						).to_tuple()

       UpperCamelCase__				=    {'''input_ids''': input_ids_a, '''mems''': mems_a}

       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						).to_tuple()

       self.parent.assertEqual(hidden_states_a.shape	,      (self.batch_size, self.seq_length, self.hidden_size)						)
       self.parent.assertEqual(hidden_states_a.shape	,      (self.batch_size, self.seq_length, self.hidden_size)						)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]	,      [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers	,      )
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]	,      [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers	,      )







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE_						)

       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						).to_tuple()

       UpperCamelCase__				=    {'''input_ids''': input_ids_a, '''labels''': lm_labels}
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						).to_tuple()

       UpperCamelCase__				=    model([input_ids_a, mems_a]						).to_tuple()

       UpperCamelCase__				=    {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels}

       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						).to_tuple()

       self.parent.assertEqual(lm_logits_a.shape	,      (self.batch_size, self.seq_length, self.vocab_size)						)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]	,      [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers	,      )

       self.parent.assertEqual(lm_logits_a.shape	,      (self.batch_size, self.seq_length, self.vocab_size)						)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]	,      [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers	,      )







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						)
       self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.prepare_config_and_inputs()
       (UpperCamelCase__)				=    config_and_inputs
       UpperCamelCase__				=    {'''input_ids''': input_ids_a}
       return config, inputs_dict






@require_tf
class      __A(    __lowerCamelCase    ,				__lowerCamelCase    ,				unittest.TestCase			):

  """simple docstring"""
  SCREAMING_SNAKE_CASE__         =      (
      (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
  )
  SCREAMING_SNAKE_CASE__         =      () if is_tf_available() else ()
  SCREAMING_SNAKE_CASE__         =      (
      {
          """feature-extraction""": TFTransfoXLModel,
          """text-classification""": TFTransfoXLForSequenceClassification,
          """text-generation""": TFTransfoXLLMHeadModel,
          """zero-shot""": TFTransfoXLForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       if pipeline_test_casse_name == "TextGenerationPipelineTests":
            # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
            # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
            # tokenizer.
            return True

       return False







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    TFTransfoXLModelTester(self						)
       UpperCamelCase__				=    ConfigTester(self	,      config_class=SCREAMING_SNAKE_CASE_	,      d_embed=37						)







  def 	UpperCAmelCase_ (self						):
       self.config_tester.run_common_tests()







  def 	UpperCAmelCase_ (self						):
       self.model_tester.set_seed()
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       self.model_tester.set_seed()
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__				=    [TFTransfoXLForSequenceClassification]

       for model_class in self.all_model_classes:
            UpperCamelCase__				=    model_class(SCREAMING_SNAKE_CASE_						)
            assert isinstance(model.get_input_embeddings()	,      tf.keras.layers.Layer						)
            if model_class in list_other_models_with_output_ebd:
                 UpperCamelCase__				=    model.get_output_embeddings()
                 assert isinstance(SCREAMING_SNAKE_CASE_	,      tf.keras.layers.Layer						)
                 UpperCamelCase__				=    model.get_bias()
                 assert name is None
            else:
                 UpperCamelCase__				=    model.get_output_embeddings()
                 assert x is None
                 UpperCamelCase__				=    model.get_bias()
                 assert name is None







  def 	UpperCAmelCase_ (self						):
       # TODO JP: Make TransfoXL XLA compliant
       pass







  @slow
  def 	UpperCAmelCase_ (self						):
       for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCamelCase__				=    TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE_						)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE_						)







  @unittest.skip(reason="""This model doesn\'t play well with fit() due to not returning a single loss."""						)
  def 	UpperCAmelCase_ (self						):
       pass






@require_tf
class      __A(    unittest.TestCase			):

  """simple docstring"""







  @unittest.skip("""Skip test until #12651 is resolved."""						)
  @slow
  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103"""						)
       # fmt: off
       UpperCamelCase__				=    tf.convert_to_tensor([[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0]]	,      dtype=tf.intaa						)  # noqa: E231
       # fmt: on
       #  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>

       # fmt: off
       UpperCamelCase__				=    [33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0,33,1,18_57,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,28,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,0]  # noqa: E231
       # fmt: on
       #  In 1991, the remains of Russian Tsar Nicholas II and his family (
       #  except for Alexei and Maria ) are discovered. The voice of 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. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
       # Nicholas II and his family were discovered. The voice of <unk> young son,
       # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

       UpperCamelCase__				=    model.generate(SCREAMING_SNAKE_CASE_	,      max_length=2_00	,      do_sample=SCREAMING_SNAKE_CASE_						)
       self.assertListEqual(output_ids[0].numpy().tolist()	,      SCREAMING_SNAKE_CASE_						)







import collections
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(r'''^\s+"([^"]+)",''')
# Catches a line with objects between brackets only:    ["foo", "bar"],
lowerCamelCase_						     =					re.compile(r'''^\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 						__magic_name__			(   __a      :	List[Any]						):



     '''simple docstring'''




     if _re_test_backend.search(__a						) is None:
          return None
     UpperCamelCase__				=    [b[0] for b in _re_backend.findall(__a						)]
     backends.sort()
     return "_and_".join(__a						)






def 						__magic_name__			(   __a      :	Dict						):



     '''simple docstring'''




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

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

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

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

     UpperCamelCase__				=    {"""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.
          UpperCamelCase__				=    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:
               UpperCamelCase__				=    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

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

               UpperCamelCase__				=    objects
          else:
               line_index += 1

    # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
     UpperCamelCase__				=    []
     while (
         line_index < len(__a						)
         and find_backend(lines[line_index]						) is None
         and not lines[line_index].startswith("""else"""						)
     ):
          UpperCamelCase__				=    lines[line_index]
          UpperCamelCase__				=    _re_import.search(__a						)
          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

     UpperCamelCase__				=    {"""none""": objects}
     # Let's continue with backend-specific objects
     while line_index < len(__a						):
          # If the line is an if is_backend_available, we grab all objects associated.
          UpperCamelCase__				=    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:
               UpperCamelCase__				=    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

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

               UpperCamelCase__				=    objects
          else:
               line_index += 1

     return import_dict_objects, type_hint_objects






def 						__magic_name__			(   __a      :	Dict	,		__a      :	Dict						):



     '''simple docstring'''




     def find_duplicates(__a      :	Optional[Any]						):
          return [k for k, v in collections.Counter(__a						).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!"]

     UpperCamelCase__				=    []
     for key in import_dict_objects.keys():
          UpperCamelCase__				=    find_duplicates(import_dict_objects[key]						)
          if duplicate_imports:
               errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}"						)
          UpperCamelCase__				=    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]						)						):
               UpperCamelCase__				=    """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 						__magic_name__			(   ):



     '''simple docstring'''




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






def 						__magic_name__			(   ):



     '''simple docstring'''




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


lowerCamelCase_						     =					[
    '''convert_pytorch_checkpoint_to_tf2''',
    '''modeling_flax_pytorch_utils''',
    '''models.esm.openfold_utils''',
]






def 						__magic_name__			(   ):



     '''simple docstring'''




     from transformers.utils import direct_transformers_import

     UpperCamelCase__				=    direct_transformers_import(__a						)

     UpperCamelCase__				=    set(transformers._import_structure.keys()						)
     # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing
     # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and
     # (potentiall re-) add them.
     with open(os.path.join(__a	,		"""__init__.py"""						)	,		"""r"""						) as f:
          UpperCamelCase__				=    f.read()
     import_structure_keys.update(set(re.findall(R"""import_structure\[\"([^\"]*)\"\]"""	,		__a						)						)						)

     UpperCamelCase__				=    [
         module
         for module in get_transformers_submodules()
         if module not in IGNORE_SUBMODULES and module not in import_structure_keys
     ]

     if len(__a						) > 0:
          UpperCamelCase__				=    """\n""".join(f"- {module}" for module in module_not_registered						)
          raise ValueError(
              """The following submodules are not properly registed 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()





