






"""simple docstring"""



import argparse
import collections
import importlib.util
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
_snake_case       :      Optional[Any]       =					"src/diffusers"
_snake_case       :      Optional[int]       =					"docs/source/en"
_snake_case       :      int       =					"."




def 						lowerCamelCase_				(  __A  :		List[str]			,	__A  :		str			,	__A  :		List[Any]			):
					with open(__A			,	'r'			,	encoding='utf-8'			,	newline='\n'			) as f:
										lowerCamelCase__				=f.readlines()
					# Find the start prompt.
					lowerCamelCase__				=0
					while not lines[start_index].startswith(__A			):
										start_index += 1
					start_index += 1

					lowerCamelCase__				=start_index
					while not lines[end_index].startswith(__A			):
										end_index += 1
					end_index -= 1

					while len(lines[start_index]			) <= 1:
										start_index += 1
					while len(lines[end_index]			) <= 1:
										end_index -= 1
					end_index += 1
					return "".join(lines[start_index:end_index]			), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
_snake_case       :      int       =					"Model|Encoder|Decoder|ForConditionalGeneration"
# Regexes that match TF/Flax/PT model names.
_snake_case       :      Tuple       =					re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
_snake_case       :      str       =					re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
_snake_case       :      List[str]       =					re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")


# This is to make sure the diffusers module imported is the one in the repo.
_snake_case       :      int       =					importlib.util.spec_from_file_location(
    "diffusers",
    os.path.join(TRANSFORMERS_PATH, "__init__.py"),
    submodule_search_locations=[TRANSFORMERS_PATH],
)
_snake_case       :      Tuple       =					spec.loader.load_module()




def 						lowerCamelCase_				(  __A  :		List[str]			):
					lowerCamelCase__				=re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'			,	__A			)
					return [m.group(0			) for m in matches]




def 						lowerCamelCase_				(  __A  :		Union[str, Any]			,	__A  :		int			):
					lowerCamelCase__				=2 if text == '✅' or text == '❌' else len(__A			)
					lowerCamelCase__				=(width - text_length) // 2
					lowerCamelCase__				=width - text_length - left_indent
					return " " * left_indent + text + " " * right_indent




def 						lowerCamelCase_				(  ):
					lowerCamelCase__				=diffusers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
					lowerCamelCase__				={
					    name: config_mapping_names[code]
					    for code, name in diffusers_module.MODEL_NAMES_MAPPING.items()
					    if code in config_mapping_names
					}
					lowerCamelCase__				={name: config.replace('ConfigMixin'			,	''			) for name, config in model_name_to_config.items()}

					# Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
					lowerCamelCase__				=collections.defaultdict(__A			)
					lowerCamelCase__				=collections.defaultdict(__A			)
					lowerCamelCase__				=collections.defaultdict(__A			)
					lowerCamelCase__				=collections.defaultdict(__A			)
					lowerCamelCase__				=collections.defaultdict(__A			)

					# Let's lookup through all diffusers object (once).
					for attr_name in dir(__A			):
										lowerCamelCase__				=None
										if attr_name.endswith('Tokenizer'			):
															lowerCamelCase__				=slow_tokenizers
															lowerCamelCase__				=attr_name[:-9]
										elif attr_name.endswith('TokenizerFast'			):
															lowerCamelCase__				=fast_tokenizers
															lowerCamelCase__				=attr_name[:-13]
										elif _re_tf_models.match(__A			) is not None:
															lowerCamelCase__				=tf_models
															lowerCamelCase__				=_re_tf_models.match(__A			).groups()[0]
										elif _re_flax_models.match(__A			) is not None:
															lowerCamelCase__				=flax_models
															lowerCamelCase__				=_re_flax_models.match(__A			).groups()[0]
										elif _re_pt_models.match(__A			) is not None:
															lowerCamelCase__				=pt_models
															lowerCamelCase__				=_re_pt_models.match(__A			).groups()[0]

										if lookup_dict is not None:
															while len(__A			) > 0:
																				if attr_name in model_name_to_prefix.values():
																									lowerCamelCase__				=True
																									break
																				# Try again after removing the last word in the name
																				lowerCamelCase__				=''.join(camel_case_split(__A			)[:-1]			)

    # Let's build that table!
					lowerCamelCase__				=list(model_name_to_config.keys()			)
					model_names.sort(key=str.lower			)
					lowerCamelCase__				=['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support']
					# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
					lowerCamelCase__				=[len(__A			) + 2 for c in columns]
					lowerCamelCase__				=max([len(__A			) for name in model_names]			) + 2

					# Build the table per se
					lowerCamelCase__				='|' + '|'.join([_center_text(__A			,	__A			) for c, w in zip(__A			,	__A			)]			) + '|\n'
					# Use ":-----:" format to center-aligned table cell texts
					table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths]			) + "|\n"

					lowerCamelCase__				={True: '✅', False: '❌'}
					for name in model_names:
										lowerCamelCase__				=model_name_to_prefix[name]
										lowerCamelCase__				=[
										    name,
										    check[slow_tokenizers[prefix]],
										    check[fast_tokenizers[prefix]],
										    check[pt_models[prefix]],
										    check[tf_models[prefix]],
										    check[flax_models[prefix]],
										]
										table += "|" + "|".join([_center_text(__A			,	__A			) for l, w in zip(__A			,	__A			)]			) + "|\n"
					return table




