


"""simple docstring"""
import datasets

from .evaluate import evaluate


UpperCAmelCase				=						"""\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

UpperCAmelCase				=						"""
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
"""

UpperCAmelCase				=						"""
Computes SQuAD scores (F1 and EM).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': the text of the answer
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the SQuAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_metric = datasets.load_metric(\"squad\")
    >>> results = squad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0}
"""




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





   def 		UpperCamelCase_  (							self)  ->  Tuple:
      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 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  Tuple:
      _lowerCamelCase	:					Dict   =		{prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
      _lowerCamelCase	:					Optional[Any]   =		[
          {
              """paragraphs""": [
                  {
                      """qas""": [
                          {
                              """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
                              """id""": ref["""id"""],
                          }
                          for ref in references
                      ]
                  }
              ]
          }
      ]
      _lowerCamelCase	:					str   =		evaluate(dataset=SCREAMING_SNAKE_CASE      ,   predictions=SCREAMING_SNAKE_CASE)
      return score



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__						=				logging.get_logger(__name__)

lowerCamelCase__						=				{
    "google/pix2struct-textcaps-base": (
        "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"
    ),
}







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			Union[str, Any]						=		"pix2struct_text_model"
						UpperCamelCase_				:			str						=		["past_key_values"]
						UpperCamelCase_				:			str						=		{
						    "hidden_size": "hidden_size",
						    "num_attention_heads": "num_heads",
						    "num_hidden_layers": "num_layers",
						}

						def __init__(      self							,				a=5_02_44							,				a=7_68							,				a=64							,				a=20_48							,				a=12							,				a=12							,				a=32							,				a=1_28							,				a=0.1							,				a=1e-6							,				a=1.0							,				a="gelu_new"							,				a=0							,				a=False							,				a=0							,				a=1							,				a=False							,				a=True							,				**a							,				)       ->   Optional[int]:


								'''simple docstring'''

								_UpperCamelCase         =						vocab_size
								_UpperCamelCase         =						hidden_size
								_UpperCamelCase         =						d_kv
								_UpperCamelCase         =						d_ff
								_UpperCamelCase         =						num_layers
								_UpperCamelCase         =						num_heads
								_UpperCamelCase         =						relative_attention_num_buckets
								_UpperCamelCase         =						relative_attention_max_distance
								_UpperCamelCase         =						dropout_rate
								_UpperCamelCase         =						layer_norm_epsilon
								_UpperCamelCase         =						initializer_factor
								_UpperCamelCase         =						use_cache

								_UpperCamelCase         =						eos_token_id
								_UpperCamelCase         =						decoder_start_token_id

								# for backwards compatibility
								_UpperCamelCase         =						dense_act_fn

								super().__init__(
								    pad_token_id=a							,				eos_token_id=a							,				decoder_start_token_id=a							,				tie_word_embeddings=a							,				is_decoder=a							,				**a							,				)







						@classmethod
						def 			A_					(      cls							,				a							,				**a					)       ->   "PretrainedConfig":


								'''simple docstring'''

								cls._set_token_in_kwargs(a					)

								_UpperCamelCase     ,						_UpperCamelCase         =						cls.get_config_dict(a							,				**a					)

								# get the text config dict if we are loading from Pix2StructConfig
								if config_dict.get("""model_type"""					) == "pix2struct":
										_UpperCamelCase         =						config_dict["""text_config"""]

								if "model_type" in config_dict and hasattr(cls							,				"""model_type"""					) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
										    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'					)

								return cls.from_dict(a							,				**a					)







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			int						=		"pix2struct_vision_model"

						def __init__(      self							,				a=7_68							,				a=7_68							,				a=20_48							,				a=64							,				a=12							,				a=12							,				a="gelu_new"							,				a=1e-6							,				a=0.0							,				a=0.0							,				a=1e-10							,				a=1.0							,				a=40_96							,				a=32							,				a=1_28							,				**a							,				)       ->   Tuple:


								'''simple docstring'''

								super().__init__(**a					)

								_UpperCamelCase         =						hidden_size
								_UpperCamelCase         =						patch_embed_hidden_size
								_UpperCamelCase         =						d_ff
								_UpperCamelCase         =						dropout_rate
								_UpperCamelCase         =						num_hidden_layers
								_UpperCamelCase         =						num_attention_heads
								_UpperCamelCase         =						initializer_range
								_UpperCamelCase         =						initializer_factor
								_UpperCamelCase         =						attention_dropout
								_UpperCamelCase         =						layer_norm_eps
								_UpperCamelCase         =						dense_act_fn
								_UpperCamelCase         =						seq_len
								_UpperCamelCase         =						relative_attention_num_buckets
								_UpperCamelCase         =						relative_attention_max_distance
								_UpperCamelCase         =						d_kv







						@classmethod
						def 			A_					(      cls							,				a							,				**a					)       ->   "PretrainedConfig":


								'''simple docstring'''

								cls._set_token_in_kwargs(a					)

								_UpperCamelCase     ,						_UpperCamelCase         =						cls.get_config_dict(a							,				**a					)

								# get the vision config dict if we are loading from Pix2StructConfig
								if config_dict.get("""model_type"""					) == "pix2struct":
										_UpperCamelCase         =						config_dict["""vision_config"""]

								if "model_type" in config_dict and hasattr(cls							,				"""model_type"""					) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
										    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'					)

								return cls.from_dict(a							,				**a					)







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			Dict						=		"pix2struct"
						UpperCamelCase_				:			int						=		True

						def __init__(      self							,				a=None							,				a=None							,				a=1.0							,				a=0.02							,				a=False							,				a=False							,				a=True							,				**a							,				)       ->   Optional[Any]:


								'''simple docstring'''

								super().__init__(tie_word_embeddings=a							,				is_encoder_decoder=a							,				**a					)

								if text_config is None:
										_UpperCamelCase         =						{}
										logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values."""					)

								if vision_config is None:
										_UpperCamelCase         =						{}
										logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values."""					)

								_UpperCamelCase         =						PixaStructTextConfig(**a					)
								_UpperCamelCase         =						PixaStructVisionConfig(**a					)

								_UpperCamelCase         =						self.text_config.decoder_start_token_id
								_UpperCamelCase         =						self.text_config.pad_token_id
								_UpperCamelCase         =						self.text_config.eos_token_id

								_UpperCamelCase         =						initializer_factor
								_UpperCamelCase         =						initializer_range

								_UpperCamelCase         =						self.initializer_range
								_UpperCamelCase         =						self.initializer_range

								_UpperCamelCase         =						is_vqa

						@classmethod
						def 			A_					(      cls							,				a							,				a							,				**a					)       ->   str:


								'''simple docstring'''

								return cls(text_config=text_config.to_dict()							,				vision_config=vision_config.to_dict()							,				**a					)







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


								'''simple docstring'''

								_UpperCamelCase         =						copy.deepcopy(self.__dict__					)
								_UpperCamelCase         =						self.text_config.to_dict()
								_UpperCamelCase         =						self.vision_config.to_dict()
								_UpperCamelCase         =						self.__class__.model_type
								return output



