





import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
				import torch

				from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer







@require_torch
class 	_UpperCamelCase	(							unittest.TestCase	):







					'''simple docstring'''

					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""		)
						model.to(__lowercase		)

						# encoder-decoder outputs
						UpperCAmelCase_		    =  torch.tensor([[17, 9_62_08, 10_34_71, 2]]		).to(__lowercase		)
						UpperCAmelCase_		    =  torch.tensor(
						    [[2, 2_50, 99_53, 34, 6_94_89, 16_20, 32, 11_84_24, 6_24, 2_10, 1_05, 29_13, 10_32, 3_51]]		).to(__lowercase		)
						UpperCAmelCase_		    =  model(
						    input_ids=__lowercase			,       attention_mask=__lowercase			,       encoder_outputs=__lowercase			,       decoder_input_ids=__lowercase		)
						UpperCAmelCase_		    =  output[0]
						UpperCAmelCase_		    =  torch.Size((1, 14, 25_00_12)		)
						self.assertEqual(output_predited_logis.shape			,       __lowercase		)
						UpperCAmelCase_		    =  torch.tensor(
						    [[[-6.3986, -8.2391, 12.5189], [-6.3289, -8.0864, 12.6211], [-6.2418, -8.0445, 12.7968]]]		).to(__lowercase		)
						self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]			,       __lowercase			,       atol=1e-4		)		)

						# encoder outputs
						UpperCAmelCase_		    =  model.prophetnet.encoder(__lowercase		)[0]
						UpperCAmelCase_		    =  torch.tensor(
						    [[[-1.4260, -0.7628, 0.8453], [-1.4719, -0.1391, 0.7807], [-1.7678, 0.0114, 0.4646]]]		).to(__lowercase		)
						UpperCAmelCase_		    =  torch.Size((1, 4, 10_24)		)
						self.assertEqual(encoder_outputs.shape			,       __lowercase		)
						self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]			,       __lowercase			,       atol=1e-4		)		)

						# decoder outputs
						UpperCAmelCase_		    =  model.prophetnet.decoder(
						    __lowercase			,       encoder_hidden_states=__lowercase			,       )
						UpperCAmelCase_		    =  decoder_outputs[1].view(1			,       model.config.ngram			,       14			,       -1		)
						UpperCAmelCase_		    =  model.lm_head(__lowercase		)
						UpperCAmelCase_		    =  predicting_streams_logits[:, 0]
						self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]			,       __lowercase			,       atol=1e-4		)		)





					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	Any		):






						'''simple docstring'''







						UpperCAmelCase_		    =  XLMProphetNetForConditionalGeneration.from_pretrained(
						    """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""		)
						model.to(__lowercase		)

						UpperCAmelCase_		    =  torch.tensor([[17, 9_62_08, 10_34_71, 2]]		).to(__lowercase		)
						UpperCAmelCase_		    =  torch.tensor(
						    [[2, 2_50, 99_53, 34, 6_94_89, 16_20, 32, 11_84_24, 6_24, 2_10, 1_05, 29_13, 10_32, 3_51]]		).to(__lowercase		)
						UpperCAmelCase_		    =  model(
						    input_ids=__lowercase			,       attention_mask=__lowercase			,       encoder_outputs=__lowercase			,       decoder_input_ids=__lowercase		)
						UpperCAmelCase_		    =  output[0]
						UpperCAmelCase_		    =  torch.Size((1, 14, 25_00_12)		)
						self.assertEqual(output_predited_logis.shape			,       __lowercase		)
						# compare the actual values for a slice.
						UpperCAmelCase_		    =  torch.tensor(
						    [[[-9.2253, -9.7173, -6.3529], [-7.6701, -9.0145, -1.9382], [-8.0195, -7.0004, -0.1523]]]		).to(__lowercase		)

						self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]			,       __lowercase			,       atol=1e-4		)		)





					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  XLMProphetNetForConditionalGeneration.from_pretrained(
						    """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""		)
						model.to(__lowercase		)
						UpperCAmelCase_		    =  5_12

						UpperCAmelCase_		    =  XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""		)

						UpperCAmelCase_		    =  (
						    """Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"""
						    """ January 14, 2020, according to the official portal of the organization. From that day, users of this"""
						    """ system will not be able to receive security updates, which could make their computers vulnerable to"""
						    """ cyber attacks."""
						)
						UpperCAmelCase_		    =  (
						    """орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"""
						    """ после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"""
						    """ этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"""
						    """ к кибератакам."""
						)
						UpperCAmelCase_		    =  (
						    """根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"""
						)

						UpperCAmelCase_		    =  tokenizer(
						    [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]			,       padding=__lowercase			,       max_length=2_55			,       return_tensors="""pt"""		).input_ids
						UpperCAmelCase_		    =  input_ids.to(__lowercase		)

						UpperCAmelCase_		    =  model.generate(
						    __lowercase			,       num_beams=10			,       length_penalty=1.0			,       no_repeat_ngram_size=3			,       early_stopping=__lowercase		)
						UpperCAmelCase_		    =  [tokenizer.decode(__lowercase			,       skip_special_tokens=__lowercase		) for g in summary_ids]
						UpperCAmelCase_		    =  """Microsoft to end Windows 7 free support after January 14, 2020"""
						UpperCAmelCase_		    =  """Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"""
						UpperCAmelCase_		    =  """微软打算终止对Windows 7操作系统的免费支持"""
						self.assertListEqual(
						    [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]			,       __lowercase			,       )

						UpperCAmelCase_		    =  model.generate(
						    __lowercase			,       num_beams=1			,       length_penalty=1.0			,       no_repeat_ngram_size=3			,       early_stopping=__lowercase		)
						UpperCAmelCase_		    =  [
						    tokenizer.convert_ids_to_tokens(__lowercase			,       skip_special_tokens=__lowercase		) for g in summary_ids_beama
						]
						UpperCAmelCase_		    =  """▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7""".split(""" """		)
						UpperCAmelCase_		    =  """▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года""".split(
						    """ """		)
						UpperCAmelCase_		    =  """微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持""".split(""" """		)
						self.assertListEqual(
						    [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]			,       __lowercase			,       )









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




