




import argparse
import json
import re
import string
import sys
from collections import Counter





def 		A_			(		lowercase_	)							->int:







 """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_	):
  SCREAMING_SNAKE_CASE							  =						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_	)							->int:







 """simple docstring"""

 SCREAMING_SNAKE_CASE							  =						normalize_answer(lowercase_	).split()
 SCREAMING_SNAKE_CASE							  =						normalize_answer(lowercase_	).split()
 SCREAMING_SNAKE_CASE							  =						Counter(lowercase_	) & Counter(lowercase_	)
 SCREAMING_SNAKE_CASE							  =						sum(common.values()	)
 if num_same == 0:
  return 0
 SCREAMING_SNAKE_CASE							  =						1.0 * num_same / len(lowercase_	)
 SCREAMING_SNAKE_CASE							  =						1.0 * num_same / len(lowercase_	)
 SCREAMING_SNAKE_CASE							  =						(2 * precision * recall) / (precision + recall)
 return fa





def 		A_			(		lowercase_					,       lowercase_	)							->str:







 """simple docstring"""

 return normalize_answer(lowercase_	) == normalize_answer(lowercase_	)





def 		A_			(		lowercase_					,       lowercase_					,       lowercase_	)							->Optional[Any]:







 """simple docstring"""

 SCREAMING_SNAKE_CASE							  =						[]
 for ground_truth in ground_truths:
  SCREAMING_SNAKE_CASE							  =						metric_fn(lowercase_					,       lowercase_	)
  scores_for_ground_truths.append(lowercase_	)
 return max(lowercase_	)





def 		A_			(		lowercase_					,       lowercase_	)							->Optional[int]:







 """simple docstring"""

 SCREAMING_SNAKE_CASE							  =						SCREAMING_SNAKE_CASE							  =						SCREAMING_SNAKE_CASE							  =						0
 SCREAMING_SNAKE_CASE							  =						[]
 for passage in dataset:
  for qa in passage["qas"]:
   total += 1
   if qa["id"] not in predictions:
    SCREAMING_SNAKE_CASE							  =						f'''Unanswered question {qa['id']} will receive score 0.'''
    print(lowercase_					,       file=sys.stderr	)
    continue

   SCREAMING_SNAKE_CASE							  =						[x['text'] for x in qa['answers']]
   SCREAMING_SNAKE_CASE							  =						predictions[qa['id']]

   SCREAMING_SNAKE_CASE							  =						metric_max_over_ground_truths(lowercase_					,       lowercase_					,       lowercase_	)
   if int(_exact_match	) == 1:
    correct_ids.append(qa['id']	)
   exact_match += _exact_match

   fa += metric_max_over_ground_truths(lowercase_					,       lowercase_					,       lowercase_	)

 SCREAMING_SNAKE_CASE							  =						exact_match / total
 SCREAMING_SNAKE_CASE							  =						fa / total

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


if __name__ == "__main__":
      __UpperCAmelCase      				=							"1.0"
      __UpperCAmelCase      				=							argparse.ArgumentParser("Official evaluation script for ReCoRD v1.0.")
      parser.add_argument("data_file", help="The dataset file in JSON format.")
      parser.add_argument("pred_file", help="The model prediction file in JSON format.")
      parser.add_argument("--output_correct_ids", action="store_true", help="Output the correctly answered query IDs.")
      __UpperCAmelCase      				=							parser.parse_args()

      with open(args.data_file) as data_file:
            __UpperCAmelCase      				=							json.load(data_file)
            if dataset_json["version"] != expected_version:
                  print(
                      f'Evaluation expects v-{expected_version}, but got dataset with v-{dataset_json["version"]}',
                      file=sys.stderr,
                  )
            __UpperCAmelCase      				=							dataset_json["data"]

      with open(args.pred_file) as pred_file:
            __UpperCAmelCase      				=							json.load(pred_file)

      __UpperCAmelCase				,	__UpperCAmelCase      				=							evaluate(dataset, predictions)

      if args.output_correct_ids:
            print(f'Output {len(correct_ids)} correctly answered question IDs.')
            with open("correct_ids.json", "w") as f:
                  json.dump(correct_ids, f)












import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm





def 		A_			(		lowercase_					,       lowercase_ = False	)							->Union[str, Any]:







 """simple docstring"""

 if device_specific:
  seed += AcceleratorState().process_index
 random.seed(lowercase_	)
 np.random.seed(lowercase_	)
 torch.manual_seed(lowercase_	)
 if is_xpu_available():
  torch.xpu.manual_seed_all(lowercase_	)
 elif is_npu_available():
  torch.npu.manual_seed_all(lowercase_	)
 else:
  torch.cuda.manual_seed_all(lowercase_	)
 # ^^ safe to call this function even if cuda is not available
 if is_tpu_available():
  xm.set_rng_state(lowercase_	)





def 		A_			(		lowercase_ = None					,       lowercase_ = None	)							->Optional[Any]:







 """simple docstring"""

 if rng_type == RNGType.TORCH:
  SCREAMING_SNAKE_CASE							  =						torch.get_rng_state()
 elif rng_type == RNGType.CUDA:
  SCREAMING_SNAKE_CASE							  =						torch.cuda.get_rng_state()
 elif rng_type == RNGType.XLA:
  assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
  SCREAMING_SNAKE_CASE							  =						torch.tensor(xm.get_rng_state()	)
 elif rng_type == RNGType.NPU:
  assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
  SCREAMING_SNAKE_CASE							  =						torch.npu.get_rng_state()
 elif rng_type == RNGType.XPU:
  assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
  SCREAMING_SNAKE_CASE							  =						torch.xpu.get_rng_state()
 elif rng_type == RNGType.GENERATOR:
  assert generator is not None, "Need a generator to synchronize its seed."
  SCREAMING_SNAKE_CASE							  =						generator.get_state()

 # Broadcast the rng state from device 0 to other devices
 SCREAMING_SNAKE_CASE							  =						AcceleratorState()
 if state.distributed_type == DistributedType.TPU:
  SCREAMING_SNAKE_CASE							  =						rng_state.to(xm.xla_device()	)
  xm.collective_broadcast([rng_state]	)
  xm.mark_step()
  SCREAMING_SNAKE_CASE							  =						rng_state.cpu()
 elif (
     state.distributed_type in CUDA_DISTRIBUTED_TYPES
     or state.distributed_type == DistributedType.MULTI_NPU
     or state.distributed_type == DistributedType.MULTI_XPU
 ):
  SCREAMING_SNAKE_CASE							  =						rng_state.to(state.device	)
  torch.distributed.broadcast(lowercase_					,       0	)
  SCREAMING_SNAKE_CASE							  =						rng_state.cpu()
 elif state.distributed_type == DistributedType.MULTI_CPU:
  torch.distributed.broadcast(lowercase_					,       0	)

 # Set the broadcast rng state
 if rng_type == RNGType.TORCH:
  torch.set_rng_state(lowercase_	)
 elif rng_type == RNGType.CUDA:
  torch.cuda.set_rng_state(lowercase_	)
 elif rng_type == RNGType.NPU:
  torch.npu.set_rng_state(lowercase_	)
 elif rng_type == RNGType.XPU:
  torch.xpu.set_rng_state(lowercase_	)
 elif rng_type == RNGType.XLA:
  xm.set_rng_state(rng_state.item()	)
 elif rng_type == RNGType.GENERATOR:
  generator.set_state(lowercase_	)





def 		A_			(		lowercase_					,       lowercase_ = None	)							->str:







 """simple docstring"""

 for rng_type in rng_types:
  synchronize_rng_state(RNGType(lowercase_	)					,       generator=lowercase_	)




