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


__lowerCamelCase   :						Dict				=			'''src/transformers'''


# Matches is_xxx_available()
__lowerCamelCase   :						Optional[Any]				=			re.compile(R'''is\_([a-z_]*)_available()''')
# Catches a one-line _import_struct = {xxx}
__lowerCamelCase   :						Dict				=			re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__lowerCamelCase   :						List[str]				=			re.compile(R'''\s+\"\S*\":\s+\[([^\]]*)\]''')
# Catches a line if not is_foo_available
__lowerCamelCase   :						List[str]				=			re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''')
# Catches a line _import_struct["bla"].append("foo")
__lowerCamelCase   :						Tuple				=			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   :						Dict				=			re.compile('''^\s+\"([^\"]+)\",''')
# Catches a line with objects between brackets only:    ["foo", "bar"],
__lowerCamelCase   :						List[str]				=			re.compile('''^\s+\[([^\]]+)\]''')
# Catches a line with from foo import bar, bla, boo
__lowerCamelCase   :						Dict				=			re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
# Catches a line with try:
__lowerCamelCase   :						Optional[Any]				=			re.compile(R'''^\s*try:''')
# Catches a line with else:
__lowerCamelCase   :						Optional[Any]				=			re.compile(R'''^\s*else:''')







def 		lowercase__   (		__A:	Optional[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[Any]				):





					'''simple docstring'''






					with open(lowercase_							,'''r'''							,encoding='''utf-8'''							,newline='''\n'''				) as f:
										__magic_name__							:	int    							=							f.readlines()

					__magic_name__							:	Any    							=							0
					while line_index < len(lowercase_				) and not lines[line_index].startswith('''_import_structure = {'''				):
										line_index += 1

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

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

					__magic_name__							:	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.
										__magic_name__							:	List[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:
															__magic_name__							:	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

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

															__magic_name__							:	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
					__magic_name__							:	int    							=							[]
					while (
					    line_index < len(lowercase_				)
					    and find_backend(lines[line_index]				) is None
					    and not lines[line_index].startswith('''else'''				)
					):
										__magic_name__							:	str    							=							lines[line_index]
										__magic_name__							:	Tuple    							=							_re_import.search(lowercase_				)
										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

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

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

															__magic_name__							:	Dict    							=							objects
										else:
															line_index += 1

					return import_dict_objects, type_hint_objects







def 		lowercase__   (		__A:	Optional[Any]							,__A:	List[str]				):





					'''simple docstring'''






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

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





					'''simple docstring'''






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







def 		lowercase__   (		):





					'''simple docstring'''






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


__lowerCamelCase   :						List[Any]				=			[
    '''convert_pytorch_checkpoint_to_tf2''',
    '''modeling_flax_pytorch_utils''',
]







def 		lowercase__   (		):





					'''simple docstring'''






					__magic_name__							:	Tuple    							=							importlib.util.spec_from_file_location(
					    '''transformers'''							,os.path.join(lowercase_							,'''__init__.py'''				)							,submodule_search_locations=[PATH_TO_TRANSFORMERS]							,)
					__magic_name__							:	str    							=							spec.loader.load_module()

					__magic_name__							:	List[Any]    							=							[
					    module
					    for module in get_transformers_submodules()
					    if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
					]
					if len(lowercase_				) > 0:
										__magic_name__							:	List[Any]    							=							"\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()









import warnings
from typing import Dict

import numpy as np

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


if is_tf_available():
	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					return 1.0 / (1.0 + np.exp(-_outputs				))







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					__magic_name__							:	List[str]    							=							np.max(_outputs							,axis=-1							,keepdims=__A				)
					__magic_name__							:	int    							=							np.exp(_outputs - maxes				)
					return shifted_exp / shifted_exp.sum(axis=-1							,keepdims=__A				)


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								='''sigmoid'''
			UpperCamelCase__								='''softmax'''
			UpperCamelCase__								='''none'''






@add_end_docstrings(
    _lowerCamelCase				,R'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''				,)
class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=False
			UpperCamelCase__								=ClassificationFunction.NONE

			def __init__( self			:   Tuple       ,						**lowerCamelCase_			:   Tuple  )						->   List[Any]:
								super().__init__(**lowerCamelCase_  )

								self.check_model_type(
								    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
								    if self.framework == '''tf'''
								    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   Tuple=None       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   Optional[int]=""       ,						**lowerCamelCase_			:   int  )						->   str:
								# Using "" as default argument because we're going to use `top_k=None` in user code to declare
								# "No top_k"
								__magic_name__							:	Dict    							=							tokenizer_kwargs

								__magic_name__							:	Dict    							=							{}
								if hasattr(self.model.config       ,						'''return_all_scores'''  ) and return_all_scores is None:
													__magic_name__							:	List[str]    							=							self.model.config.return_all_scores

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) or top_k is None:
													__magic_name__							:	Dict    							=							top_k
													__magic_name__							:	List[Any]    							=							False
								elif return_all_scores is not None:
													warnings.warn(
													    '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
													    ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''       ,						lowerCamelCase_       ,						)
													if return_all_scores:
																		__magic_name__							:	str    							=							None
													else:
																		__magic_name__							:	int    							=							1

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													__magic_name__							:	str    							=							ClassificationFunction[function_to_apply.upper()]

								if function_to_apply is not None:
													__magic_name__							:	List[str]    							=							function_to_apply
								return preprocess_params, {}, postprocess_params

			def __call__( self			:   Optional[Any]       ,						*lowerCamelCase_			:   Union[str, Any]       ,						**lowerCamelCase_			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							:	Optional[int]    							=							super().__call__(*lowerCamelCase_       ,						**lowerCamelCase_  )
								# TODO try and retrieve it in a nicer way from _sanitize_parameters.
								__magic_name__							:	int    							=							'''top_k''' not in kwargs
								if isinstance(args[0]       ,						lowerCamelCase_  ) and _legacy:
													# This pipeline is odd, and return a list when single item is run
													return [result]
								else:
													return result

			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Any       ,						**lowerCamelCase_			:   int  )						->   Dict[str, GenericTensor]:
								__magic_name__							:	Union[str, Any]    							=							self.framework
								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													return self.tokenizer(**lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and len(lowerCamelCase_  ) == 1 and isinstance(inputs[0]       ,						lowerCamelCase_  ) and len(inputs[0]  ) == 2:
													# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
													return self.tokenizer(
													    text=inputs[0][0]       ,						text_pair=inputs[0][1]       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													# This is likely an invalid usage of the pipeline attempting to pass text pairs.
													raise ValueError(
													    '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
													    ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''  )
								return self.tokenizer(lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   str       ,						lowerCamelCase_			:   Dict  )						->   Union[str, Any]:
								return self.model(**lowerCamelCase_  )


			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Dict       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   List[str]=1       ,						lowerCamelCase_			:   Any=True  )						->   int:
								# `_legacy` is used to determine if we're running the naked pipeline and in backward
								# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
								# the more natural result containing the list.
								# Default value before `set_parameters`
								if function_to_apply is None:
													if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																		__magic_name__							:	Union[str, Any]    							=							ClassificationFunction.SIGMOID
													elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																		__magic_name__							:	str    							=							ClassificationFunction.SOFTMAX
													elif hasattr(self.model.config       ,						'''function_to_apply'''  ) and function_to_apply is None:
																		__magic_name__							:	Dict    							=							self.model.config.function_to_apply
													else:
																		__magic_name__							:	Optional[Any]    							=							ClassificationFunction.NONE

								__magic_name__							:	Any    							=							model_outputs['''logits'''][0]
								__magic_name__							:	Optional[int]    							=							outputs.numpy()

								if function_to_apply == ClassificationFunction.SIGMOID:
													__magic_name__							:	List[str]    							=							sigmoid(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.SOFTMAX:
													__magic_name__							:	Optional[int]    							=							softmax(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.NONE:
													__magic_name__							:	Optional[int]    							=							outputs
								else:
													raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}'''  )

								if top_k == 1 and _legacy:
													return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

								__magic_name__							:	Union[str, Any]    							=							[
								    {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(lowerCamelCase_  )
								]
								if not _legacy:
													dict_scores.sort(key=lambda lowerCamelCase_  : x["score"]       ,						reverse=lowerCamelCase_  )
													if top_k is not None:
																		__magic_name__							:	Dict    							=							dict_scores[:top_k]
								return dict_scores



