

'''simple docstring'''


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 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[Any]:
	if _re_test_backend.search(UpperCamelCase  ) is None:
		return None
	UpperCAmelCase_		:      Optional[Any]       	=					[b[0] for b in _re_backend.findall(UpperCamelCase  )]
	backends.sort()
	return "_and_".join(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    int:
	with open(UpperCamelCase   ,'r'   ,encoding='utf-8'   ,newline='\n'  ) as f:
		UpperCAmelCase_		:      str       	=					f.readlines()

	UpperCAmelCase_		:      Union[str, Any]       	=					0
	while line_index < len(UpperCamelCase  ) and not lines[line_index].startswith('_import_structure = {'  ):
		line_index += 1

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

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

	UpperCAmelCase_		:      Dict       	=					{'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_		:      Dict       	=					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_		:      List[str]       	=					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_		:      str       	=					[]
			# Until we unindent, add backend objects to the list
			while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(' ' * 4  ):
				UpperCAmelCase_		:      int       	=					lines[line_index]
				if _re_import_struct_add_one.search(UpperCamelCase  ) is not None:
					objects.append(_re_import_struct_add_one.search(UpperCamelCase  ).groups()[0]  )
				elif _re_import_struct_add_many.search(UpperCamelCase  ) is not None:
					UpperCAmelCase_		:      Tuple       	=					_re_import_struct_add_many.search(UpperCamelCase  ).groups()[0].split(', '  )
					UpperCAmelCase_		:      Optional[int]       	=					[obj[1:-1] for obj in imports if len(UpperCamelCase  ) > 0]
					objects.extend(UpperCamelCase  )
				elif _re_between_brackets.search(UpperCamelCase  ) is not None:
					UpperCAmelCase_		:      int       	=					_re_between_brackets.search(UpperCamelCase  ).groups()[0].split(', '  )
					UpperCAmelCase_		:      List[Any]       	=					[obj[1:-1] for obj in imports if len(UpperCamelCase  ) > 0]
					objects.extend(UpperCamelCase  )
				elif _re_quote_object.search(UpperCamelCase  ) is not None:
					objects.append(_re_quote_object.search(UpperCamelCase  ).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

			UpperCAmelCase_		:      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
	UpperCAmelCase_		:      Optional[Any]       	=					[]
	while (
	    line_index < len(UpperCamelCase  )
	    and find_backend(lines[line_index]  ) is None
	    and not lines[line_index].startswith('else'  )
	):
		UpperCAmelCase_		:      Optional[Any]       	=					lines[line_index]
		UpperCAmelCase_		:      int       	=					_re_import.search(UpperCamelCase  )
		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_		:      Optional[int]       	=					{'none': objects}
	# Let's continue with backend-specific objects
	while line_index < len(UpperCamelCase  ):
		# If the line is an if is_backend_available, we grab all objects associated.
		UpperCAmelCase_		:      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:
			UpperCAmelCase_		:      Union[str, 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

			UpperCAmelCase_		:      int       	=					[]
			# Until we unindent, add backend objects to the list
			while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(' ' * 8  ):
				UpperCAmelCase_		:      str       	=					lines[line_index]
				UpperCAmelCase_		:      Dict       	=					_re_import.search(UpperCamelCase  )
				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

			UpperCAmelCase_		:      Optional[Any]       	=					objects
		else:
			line_index += 1

	return import_dict_objects, type_hint_objects







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    List[str]:

	def find_duplicates(UpperCamelCase  ):
		return [k for k, v in collections.Counter(UpperCamelCase  ).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_		:      int       	=					[]
	for key in import_dict_objects.keys():
		UpperCAmelCase_		:      str       	=					find_duplicates(import_dict_objects[key]  )
		if duplicate_imports:
			errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}"""  )
		UpperCAmelCase_		:      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]  )  ):
			UpperCAmelCase_		:      Tuple       	=					'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 						SCREAMING_SNAKE_CASE(  )    ->    Dict:
	UpperCAmelCase_		:      str       	=					[]
	for root, _, files in os.walk(UpperCamelCase  ):
		if "__init__.py" in files:
			UpperCAmelCase_		:      Union[str, Any]       	=					os.path.join(UpperCamelCase   ,'__init__.py'  )
			UpperCAmelCase_		:      Tuple       	=					parse_init(UpperCamelCase  )
			if objects is not None:
				UpperCAmelCase_		:      List[Any]       	=					analyze_results(*UpperCamelCase  )
				if len(UpperCamelCase  ) > 0:
					UpperCAmelCase_		:      Any       	=					f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"""
					failures.append('\n'.join(UpperCamelCase  )  )
	if len(UpperCamelCase  ) > 0:
		raise ValueError('\n\n'.join(UpperCamelCase  )  )







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


lowerCAmelCase__										= [
    "convert_pytorch_checkpoint_to_tf2",
    "modeling_flax_pytorch_utils",
    "models.esm.openfold_utils",
]







def 						SCREAMING_SNAKE_CASE(  )    ->    Optional[Any]:
	# This is to make sure the transformers module imported is the one in the repo.
	from transformers.utils import direct_transformers_import

	UpperCAmelCase_		:      int       	=					direct_transformers_import(UpperCamelCase  )

	UpperCAmelCase_		:      Optional[int]       	=					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(UpperCamelCase   ,'__init__.py'  )   ,'r'  ) as f:
		UpperCAmelCase_		:      Dict       	=					f.read()
	import_structure_keys.update(set(re.findall(r'import_structure\[\"([^\"]*)\"\]'   ,UpperCamelCase  )  )  )

	UpperCAmelCase_		:      Union[str, Any]       	=					[
	    module
	    for module in get_transformers_submodules()
	    if module not in IGNORE_SUBMODULES and module not in import_structure_keys
	]

	if len(UpperCamelCase  ) > 0:
		UpperCAmelCase_		:      str       	=					'\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()









'''simple docstring'''


from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
						import tensorflow as tf

						from ..tf_utils import stable_softmax


if is_torch_available():
						import torch


lowerCAmelCase__										= logging.get_logger(__name__)



@add_end_docstrings(
    a_,					r"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    ",					)
class 					lowercase						(  a_ ):


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								if self.framework == "tf":
									UpperCAmelCase_		:      Dict       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
								elif self.framework == "pt":
									UpperCAmelCase_		:      Any       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case)
								else:
									raise ValueError('Unsupported framework')
								return masked_index


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								UpperCAmelCase_		:      Optional[int]       	=					self.get_masked_index(_snake_case)
								UpperCAmelCase_		:      int       	=					np.prod(masked_index.shape)
								if numel < 1:
									raise PipelineException(
									    'fill-mask'    ,			self.model.base_model_prefix    ,			F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""    ,			)


							def 						_snake_case							(			self    ,			_snake_case)							->				int:
								if isinstance(_snake_case    ,			_snake_case):
									for model_input in model_inputs:
										self._ensure_exactly_one_mask_token(model_input['input_ids'][0])
								else:
									for input_ids in model_inputs["input_ids"]:
										self._ensure_exactly_one_mask_token(_snake_case)


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None    ,			**_snake_case)							->				Dict[str, GenericTensor]:
								if return_tensors is None:
									UpperCAmelCase_		:      Optional[Any]       	=					self.framework
								UpperCAmelCase_		:      str       	=					self.tokenizer(_snake_case    ,			return_tensors=_snake_case)
								self.ensure_exactly_one_mask_token(_snake_case)
								return model_inputs


							def 						_snake_case							(			self    ,			_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      List[str]       	=					self.model(**_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					model_inputs['input_ids']
								return model_outputs


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=5    ,			_snake_case=None)							->				str:
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
									UpperCAmelCase_		:      Optional[int]       	=					target_ids.shape[0]
								UpperCAmelCase_		:      Union[str, Any]       	=					model_outputs['input_ids'][0]
								UpperCAmelCase_		:      Optional[Any]       	=					model_outputs['logits']

								if self.framework == "tf":
									UpperCAmelCase_		:      Optional[int]       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

									UpperCAmelCase_		:      Tuple       	=					outputs.numpy()

									UpperCAmelCase_		:      Dict       	=					outputs[0, masked_index, :]
									UpperCAmelCase_		:      List[str]       	=					stable_softmax(_snake_case    ,			axis=-1)
									if target_ids is not None:
										UpperCAmelCase_		:      str       	=					tf.gather_nd(tf.squeeze(_snake_case    ,			0)    ,			target_ids.reshape(-1    ,			1))
										UpperCAmelCase_		:      str       	=					tf.expand_dims(_snake_case    ,			0)

									UpperCAmelCase_		:      int       	=					tf.math.top_k(_snake_case    ,			k=_snake_case)
									UpperCAmelCase_	,    UpperCAmelCase_		:      Dict       	=					topk.values.numpy(), topk.indices.numpy()
								else:
									UpperCAmelCase_		:      List[str]       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case).squeeze(-1)
									# Fill mask pipeline supports only one ${mask_token} per sample

									UpperCAmelCase_		:      int       	=					outputs[0, masked_index, :]
									UpperCAmelCase_		:      str       	=					logits.softmax(dim=-1)
									if target_ids is not None:
										UpperCAmelCase_		:      List[str]       	=					probs[..., target_ids]

									UpperCAmelCase_	,    UpperCAmelCase_		:      Union[str, Any]       	=					probs.topk(_snake_case)

								UpperCAmelCase_		:      Optional[Any]       	=					[]
								UpperCAmelCase_		:      str       	=					values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist()    ,			predictions.tolist())):
									UpperCAmelCase_		:      Union[str, Any]       	=					[]
									for v, p in zip(_values    ,			_predictions):
										# Copy is important since we're going to modify this array in place
										UpperCAmelCase_		:      Union[str, Any]       	=					input_ids.numpy().copy()
										if target_ids is not None:
											UpperCAmelCase_		:      str       	=					target_ids[p].tolist()

										UpperCAmelCase_		:      Union[str, Any]       	=					p
										# Filter padding out:
										UpperCAmelCase_		:      List[str]       	=					tokens[np.where(tokens != self.tokenizer.pad_token_id)]
										# Originally we skip special tokens to give readable output.
										# For multi masks though, the other [MASK] would be removed otherwise
										# making the output look odd, so we add them back
										UpperCAmelCase_		:      Union[str, Any]       	=					self.tokenizer.decode(_snake_case    ,			skip_special_tokens=_snake_case)
										UpperCAmelCase_		:      Tuple       	=					{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]), 'sequence': sequence}
										row.append(_snake_case)
									result.append(_snake_case)
								if single_mask:
									return result[0]
								return result


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None)							->				List[str]:
								if isinstance(_snake_case    ,			_snake_case):
									UpperCAmelCase_		:      List[str]       	=					[targets]
								try:
									UpperCAmelCase_		:      Optional[int]       	=					self.tokenizer.get_vocab()
								except Exception:
									UpperCAmelCase_		:      Union[str, Any]       	=					{}
								UpperCAmelCase_		:      List[Any]       	=					[]
								for target in targets:
									UpperCAmelCase_		:      Optional[int]       	=					vocab.get(_snake_case    ,			_snake_case)
									if id_ is None:
										UpperCAmelCase_		:      int       	=					self.tokenizer(
										    _snake_case    ,			add_special_tokens=_snake_case    ,			return_attention_mask=_snake_case    ,			return_token_type_ids=_snake_case    ,			max_length=1    ,			truncation=_snake_case    ,			)['input_ids']
										if len(_snake_case) == 0:
											logger.warning(
											    F"""The specified target token `{target}` does not exist in the model vocabulary. """
											    'We cannot replace it with anything meaningful, ignoring it')
											continue
										UpperCAmelCase_		:      Tuple       	=					input_ids[0]
										# XXX: If users encounter this pass
										# it becomes pretty slow, so let's make sure
										# The warning enables them to fix the input to
										# get faster performance.
										logger.warning(
										    F"""The specified target token `{target}` does not exist in the model vocabulary. """
										    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.""")
									target_ids.append(id_)
								UpperCAmelCase_		:      Union[str, Any]       	=					list(set(_snake_case))
								if len(_snake_case) == 0:
									raise ValueError('At least one target must be provided when passed.')
								UpperCAmelCase_		:      Dict       	=					np.array(_snake_case)
								return target_ids


							def 						_snake_case							(			self    ,			_snake_case=None    ,			_snake_case=None)							->				Dict:
								UpperCAmelCase_		:      str       	=					{}

								if targets is not None:
									UpperCAmelCase_		:      Dict       	=					self.get_target_ids(_snake_case    ,			_snake_case)
									UpperCAmelCase_		:      Optional[int]       	=					target_ids

								if top_k is not None:
									UpperCAmelCase_		:      List[str]       	=					top_k

								if self.tokenizer.mask_token_id is None:
									raise PipelineException(
									    'fill-mask'    ,			self.model.base_model_prefix    ,			'The tokenizer does not define a `mask_token`.')
								return {}, {}, postprocess_params





							def __call__(			self    ,			_snake_case    ,			*_snake_case    ,			**_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      Any       	=					super().__call__(_snake_case    ,			**_snake_case)
								if isinstance(_snake_case    ,			_snake_case) and len(_snake_case) == 1:
									return outputs[0]
								return outputs






