



import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow






class      UpperCamelCase    :



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							return None






class      UpperCamelCase    :



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							return None






class      UpperCamelCase    (						unittest.TestCase     ):
	lowerCAmelCase	:   Optional[int]				=	[
	    # (model_name, model_kwargs)
	    ("""bert-base-cased""", {}),
	    ("""gpt2""", {"""use_cache""": False}),  # We don't support exporting GPT2 past keys anymore
	]



	@require_tf
	@slow
	def 			__A							(       self		):
							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
													self._test_export(UpperCAmelCase__			,	"tf"			,	12			,	**UpperCAmelCase__		)



	@require_torch
	@slow
	def 			__A							(       self		):
							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
													self._test_export(UpperCAmelCase__			,	"pt"			,	12			,	**UpperCAmelCase__		)



	@require_torch
	@slow
	def 			__A							(       self		):
							from transformers import BertModel

							A__							=       ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"]
							with NamedTemporaryFile(mode="w+t"		) as vocab_file:
													vocab_file.write("\n".join(UpperCAmelCase__		)		)
													vocab_file.flush()
													A__							=       BertTokenizerFast(vocab_file.name		)

							with TemporaryDirectory() as bert_save_dir:
													A__							=       BertModel(BertConfig(vocab_size=len(UpperCAmelCase__		)		)		)
													model.save_pretrained(UpperCAmelCase__		)
													self._test_export(UpperCAmelCase__			,	"pt"			,	12			,	UpperCAmelCase__		)



	@require_tf
	@slow
	def 			__A							(       self		):
							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
													A__							=       self._test_export(UpperCAmelCase__			,	"tf"			,	12			,	**UpperCAmelCase__		)
													A__							=       quantize(Path(UpperCAmelCase__		)		)

													# Ensure the actual quantized model is not bigger than the original one
													if quantized_path.stat().st_size >= Path(UpperCAmelCase__		).stat().st_size:
																			self.fail("Quantized model is bigger than initial ONNX model"		)



	@require_torch
	@slow
	def 			__A							(       self		):
							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
													A__							=       self._test_export(UpperCAmelCase__			,	"pt"			,	12			,	**UpperCAmelCase__		)
													A__							=       quantize(UpperCAmelCase__		)

													# Ensure the actual quantized model is not bigger than the original one
													if quantized_path.stat().st_size >= Path(UpperCAmelCase__		).stat().st_size:
																			self.fail("Quantized model is bigger than initial ONNX model"		)



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__=None			,	**UpperCAmelCase__		):
							try:
													# Compute path
													with TemporaryDirectory() as tempdir:
																			A__							=       Path(UpperCAmelCase__		).joinpath("model.onnx"		)

													# Remove folder if exists
													if path.parent.exists():
																			path.parent.rmdir()

													# Export
													convert(UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__			,	**UpperCAmelCase__		)

													return path
							except Exception as e:
													self.fail(UpperCAmelCase__		)



	@require_torch
	@require_tokenizers
	@slow
	def 			__A							(       self		):
							from transformers import BertModel

							A__							=       BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random"		)		)
							A__							=       BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random"		)
							self._test_infer_dynamic_axis(UpperCAmelCase__			,	UpperCAmelCase__			,	"pt"		)



	@require_tf
	@require_tokenizers
	@slow
	def 			__A							(       self		):
							from transformers import TFBertModel

							A__							=       TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random"		)		)
							A__							=       BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random"		)
							self._test_infer_dynamic_axis(UpperCAmelCase__			,	UpperCAmelCase__			,	"tf"		)



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							A__							=       FeatureExtractionPipeline(UpperCAmelCase__			,	UpperCAmelCase__		)

							A__							=       ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"]
							A__						,       A__						,       A__						,       A__							=       infer_shapes(UpperCAmelCase__			,	UpperCAmelCase__		)

							# Assert all variables are present
							self.assertEqual(len(UpperCAmelCase__		)			,	len(UpperCAmelCase__		)		)
							self.assertTrue(all(var_name in shapes for var_name in variable_names		)		)
							self.assertSequenceEqual(variable_names[:3]			,	UpperCAmelCase__		)
							self.assertSequenceEqual(variable_names[3:]			,	UpperCAmelCase__		)

							# Assert inputs are {0: batch, 1: sequence}
							for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
													self.assertDictEqual(shapes[var_name]			,	{0: "batch", 1: "sequence"}		)

							# Assert outputs are {0: batch, 1: sequence} and {0: batch}
							self.assertDictEqual(shapes["output_0"]			,	{0: "batch", 1: "sequence"}		)
							self.assertDictEqual(shapes["output_1"]			,	{0: "batch"}		)



	def 			__A							(       self		):
							A__							=       ["input_ids", "attention_mask", "token_type_ids"]
							A__							=       {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]}
							A__						,       A__							=       ensure_valid_input(FuncContiguousArgs()			,	UpperCAmelCase__			,	UpperCAmelCase__		)

							# Should have exactly the same number of args (all are valid)
							self.assertEqual(len(UpperCAmelCase__		)			,	3		)

							# Should have exactly the same input names
							self.assertEqual(set(UpperCAmelCase__		)			,	set(UpperCAmelCase__		)		)

							# Parameter should be reordered according to their respective place in the function:
							# (input_ids, token_type_ids, attention_mask)
							self.assertEqual(UpperCAmelCase__			,	(tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"])		)

							# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
							A__						,       A__							=       ensure_valid_input(FuncNonContiguousArgs()			,	UpperCAmelCase__			,	UpperCAmelCase__		)

							# Should have exactly the one arg (all before the one not provided "some_other_args")
							self.assertEqual(len(UpperCAmelCase__		)			,	1		)
							self.assertEqual(len(UpperCAmelCase__		)			,	1		)

							# Should have only "input_ids"
							self.assertEqual(inputs_args[0]			,	tokens["input_ids"]		)
							self.assertEqual(ordered_input_names[0]			,	"input_ids"		)



	def 			__A							(       self		):
							A__							=       generate_identified_filename(Path("/home/something/my_fake_model.onnx"		)			,	"-test"		)
							self.assertEqual("/home/something/my_fake_model-test.onnx"			,	generated.as_posix()		)










import datasets

from .evaluate import evaluate


UpperCAmelCase_							:      List[Any]      =  "\\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"

UpperCAmelCase_							:      Any      =  "\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering 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"

UpperCAmelCase_							:      Tuple      =  "\nComputes SQuAD scores (F1 and EM).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair as given in the references (see below)\n        - 'prediction_text': the text of the 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 Dict in the SQuAD dataset format\n            {\n                'text': list of possible texts for the answer, as a list of strings\n                'answer_start': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    'exact_match': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_metric = datasets.load_metric(\"squad\")\n    >>> results = squad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 100.0, 'f1': 100.0}\n"






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



	def 			__A							(       self		):
							return datasets.MetricInfo(
							    description=_DESCRIPTION			,	citation=_CITATION			,	inputs_description=_KWARGS_DESCRIPTION			,	features=datasets.Features(
							        {
							            "predictions": {"id": datasets.Value("string"		), "prediction_text": datasets.Value("string"		)},
							            "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 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							A__							=       {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
							A__							=       [
							    {
							        "paragraphs": [
							            {
							                "qas": [
							                    {
							                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
							                        "id": ref["id"],
							                    }
							                    for ref in references
							                ]
							            }
							        ]
							    }
							]
							A__							=       evaluate(dataset=UpperCAmelCase__			,	predictions=UpperCAmelCase__		)
							return score





