


'''simple docstring'''



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


__UpperCAmelCase    :str				       =     "src/transformers"


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




def 			_a			(		_lowercase      :			Union[str, Any]						):





					'''simple docstring'''






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




def 			_a			(		_lowercase      :			List[str]						):





					'''simple docstring'''






					with open(_lowercase    ,      '''r'''    ,      encoding='''utf-8'''    ,      newline='''\n'''						) as f:
										__UpperCAmelCase			:				Tuple													=    f.readlines()

					__UpperCAmelCase			:				Optional[int]													=    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
					__UpperCAmelCase			:				Optional[Any]													=    []
					while not lines[line_index].startswith('''if TYPE_CHECKING'''						) and find_backend(lines[line_index]						) is None:
										__UpperCAmelCase			:				str													=    lines[line_index]
										# If we have everything on a single line, let's deal with it.
										if _re_one_line_import_struct.search(_lowercase						):
															__UpperCAmelCase			:				int													=    _re_one_line_import_struct.search(_lowercase						).groups()[0]
															__UpperCAmelCase			:				Any													=    re.findall('''\[([^\]]+)\]'''    ,      _lowercase						)
															for imp in imports:
																				objects.extend([obj[1:-1] for obj in imp.split(''', '''						)]						)
															line_index += 1
															continue
										__UpperCAmelCase			:				int													=    _re_import_struct_key_value.search(_lowercase						)
										if single_line_import_search is not None:
															__UpperCAmelCase			:				Optional[int]													=    [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

					__UpperCAmelCase			:				Optional[int]													=    {'''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			:				List[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			:				Tuple													=    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			:				List[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(_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:
																									__UpperCAmelCase			:				Optional[int]													=    _re_import_struct_add_many.search(_lowercase						).groups()[0].split(''', '''						)
																									__UpperCAmelCase			:				int													=    [obj[1:-1] for obj in imports if len(_lowercase						) > 0]
																									objects.extend(_lowercase						)
																				elif _re_between_brackets.search(_lowercase						) is not None:
																									__UpperCAmelCase			:				Optional[Any]													=    _re_between_brackets.search(_lowercase						).groups()[0].split(''', '''						)
																									__UpperCAmelCase			:				List[Any]													=    [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(''' ''' * 12 + '''"'''						):
																									objects.append(line[13:-3]						)
																				line_index += 1

															__UpperCAmelCase			:				Dict													=    objects
										else:
															line_index += 1

    # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
					__UpperCAmelCase			:				List[str]													=    []
					while (
					    line_index < len(_lowercase						)
					    and find_backend(lines[line_index]						) is None
					    and not lines[line_index].startswith('''else'''						)
					):
										__UpperCAmelCase			:				Any													=    lines[line_index]
										__UpperCAmelCase			:				List[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(''' ''' * 8						):
															objects.append(line[8:-2]						)
										line_index += 1

					__UpperCAmelCase			:				int													=    {'''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.
										__UpperCAmelCase			:				List[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			:				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

															__UpperCAmelCase			:				Tuple													=    []
															# Until we unindent, add backend objects to the list
															while len(lines[line_index]						) <= 1 or lines[line_index].startswith(''' ''' * 8						):
																				__UpperCAmelCase			:				List[Any]													=    lines[line_index]
																				__UpperCAmelCase			:				Optional[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(''' ''' * 12						):
																									objects.append(line[12:-2]						)
																				line_index += 1

															__UpperCAmelCase			:				Tuple													=    objects
										else:
															line_index += 1

					return import_dict_objects, type_hint_objects




def 			_a			(		_lowercase      :			Union[str, Any]    ,      _lowercase      :			Union[str, Any]						):





					'''simple docstring'''






					def find_duplicates(_lowercase      :			Tuple						):
										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!"]

					__UpperCAmelCase			:				Any													=    []
					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			:				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]						)						):
															__UpperCAmelCase			:				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 			_a			(		):





					'''simple docstring'''






					__UpperCAmelCase			:				List[str]													=    []
					for root, _, files in os.walk(_lowercase						):
										if "__init__.py" in files:
															__UpperCAmelCase			:				Any													=    os.path.join(_lowercase    ,      '''__init__.py'''						)
															__UpperCAmelCase			:				List[Any]													=    parse_init(_lowercase						)
															if objects is not None:
																				__UpperCAmelCase			:				Optional[int]													=    analyze_results(*_lowercase						)
																				if len(_lowercase						) > 0:
																									__UpperCAmelCase			:				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 			_a			(		):





					'''simple docstring'''






					__UpperCAmelCase			:				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
															__UpperCAmelCase			:				int													=    str((Path(_lowercase						) / folder).relative_to(_lowercase						)						)
															__UpperCAmelCase			:				Optional[Any]													=    short_path.replace(os.path.sep    ,      '''.'''						)
															submodules.append(_lowercase						)
										for fname in files:
															if fname == "__init__.py":
																				continue
															__UpperCAmelCase			:				int													=    str((Path(_lowercase						) / fname).relative_to(_lowercase						)						)
															__UpperCAmelCase			:				Union[str, Any]													=    short_path.replace('''.py'''    ,      ''''''						).replace(os.path.sep    ,      '''.'''						)
															if len(submodule.split('''.'''						)						) == 1:
																				submodules.append(_lowercase						)
					return submodules


__UpperCAmelCase    :Optional[int]				       =     [
    "convert_pytorch_checkpoint_to_tf2",
    "modeling_flax_pytorch_utils",
]




def 			_a			(		):





					'''simple docstring'''






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

					__UpperCAmelCase			:				Dict													=    [
					    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:
										__UpperCAmelCase			:				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()



'''simple docstring'''



import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


__UpperCAmelCase    :str				       =     "\\n@inproceedings{popovic-2015-chrf,\n    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n    month = sep,\n    year = \"2015\",\n    address = \"Lisbon, Portugal\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W15-3049\",\n    doi = \"10.18653/v1/W15-3049\",\n    pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n    title = \"chr{F}++: words helping character n-grams\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n    month = sep,\n    year = \"2017\",\n    address = \"Copenhagen, Denmark\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W17-4770\",\n    doi = \"10.18653/v1/W17-4770\",\n    pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

__UpperCAmelCase    :Tuple				       =     "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

__UpperCAmelCase    :List[Any]				       =     "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,						_KWARGS_DESCRIPTION )
class 			a       (	datasets.Metric ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Dict    )		->							str:
          if version.parse(scb.__version__    ) < version.parse('''1.4.12'''    ):
               raise ImportWarning(
                   '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'''
                   '''You can install it with `pip install "sacrebleu>=1.4.12"`.'''    )
          return datasets.MetricInfo(
              description=_DESCRIPTION							,				citation=_CITATION							,				homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf'''							,				inputs_description=_KWARGS_DESCRIPTION							,				features=datasets.Features(
                  {
                      '''predictions''': datasets.Value('''string'''							,				id='''sequence'''    ),
                      '''references''': datasets.Sequence(datasets.Value('''string'''							,				id='''sequence'''    )							,				id='''references'''    ),
                  }    )							,				codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf''']							,				reference_urls=[
                  '''https://github.com/m-popovic/chrF''',
              ]							,				)






     def 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	str							,				snake_case  :	int							,				snake_case  :	int = CHRF.CHAR_ORDER							,				snake_case  :	int = CHRF.WORD_ORDER							,				snake_case  :	int = CHRF.BETA							,				snake_case  :	bool = False							,				snake_case  :	bool = False							,				snake_case  :	bool = False							,				)		->							Optional[int]:
          __UpperCAmelCase			:				Any													=    len(references[0]    )
          if any(len(snake_case    ) != references_per_prediction for refs in references    ):
               raise ValueError('''Sacrebleu requires the same number of references for each prediction'''    )
          __UpperCAmelCase			:				int													=    [[refs[i] for refs in references] for i in range(snake_case    )]

          __UpperCAmelCase			:				int													=    CHRF(snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case    )
          __UpperCAmelCase			:				Dict													=    sb_chrf.corpus_score(snake_case							,				snake_case    )

          return {
              "score": output.score,
              "char_order": output.char_order,
              "word_order": output.word_order,
              "beta": output.beta,
          }