def 						lowerCamelCase_				(  __A  :		Union[str, Any]=False			):
					lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				=_find_text_in_file(
					    filename=os.path.join(__A			,	'index.mdx'			)			,	start_prompt='<!--This table is updated automatically from the auto modules'			,	end_prompt='<!-- End table-->'			,	)
					lowerCamelCase__				=get_model_table_from_auto_modules()

					if current_table != new_table:
										if overwrite:
															with open(os.path.join(__A			,	'index.mdx'			)			,	'w'			,	encoding='utf-8'			,	newline='\n'			) as f:
																				f.writelines(lines[:start_index] + [new_table] + lines[end_index:]			)
										else:
															raise ValueError(
															    'The model table in the `index.mdx` has not been updated. Run `make fix-copies` to fix this.'			)


if __name__ == "__main__":
						_snake_case       :      int       =					argparse.ArgumentParser()
						parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
						_snake_case       :      Union[str, Any]       =					parser.parse_args()

						check_model_table(args.fix_and_overwrite)







"""simple docstring"""



import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


_snake_case       :      Dict       =					"\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n"

_snake_case       :      List[str]       =					"\nThis metric wrap the official scoring script for version 2 of the Stanford Question\nAnswering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n\nSQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions\nwritten adversarially by crowdworkers to look similar to answerable ones.\nTo do well on SQuAD2.0, systems must not only answer questions when possible, but also\ndetermine when no answer is supported by the paragraph and abstain from answering.\n"

_snake_case       :      Dict       =					"\nComputes SQuAD v2 scores (F1 and EM).\nArgs:\n    predictions: List of triple for question-answers to score with the following elements:\n        - the question-answer 'id' field as given in the references (see below)\n        - the text of the answer\n        - the probability that the question has no answer\n    references: List of question-answers dictionaries with the following key-values:\n            - 'id': id of the question-answer pair (see above),\n            - 'answers': a list of Dict {'text': text of the answer as a string}\n    no_answer_threshold: float\n        Probability threshold to decide that a question has no answer.\nReturns:\n    'exact': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\n    'total': Number of score considered\n    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'HasAns_f1': The F-score of predicted tokens versus the gold answer\n    'HasAns_total': Number of score considered\n    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'NoAns_f1': The F-score of predicted tokens versus the gold answer\n    'NoAns_total': Number of score considered\n    'best_exact': Best exact match (with varying threshold)\n    'best_exact_thresh': No-answer probability threshold associated to the best exact match\n    'best_f1': Best F1 (with varying threshold)\n    'best_f1_thresh': No-answer probability threshold associated to the best F1\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")\n    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}\n"




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






						def 		lowerCAmelCase   (					self)			->  int:




											"""simple docstring"""





											return datasets.MetricInfo(
											    description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
											        {
											            'predictions': {
											                'id': datasets.Value('string'),
											                'prediction_text': datasets.Value('string'),
											                'no_answer_probability': datasets.Value('float32'),
											            },
											            'references': {
											                'id': datasets.Value('string'),
											                'answers': datasets.features.Sequence(
											                    {'text': datasets.Value('string'), 'answer_start': datasets.Value('int32')}),
											            },
											        })    ,						codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/']    ,						reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/']    ,						)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=1.0)			->  Optional[int]:




											"""simple docstring"""





											lowerCamelCase__				={p['id']: p['no_answer_probability'] for p in predictions}
											lowerCamelCase__				=[{'paragraphs': [{'qas': references}]}]
											lowerCamelCase__				={p['id']: p['prediction_text'] for p in predictions}

											lowerCamelCase__				=make_qid_to_has_ans(_SCREAMING_SNAKE_CASE)  # maps qid to True/False
											lowerCamelCase__				=[k for k, v in qid_to_has_ans.items() if v]
											lowerCamelCase__				=[k for k, v in qid_to_has_ans.items() if not v]

											lowerCamelCase__				,     lowerCamelCase__				=get_raw_scores(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=apply_no_ans_threshold(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=apply_no_ans_threshold(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)

											if has_ans_qids:
																lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						qid_list=_SCREAMING_SNAKE_CASE)
																merge_eval(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						'HasAns')
											if no_ans_qids:
																lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						qid_list=_SCREAMING_SNAKE_CASE)
																merge_eval(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						'NoAns')
											find_all_best_thresh(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											return dict(_SCREAMING_SNAKE_CASE)