



from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
	import torch

A__       =			logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
	from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):


	def 						_UpperCAmelCase							( cls     ):





						"""simple docstring"""

						return cls


def 						_UpperCAmelCase							( snake_case      ,		snake_case = None      ,		snake_case = None      ,		snake_case = None      ,		snake_case = None      ,		):





					"""simple docstring"""

					_lowerCAmelCase         =       device
					_lowerCAmelCase         =       shape[0]

					_lowerCAmelCase         =       layout or torch.strided
					_lowerCAmelCase         =       device or torch.device("""cpu"""     )

					if generator is not None:
										_lowerCAmelCase         =       generator.device.type if not isinstance(snake_case      ,		snake_case     ) else generator[0].device.type
										if gen_device_type != device.type and gen_device_type == "cpu":
															_lowerCAmelCase         =       """cpu"""
															if device != "mps":
																				logger.info(
																				    F'The passed generator was created on \'cpu\' even though a tensor on {device} was expected.'
																				    F' Tensors will be created on \'cpu\' and then moved to {device}. Note that one can probably'
																				    F' slighly speed up this function by passing a generator that was created on the {device} device.'     )
										elif gen_device_type != device.type and gen_device_type == "cuda":
															raise ValueError(F'Cannot generate a {device} tensor from a generator of type {gen_device_type}.'     )

					if isinstance(snake_case      ,		snake_case     ):
										_lowerCAmelCase         =       (1,) + shape[1:]
										_lowerCAmelCase         =       [
										    torch.randn(snake_case      ,		generator=generator[i]      ,		device=snake_case      ,		dtype=snake_case      ,		layout=snake_case     )
										    for i in range(snake_case     )
										]
										_lowerCAmelCase         =       torch.cat(snake_case      ,		dim=0     ).to(snake_case     )
					else:
										_lowerCAmelCase         =       torch.randn(snake_case      ,		generator=snake_case      ,		device=snake_case      ,		dtype=snake_case      ,		layout=snake_case     ).to(snake_case     )

					return latents


def 						_UpperCAmelCase							( snake_case     ):





					"""simple docstring"""

					if is_torch_version("""<"""      ,		"""2.0.0"""     ) or not hasattr(snake_case      ,		"""_dynamo"""     ):
										return False
					return isinstance(snake_case      ,		torch._dynamo.eval_frame.OptimizedModule     )







"""simple docstring"""







import argparse
import json
import re
import string
import sys
from collections import Counter
def _A		(		lowercase						):







    """simple docstring"""

    def remove_articles(lowercase						):
        return re.sub(R'''\b(a|an|the)\b'''			,       ''' '''			,       lowercase						)

    def white_space_fix(lowercase						):
        return " ".join(text.split()						)

    def remove_punc(lowercase						):
        a											=set(string.punctuation						)
        return "".join(ch for ch in text if ch not in exclude						)

    def lower(lowercase						):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(lowercase						)						)						)						)
def _A		(		lowercase			,       lowercase						):







    """simple docstring"""
    a											=normalize_answer(lowercase						).split()
    a											=normalize_answer(lowercase						).split()
    a											=Counter(lowercase						) & Counter(lowercase						)
    a											=sum(common.values()						)
    if num_same == 0:
        return 0
    a											=1.0 * num_same / len(lowercase						)
    a											=1.0 * num_same / len(lowercase						)
    a											=(2 * precision * recall) / (precision + recall)
    return fa
def _A		(		lowercase			,       lowercase						):







    """simple docstring"""
    return normalize_answer(lowercase						) == normalize_answer(lowercase						)
def _A		(		lowercase			,       lowercase			,       lowercase						):







    """simple docstring"""
    a											=[]
    for ground_truth in ground_truths:
        a											=metric_fn(lowercase			,       lowercase						)
        scores_for_ground_truths.append(lowercase						)
    return max(lowercase						)
def _A		(		lowercase			,       lowercase						):







    """simple docstring"""
    a											=a											=a											=0
    for article in dataset:
        for paragraph in article["paragraphs"]:
            for qa in paragraph["qas"]:
                total += 1
                if qa["id"] not in predictions:
                    a											='''Unanswered question ''' + qa['''id'''] + ''' will receive score 0.'''
                    print(lowercase			,       file=sys.stderr						)
                    continue
                a											=[x['''text'''] for x in qa['''answers''']]
                a											=predictions[qa['''id''']]
                exact_match += metric_max_over_ground_truths(lowercase			,       lowercase			,       lowercase						)
                fa += metric_max_over_ground_truths(lowercase			,       lowercase			,       lowercase						)

    a											=100.0 * exact_match / total
    a											=100.0 * fa / total

    return {"exact_match": exact_match, "f1": fa}


if __name__ == "__main__":
       lowerCamelCase_  :  List[Any]     		=    """1.1"""
       lowerCamelCase_  :  Optional[Any]     		=    argparse.ArgumentParser(description="""Evaluation for SQuAD """ + expected_version)
       parser.add_argument("""dataset_file""", help="""Dataset file""")
       parser.add_argument("""prediction_file""", help="""Prediction File""")
       lowerCamelCase_  :  Optional[Any]     		=    parser.parse_args()
       with open(args.dataset_file) as dataset_file:
              lowerCamelCase_  :  List[str]     		=    json.load(dataset_file)
              if dataset_json["version"] != expected_version:
                     print(
                         """Evaluation expects v-""" + expected_version + """, but got dataset with v-""" + dataset_json["""version"""],
                         file=sys.stderr,
                     )
              lowerCamelCase_  :  Dict     		=    dataset_json["""data"""]
       with open(args.prediction_file) as prediction_file:
              lowerCamelCase_  :  Optional[Any]     		=    json.load(prediction_file)
       print(json.dumps(evaluate(dataset, predictions)))