






import collections
import os
import re
from pathlib import Path


lowerCamelCase : List[str]						   =       '''src/transformers'''


# Matches is_xxx_available()
lowerCamelCase : List[Any]						   =       re.compile(r'''is\_([a-z_]*)_available()''')
# Catches a one-line _import_struct = {xxx}
lowerCamelCase : Any						   =       re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
lowerCamelCase : Union[str, Any]						   =       re.compile(r'''\s+"\S*":\s+\[([^\]]*)\]''')
# Catches a line if not is_foo_available
lowerCamelCase : Dict						   =       re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''')
# Catches a line _import_struct["bla"].append("foo")
lowerCamelCase : Optional[Any]						   =       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 : Any						   =       re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''')
# Catches a line with an object between quotes and a comma:     "MyModel",
lowerCamelCase : str						   =       re.compile(r'''^\s+"([^"]+)",''')
# Catches a line with objects between brackets only:    ["foo", "bar"],
lowerCamelCase : Optional[Any]						   =       re.compile(r'''^\s+\[([^\]]+)\]''')
# Catches a line with from foo import bar, bla, boo
lowerCamelCase : Optional[int]						   =       re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
# Catches a line with try:
lowerCamelCase : str						   =       re.compile(r'''^\s*try:''')
# Catches a line with else:
lowerCamelCase : str						   =       re.compile(r'''^\s*else:''')
def       snake_case_		(     lowerCAmelCase_       :						Union[str, Any]      ):
							if _re_test_backend.search(lowerCAmelCase_      ) is None:
														return None
							__lowercase      :							str				=     [b[0] for b in _re_backend.findall(lowerCAmelCase_      )]
							backends.sort()
							return "_and_".join(lowerCAmelCase_      )
