

from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import (
         TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
         TFXLMForMultipleChoice,
         TFXLMForQuestionAnsweringSimple,
         TFXLMForSequenceClassification,
         TFXLMForTokenClassification,
         TFXLMModel,
         TFXLMWithLMHeadModel,
         XLMConfig,
     )


class 					A		:







    """simple docstring"""





    def __init__( self					:			Any,lowercase_					:			str,)->       Tuple:





        '''simple docstring'''







        A__        =  parent
        A__        =  1_3
        A__        =  7
        A__        =  True
        A__        =  True
        A__        =  True
        A__        =  True
        A__        =  True
        A__        =  False
        A__        =  False
        A__        =  False
        A__        =  2
        A__        =  9_9
        A__        =  0
        A__        =  3_2
        A__        =  2
        A__        =  4
        A__        =  0.1
        A__        =  0.1
        A__        =  5_1_2
        A__        =  1_6
        A__        =  2
        A__        =  0.02
        A__        =  3
        A__        =  4
        A__        =  'last'
        A__        =  True
        A__        =  None
        A__        =  0


    def 		snake_case__	( self					:			str						)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  ids_tensor([self.batch_size, self.seq_length],self.vocab_size						)
        A__        =  random_attention_mask([self.batch_size, self.seq_length],dtype=tf.floataa						)

        A__        =  None
        if self.use_input_lengths:
            A__        =  (
                ids_tensor([self.batch_size],vocab_size=2						) + self.seq_length - 2
            )  # small variation of seq_length

        A__        =  None
        if self.use_token_type_ids:
            A__        =  ids_tensor([self.batch_size, self.seq_length],self.n_langs						)

        A__        =  None
        A__        =  None
        A__        =  None
        if self.use_labels:
            A__        =  ids_tensor([self.batch_size],self.type_sequence_label_size						)
            A__        =  ids_tensor([self.batch_size, self.seq_length],self.num_labels						)
            A__        =  ids_tensor([self.batch_size],2,dtype=tf.floataa						)
            A__        =  ids_tensor([self.batch_size],self.num_choices						)

        A__        =  XLMConfig(
            vocab_size=self.vocab_size,n_special=self.n_special,emb_dim=self.hidden_size,n_layers=self.num_hidden_layers,n_heads=self.num_attention_heads,dropout=self.hidden_dropout_prob,attention_dropout=self.attention_probs_dropout_prob,gelu_activation=self.gelu_activation,sinusoidal_embeddings=self.sinusoidal_embeddings,asm=self.asm,causal=self.causal,n_langs=self.n_langs,max_position_embeddings=self.max_position_embeddings,initializer_range=self.initializer_range,summary_type=self.summary_type,use_proj=self.use_proj,bos_token_id=self.bos_token_id,)

        return (
            config,
            input_ids,
            token_type_ids,
            input_lengths,
            sequence_labels,
            token_labels,
            is_impossible_labels,
            choice_labels,
            input_mask,
        )


    def 		snake_case__	( self					:			Optional[Any],lowercase_					:			Any,lowercase_					:			Dict,lowercase_					:			str,lowercase_					:			str,lowercase_					:			Any,lowercase_					:			Tuple,lowercase_					:			Any,lowercase_					:			Tuple,lowercase_					:			Union[str, Any],)->       int:





        '''simple docstring'''







        A__        =  TFXLMModel(config=__UpperCAmelCase						)
        A__        =  {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
        A__        =  model(__UpperCAmelCase						)

        A__        =  [input_ids, input_mask]
        A__        =  model(__UpperCAmelCase						)
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)						)


    def 		snake_case__	( self					:			int,lowercase_					:			int,lowercase_					:			str,lowercase_					:			Optional[Any],lowercase_					:			Any,lowercase_					:			Any,lowercase_					:			List[str],lowercase_					:			Any,lowercase_					:			Union[str, Any],lowercase_					:			int,)->       Any:





        '''simple docstring'''







        A__        =  TFXLMWithLMHeadModel(__UpperCAmelCase						)

        A__        =  {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
        A__        =  model(__UpperCAmelCase						)

        A__        =  outputs

        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)						)


    def 		snake_case__	( self					:			int,lowercase_					:			int,lowercase_					:			Optional[int],lowercase_					:			List[str],lowercase_					:			Optional[int],lowercase_					:			Any,lowercase_					:			Optional[Any],lowercase_					:			Tuple,lowercase_					:			List[str],lowercase_					:			Optional[int],)->       Optional[Any]:





        '''simple docstring'''







        A__        =  TFXLMForQuestionAnsweringSimple(__UpperCAmelCase						)

        A__        =  {'input_ids': input_ids, 'lengths': input_lengths}

        A__        =  model(__UpperCAmelCase						)

        self.parent.assertEqual(result.start_logits.shape,(self.batch_size, self.seq_length)						)
        self.parent.assertEqual(result.end_logits.shape,(self.batch_size, self.seq_length)						)


    def 		snake_case__	( self					:			List[str],lowercase_					:			List[Any],lowercase_					:			str,lowercase_					:			List[Any],lowercase_					:			Any,lowercase_					:			List[str],lowercase_					:			Tuple,lowercase_					:			Union[str, Any],lowercase_					:			Union[str, Any],lowercase_					:			List[Any],)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  TFXLMForSequenceClassification(__UpperCAmelCase						)

        A__        =  {'input_ids': input_ids, 'lengths': input_lengths}

        A__        =  model(__UpperCAmelCase						)

        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)						)


    def 		snake_case__	( self					:			Optional[int],lowercase_					:			List[str],lowercase_					:			str,lowercase_					:			Any,lowercase_					:			int,lowercase_					:			str,lowercase_					:			Tuple,lowercase_					:			int,lowercase_					:			List[str],lowercase_					:			Optional[int],)->       List[Any]:





        '''simple docstring'''







        A__        =  self.num_labels
        A__        =  TFXLMForTokenClassification(config=__UpperCAmelCase						)
        A__        =  {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
        A__        =  model(__UpperCAmelCase						)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)						)


    def 		snake_case__	( self					:			Dict,lowercase_					:			Optional[int],lowercase_					:			Dict,lowercase_					:			str,lowercase_					:			int,lowercase_					:			int,lowercase_					:			Tuple,lowercase_					:			str,lowercase_					:			List[str],lowercase_					:			List[Any],)->       Dict:





        '''simple docstring'''







        A__        =  self.num_choices
        A__        =  TFXLMForMultipleChoice(config=__UpperCAmelCase						)
        A__        =  tf.tile(tf.expand_dims(__UpperCAmelCase,1						),(1, self.num_choices, 1)						)
        A__        =  tf.tile(tf.expand_dims(__UpperCAmelCase,1						),(1, self.num_choices, 1)						)
        A__        =  tf.tile(tf.expand_dims(__UpperCAmelCase,1						),(1, self.num_choices, 1)						)
        A__        =  {
            'input_ids': multiple_choice_inputs_ids,
            'attention_mask': multiple_choice_input_mask,
            'token_type_ids': multiple_choice_token_type_ids,
        }
        A__        =  model(__UpperCAmelCase						)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)						)


    def 		snake_case__	( self					:			int						)->       Tuple:





        '''simple docstring'''







        A__        =  self.prepare_config_and_inputs()
        (
            (
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		(
            A__      
        ) ,		      
        )        =  config_and_inputs
        A__        =  {
            'input_ids': input_ids,
            'token_type_ids': token_type_ids,
            'langs': token_type_ids,
            'lengths': input_lengths,
        }
        return config, inputs_dict




@require_tf
class 					A		(				__SCREAMING_SNAKE_CASE       ,				__SCREAMING_SNAKE_CASE       ,				unittest.TestCase					):







    """simple docstring"""





    lowerCamelCase						      =				(
        (
            TFXLMModel,
            TFXLMWithLMHeadModel,
            TFXLMForSequenceClassification,
            TFXLMForQuestionAnsweringSimple,
            TFXLMForTokenClassification,
            TFXLMForMultipleChoice,
        )
        if is_tf_available()
        else ()
    )
    lowerCamelCase						      =				(
        (TFXLMWithLMHeadModel,) if is_tf_available() else ()
    )  # TODO (PVP): Check other models whether language generation is also applicable
    lowerCamelCase						      =				(
        {
            'feature-extraction': TFXLMModel,
            'fill-mask': TFXLMWithLMHeadModel,
            'question-answering': TFXLMForQuestionAnsweringSimple,
            'text-classification': TFXLMForSequenceClassification,
            'text-generation': TFXLMWithLMHeadModel,
            'token-classification': TFXLMForTokenClassification,
            'zero-shot': TFXLMForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    lowerCamelCase						      =				False
    lowerCamelCase						      =				False


    def 		snake_case__	( self					:			List[Any],lowercase_					:			Optional[int],lowercase_					:			Optional[Any],lowercase_					:			int,lowercase_					:			str,lowercase_					:			Optional[Any]						)->       Dict:





        '''simple docstring'''







        if (
            pipeline_test_casse_name == "QAPipelineTests"
            and tokenizer_name is not None
            and not tokenizer_name.endswith('Fast'						)
        ):
            # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
            # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
            # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
            return True

        return False


    def 		snake_case__	( self					:			List[str]						)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  TFXLMModelTester(self						)
        A__        =  ConfigTester(self,config_class=__UpperCAmelCase,emb_dim=3_7						)


    def 		snake_case__	( self					:			Optional[Any]						)->       str:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    def 		snake_case__	( self					:			Optional[int]						)->       Optional[int]:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_model(*__UpperCAmelCase						)


    def 		snake_case__	( self					:			Any						)->       Optional[int]:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_lm_head(*__UpperCAmelCase						)


    def 		snake_case__	( self					:			int						)->       str:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_qa(*__UpperCAmelCase						)


    def 		snake_case__	( self					:			Tuple						)->       List[Any]:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_sequence_classif(*__UpperCAmelCase						)


    def 		snake_case__	( self					:			Optional[Any]						)->       List[str]:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_for_token_classification(*__UpperCAmelCase						)


    def 		snake_case__	( self					:			Any						)->       Optional[int]:





        '''simple docstring'''







        A__        =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_for_multiple_choice(*__UpperCAmelCase						)


    @slow
    def 		snake_case__	( self					:			Any						)->       Union[str, Any]:





        '''simple docstring'''







        for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A__        =  TFXLMModel.from_pretrained(__UpperCAmelCase						)
            self.assertIsNotNone(__UpperCAmelCase						)




@require_tf
class 					A		(				unittest.TestCase					):







    """simple docstring"""





    @slow
    def 		snake_case__	( self					:			Any						)->       List[str]:





        '''simple docstring'''







        A__        =  TFXLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048'						)
        A__        =  tf.convert_to_tensor([[1_4, 4_4_7]],dtype=tf.intaa						)  # the president
        A__        =  [
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
        ]  # the president the president the president the president the president the president the president the president the president the president
        # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
        A__        =  model.generate(__UpperCAmelCase,do_sample=__UpperCAmelCase						)
        self.assertListEqual(output_ids[0].numpy().tolist(),__UpperCAmelCase						)



"""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,
)


UpperCamelCase      :							List[str]          =					"\\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      :							int          =					"\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"

UpperCamelCase      :							Optional[Any]          =					"\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 __lowerCAmelCase						( datasets.Metric     ):





     def 		UpperCAmelCase   (      self ):

      '''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 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase=1.0 ):

      '''simple docstring'''




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

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

      __UpperCamelCase    ,      __UpperCamelCase							    =			get_raw_scores(__UpperCAmelCase      ,	__UpperCAmelCase )
      __UpperCamelCase							    =			apply_no_ans_threshold(__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase )
      __UpperCamelCase							    =			apply_no_ans_threshold(__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase )
      __UpperCamelCase							    =			make_eval_dict(__UpperCAmelCase      ,	__UpperCAmelCase )

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