def  A_(      A ):

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

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

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

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

	return white_space_fix(remove_articles(remove_punc(lower(A ) ) ) )




def  A_(      A					,   A ):
	UpperCAmelCase_		    =  normalize_answer(A ).split()
	UpperCAmelCase_		    =  normalize_answer(A ).split()
	UpperCAmelCase_		    =  Counter(A ) & Counter(A )
	UpperCAmelCase_		    =  sum(common.values() )
	if num_same == 0:
		return 0
	UpperCAmelCase_		    =  1.0 * num_same / len(A )
	UpperCAmelCase_		    =  1.0 * num_same / len(A )
	UpperCAmelCase_		    =  (2 * precision * recall) / (precision + recall)
	return fa




def  A_(      A					,   A ):
	return normalize_answer(A ) == normalize_answer(A )




def  A_(      A					,   A					,   A ):
	UpperCAmelCase_		    =  []
	for ground_truth in ground_truths:
		UpperCAmelCase_		    =  metric_fn(A					,   A )
		scores_for_ground_truths.append(A )
	return max(A )




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

			UpperCAmelCase_		    =  [x["""text"""] for x in qa["""answers"""]]
			UpperCAmelCase_		    =  predictions[qa["""id"""]]

			UpperCAmelCase_		    =  metric_max_over_ground_truths(A					,   A					,   A )
			if int(_exact_match ) == 1:
				correct_ids.append(qa["""id"""] )
			exact_match += _exact_match

			fa += metric_max_over_ground_truths(A					,   A					,   A )

	UpperCAmelCase_		    =  exact_match / total
	UpperCAmelCase_		    =  fa / total

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


if __name__ == "__main__":
				UpperCamelCase__ :			Any       	=			"""1.0"""
				UpperCamelCase__ :			Optional[Any]       	=			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__ :			Any       	=			parser.parse_args()

				with open(args.data_file) as data_file:
								UpperCamelCase__ :			int       	=			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__ :			str       	=			dataset_json["""data"""]

				with open(args.pred_file) as pred_file:
								UpperCamelCase__ :			List[Any]       	=			json.load(pred_file)

				UpperCamelCase__	,      UpperCamelCase__ :			Optional[int]       	=			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)