def       snake_case_		(     lowerCAmelCase_       :						Tuple      ):
							with open(lowerCAmelCase_       ,       """r"""       ,       encoding="""utf-8"""       ,       newline="""\n"""      ) as f:
														__lowercase      :							List[Any]				=     f.readlines()

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

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

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

							__lowercase      :							Tuple				=     {"""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.
														__lowercase      :							Optional[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:
																					__lowercase      :							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

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

																					__lowercase      :							List[str]				=     objects
														else:
																					line_index += 1

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

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

																					__lowercase      :							str				=     []
																					# Until we unindent, add backend objects to the list
																					while len(lines[line_index]      ) <= 1 or lines[line_index].startswith(""" """ * 8      ):
																												__lowercase      :							List[Any]				=     lines[line_index]
																												__lowercase      :							List[Any]				=     _re_import.search(lowerCAmelCase_      )
																												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

																					__lowercase      :							List[str]				=     objects
														else:
																					line_index += 1

							return import_dict_objects, type_hint_objects
def       snake_case_		(     lowerCAmelCase_       :						Optional[int]       ,       lowerCAmelCase_       :						List[Any]      ):

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

							__lowercase      :							List[Any]				=     []
							for key in import_dict_objects.keys():
														__lowercase      :							Optional[Any]				=     find_duplicates(import_dict_objects[key]      )
														if duplicate_imports:
																					errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}"      )
														__lowercase      :							int				=     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]      )      ):
																					__lowercase      :							str				=     """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       snake_case_		(     ):
							__lowercase      :							List[str]				=     []
							for root, _, files in os.walk(lowerCAmelCase_      ):
														if "__init__.py" in files:
																					__lowercase      :							Any				=     os.path.join(lowerCAmelCase_       ,       """__init__.py"""      )
																					__lowercase      :							Optional[int]				=     parse_init(lowerCAmelCase_      )
																					if objects is not None:
																												__lowercase      :							List[str]				=     analyze_results(*lowerCAmelCase_      )
																												if len(lowerCAmelCase_      ) > 0:
																																			__lowercase      :							Optional[Any]				=     F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"
																																			failures.append("""\n""".join(lowerCAmelCase_      )      )
							if len(lowerCAmelCase_      ) > 0:
														raise ValueError("""\n\n""".join(lowerCAmelCase_      )      )
def       snake_case_		(     ):
							__lowercase      :							Tuple				=     []
							for path, directories, files in os.walk(lowerCAmelCase_      ):
														for folder in directories:
																					# Ignore private modules
																					if folder.startswith("""_"""      ):
																												directories.remove(lowerCAmelCase_      )
																												continue
																					# Ignore leftovers from branches (empty folders apart from pycache)
																					if len(list((Path(lowerCAmelCase_      ) / folder).glob("""*.py"""      )      )      ) == 0:
																												continue
																					__lowercase      :							Optional[Any]				=     str((Path(lowerCAmelCase_      ) / folder).relative_to(lowerCAmelCase_      )      )
																					__lowercase      :							Optional[Any]				=     short_path.replace(os.path.sep       ,       """."""      )
																					submodules.append(lowerCAmelCase_      )
														for fname in files:
																					if fname == "__init__.py":
																												continue
																					__lowercase      :							Optional[int]				=     str((Path(lowerCAmelCase_      ) / fname).relative_to(lowerCAmelCase_      )      )
																					__lowercase      :							List[str]				=     short_path.replace(""".py"""       ,       """"""      ).replace(os.path.sep       ,       """."""      )
																					if len(submodule.split("""."""      )      ) == 1:
																												submodules.append(lowerCAmelCase_      )
							return submodules


lowerCamelCase : Optional[int]						   =       [
    '''convert_pytorch_checkpoint_to_tf2''',
    '''modeling_flax_pytorch_utils''',
    '''models.esm.openfold_utils''',
]
def       snake_case_		(     ):
							# This is to make sure the transformers module imported is the one in the repo.
							from transformers.utils import direct_transformers_import

							__lowercase      :							List[str]				=     direct_transformers_import(lowerCAmelCase_      )

							__lowercase      :							Tuple				=     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(lowerCAmelCase_       ,       """__init__.py"""      )       ,       """r"""      ) as f:
														__lowercase      :							List[str]				=     f.read()
							import_structure_keys.update(set(re.findall(r"""import_structure\[\"([^\"]*)\"\]"""       ,       lowerCAmelCase_      )      )      )

							__lowercase      :							List[Any]				=     [
							    module
							    for module in get_transformers_submodules()
							    if module not in IGNORE_SUBMODULES and module not in import_structure_keys
							]

							if len(lowerCAmelCase_      ) > 0:
														__lowercase      :							List[Any]				=     """\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()







from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
	from ...processing_utils import ProcessorMixin
	from ...utils import TensorType


lowerCamelCase : Optional[int]						   =       logging.get_logger(__name__)

lowerCamelCase : Tuple						   =       {
    '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''',
}

class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					_A						:			int									=      '''layoutlmv3'''



					def __init__(  self				:	Dict		,     __a				:	List[str]=50265		,     __a				:	str=768		,     __a				:	List[Any]=12		,     __a				:	List[Any]=12		,     __a				:	List[str]=3072		,     __a				:	Optional[Any]="gelu"		,     __a				:	Optional[int]=0.1		,     __a				:	List[Any]=0.1		,     __a				:	Tuple=512		,     __a				:	int=2		,     __a				:	Any=0.02		,     __a				:	Union[str, Any]=1E-5		,     __a				:	List[str]=1		,     __a				:	List[Any]=0		,     __a				:	int=2		,     __a				:	str=1024		,     __a				:	str=128		,     __a				:	List[Any]=128		,     __a				:	Tuple=True		,     __a				:	Optional[int]=32		,     __a				:	Any=128		,     __a				:	List[Any]=64		,     __a				:	Tuple=256		,     __a				:	str=True		,     __a				:	int=True		,     __a				:	Optional[Any]=True		,     __a				:	Any=224		,     __a				:	str=3		,     __a				:	List[str]=16		,     __a				:	Union[str, Any]=None		,     **__a				:	List[Any]		,     )			->  List[str]:


												"""simple docstring"""

												super().__init__(
												    vocab_size=__a		,     hidden_size=__a		,     num_hidden_layers=__a		,     num_attention_heads=__a		,     intermediate_size=__a		,     hidden_act=__a		,     hidden_dropout_prob=__a		,     attention_probs_dropout_prob=__a		,     max_position_embeddings=__a		,     type_vocab_size=__a		,     initializer_range=__a		,     layer_norm_eps=__a		,     pad_token_id=__a		,     bos_token_id=__a		,     eos_token_id=__a		,     **__a		,     )
												__lowercase      :							int				=     max_ad_position_embeddings
												__lowercase      :							Any				=     coordinate_size
												__lowercase      :							Optional[Any]				=     shape_size
												__lowercase      :							str				=     has_relative_attention_bias
												__lowercase      :							int				=     rel_pos_bins
												__lowercase      :							Union[str, Any]				=     max_rel_pos
												__lowercase      :							str				=     has_spatial_attention_bias
												__lowercase      :							str				=     rel_ad_pos_bins
												__lowercase      :							List[Any]				=     max_rel_ad_pos
												__lowercase      :							Tuple				=     text_embed
												__lowercase      :							int				=     visual_embed
												__lowercase      :							Tuple				=     input_size
												__lowercase      :							Dict				=     num_channels
												__lowercase      :							str				=     patch_size
												__lowercase      :							Optional[int]				=     classifier_dropout







class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					_A						:			str									=      version.parse('''1.12'''			)



					@property
					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  Mapping[str, Mapping[int, str]]:


												"""simple docstring"""

												if self.task in ["question-answering", "sequence-classification"]:
																			return OrderedDict(
																			    [
																			        ("""input_ids""", {0: """batch""", 1: """sequence"""}),
																			        ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
																			        ("""bbox""", {0: """batch""", 1: """sequence"""}),
																			        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
																			    ]							)
												else:
																			return OrderedDict(
																			    [
																			        ("""input_ids""", {0: """batch""", 1: """sequence"""}),
																			        ("""bbox""", {0: """batch""", 1: """sequence"""}),
																			        ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
																			        ("""pixel_values""", {0: """batch""", 1: """num_channels"""}),
																			    ]							)



					@property
					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  float:


												"""simple docstring"""

												return 1E-5



					@property
					def       lowerCAmelCase				(  self				:	str							)			->  int:


												"""simple docstring"""

												return 12



					def       lowerCAmelCase				(  self				:	List[Any]		,     __a				:	"ProcessorMixin"		,     __a				:	int = -1		,     __a				:	int = -1		,     __a				:	bool = False		,     __a				:	Optional["TensorType"] = None		,     __a				:	int = 3		,     __a				:	int = 40		,     __a				:	int = 40		,     )			->  Mapping[str, Any]:


												"""simple docstring"""

												setattr(processor.image_processor		,     """apply_ocr"""		,     __a							)

												# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
												__lowercase      :							Tuple				=     compute_effective_axis_dimension(
												    __a		,     fixed_dimension=OnnxConfig.default_fixed_batch		,     num_token_to_add=0							)
												# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
												__lowercase      :							Tuple				=     processor.tokenizer.num_special_tokens_to_add(__a							)
												__lowercase      :							Tuple				=     compute_effective_axis_dimension(
												    __a		,     fixed_dimension=OnnxConfig.default_fixed_sequence		,     num_token_to_add=__a							)
												# Generate dummy inputs according to compute batch and sequence
												__lowercase      :							Union[str, Any]				=     [[""" """.join([processor.tokenizer.unk_token]							) * seq_length]] * batch_size

												# Generate dummy bounding boxes
												__lowercase      :							Tuple				=     [[[48, 84, 73, 128]]] * batch_size

												# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
												# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
												__lowercase      :							Tuple				=     self._generate_dummy_images(__a		,     __a		,     __a		,     __a							)

												__lowercase      :							int				=     dict(
												    processor(
												        __a		,     text=__a		,     boxes=__a		,     return_tensors=__a		,     )							)

												return inputs