

import copy
import os
from typing import Union

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


_SCREAMING_SNAKE_CASE					:  Tuple             =      logging.get_logger(__name__)

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






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "pix2struct_text_model"
  a									= ["past_key_values"]
  a									= {
      "hidden_size": "hidden_size",
      "num_attention_heads": "num_heads",
      "num_hidden_layers": "num_layers",
  }






  def __init__(							self						:		Tuple     ,       __lowerCamelCase						:		Any=5_0244     ,       __lowerCamelCase						:		List[Any]=768     ,       __lowerCamelCase						:		Optional[int]=64     ,       __lowerCamelCase						:		List[str]=2048     ,       __lowerCamelCase						:		List[str]=12     ,       __lowerCamelCase						:		Optional[Any]=12     ,       __lowerCamelCase						:		Tuple=32     ,       __lowerCamelCase						:		Optional[Any]=128     ,       __lowerCamelCase						:		Any=0.1     ,       __lowerCamelCase						:		Dict=1e-6     ,       __lowerCamelCase						:		Tuple=1.0     ,       __lowerCamelCase						:		Union[str, Any]="gelu_new"     ,       __lowerCamelCase						:		Dict=0     ,       __lowerCamelCase						:		Optional[int]=False     ,       __lowerCamelCase						:		Any=0     ,       __lowerCamelCase						:		List[Any]=1     ,       __lowerCamelCase						:		int=False     ,       __lowerCamelCase						:		Optional[int]=True     ,       **__lowerCamelCase						:		Dict     ,       )		->							str:
       SCREAMING_SNAKE_CASE__   =   vocab_size
       SCREAMING_SNAKE_CASE__   =   hidden_size
       SCREAMING_SNAKE_CASE__   =   d_kv
       SCREAMING_SNAKE_CASE__   =   d_ff
       SCREAMING_SNAKE_CASE__   =   num_layers
       SCREAMING_SNAKE_CASE__   =   num_heads
       SCREAMING_SNAKE_CASE__   =   relative_attention_num_buckets
       SCREAMING_SNAKE_CASE__   =   relative_attention_max_distance
       SCREAMING_SNAKE_CASE__   =   dropout_rate
       SCREAMING_SNAKE_CASE__   =   layer_norm_epsilon
       SCREAMING_SNAKE_CASE__   =   initializer_factor
       SCREAMING_SNAKE_CASE__   =   use_cache

       SCREAMING_SNAKE_CASE__   =   eos_token_id
       SCREAMING_SNAKE_CASE__   =   decoder_start_token_id

       # for backwards compatibility
       SCREAMING_SNAKE_CASE__   =   dense_act_fn

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







  @classmethod
  def 				lowercase_		(							cls						:		Optional[int]     ,       __lowerCamelCase						:		Union[str, os.PathLike]     ,       **__lowerCamelCase						:		Optional[Any] )		->							"PretrainedConfig":
       cls._set_token_in_kwargs(__lowerCamelCase )

       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   cls.get_config_dict(__lowerCamelCase     ,       **__lowerCamelCase )

       # get the text config dict if we are loading from Pix2StructConfig
       if config_dict.get('''model_type''' ) == "pix2struct":
            SCREAMING_SNAKE_CASE__   =   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(__lowerCamelCase     ,       **__lowerCamelCase )






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "pix2struct_vision_model"






  def __init__(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		List[str]=768     ,       __lowerCamelCase						:		str=768     ,       __lowerCamelCase						:		Tuple=2048     ,       __lowerCamelCase						:		str=64     ,       __lowerCamelCase						:		Tuple=12     ,       __lowerCamelCase						:		Union[str, Any]=12     ,       __lowerCamelCase						:		Dict="gelu_new"     ,       __lowerCamelCase						:		Optional[int]=1e-6     ,       __lowerCamelCase						:		Optional[int]=0.0     ,       __lowerCamelCase						:		Optional[int]=0.0     ,       __lowerCamelCase						:		List[Any]=1e-10     ,       __lowerCamelCase						:		List[Any]=1.0     ,       __lowerCamelCase						:		Dict=4096     ,       __lowerCamelCase						:		Union[str, Any]=32     ,       __lowerCamelCase						:		List[Any]=128     ,       **__lowerCamelCase						:		List[Any]     ,       )		->							str:
       super().__init__(**__lowerCamelCase )

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







  @classmethod
  def 				lowercase_		(							cls						:		List[Any]     ,       __lowerCamelCase						:		Union[str, os.PathLike]     ,       **__lowerCamelCase						:		Tuple )		->							"PretrainedConfig":
       cls._set_token_in_kwargs(__lowerCamelCase )

       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   cls.get_config_dict(__lowerCamelCase     ,       **__lowerCamelCase )

       # get the vision config dict if we are loading from Pix2StructConfig
       if config_dict.get('''model_type''' ) == "pix2struct":
            SCREAMING_SNAKE_CASE__   =   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(__lowerCamelCase     ,       **__lowerCamelCase )






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "pix2struct"
  a									= True






  def __init__(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		Dict=None     ,       __lowerCamelCase						:		Tuple=None     ,       __lowerCamelCase						:		List[Any]=1.0     ,       __lowerCamelCase						:		int=0.02     ,       __lowerCamelCase						:		Dict=False     ,       __lowerCamelCase						:		List[str]=False     ,       __lowerCamelCase						:		List[str]=True     ,       **__lowerCamelCase						:		Tuple     ,       )		->							List[Any]:
       super().__init__(tie_word_embeddings=__lowerCamelCase     ,       is_encoder_decoder=__lowerCamelCase     ,       **__lowerCamelCase )

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

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

       SCREAMING_SNAKE_CASE__   =   PixaStructTextConfig(**__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   PixaStructVisionConfig(**__lowerCamelCase )

       SCREAMING_SNAKE_CASE__   =   self.text_config.decoder_start_token_id
       SCREAMING_SNAKE_CASE__   =   self.text_config.pad_token_id
       SCREAMING_SNAKE_CASE__   =   self.text_config.eos_token_id

       SCREAMING_SNAKE_CASE__   =   initializer_factor
       SCREAMING_SNAKE_CASE__   =   initializer_range

       SCREAMING_SNAKE_CASE__   =   self.initializer_range
       SCREAMING_SNAKE_CASE__   =   self.initializer_range

       SCREAMING_SNAKE_CASE__   =   is_vqa






  @classmethod
  def 				lowercase_		(							cls						:		Optional[int]     ,       __lowerCamelCase						:		PixaStructTextConfig     ,       __lowerCamelCase						:		PixaStructVisionConfig     ,       **__lowerCamelCase						:		Optional[int] )		->							List[Any]:
       return cls(text_config=text_config.to_dict()     ,       vision_config=vision_config.to_dict()     ,       **__lowerCamelCase )







  def 				lowercase_		(							self						:		List[str] )		->							List[str]:
       SCREAMING_SNAKE_CASE__   =   copy.deepcopy(self.__dict__ )
       SCREAMING_SNAKE_CASE__   =   self.text_config.to_dict()
       SCREAMING_SNAKE_CASE__   =   self.vision_config.to_dict()
       SCREAMING_SNAKE_CASE__   =   self.__class__.model_type
       return output





import datasets

from .evaluate import evaluate


_SCREAMING_SNAKE_CASE					:  Union[str, Any]             =      '''\
@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}
}
'''

_SCREAMING_SNAKE_CASE					:  Dict             =      '''
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.
'''

_SCREAMING_SNAKE_CASE					:  str             =      '''
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 	UpperCAmelCase__		(	datasets.Metric	):






  """simple docstring"""


  def 				lowercase_		(							self						:		List[Any] )		->							Optional[int]:
       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 				lowercase_		(							self						:		Optional[Any]     ,       __lowerCamelCase						:		Dict     ,       __lowerCamelCase						:		List[Any] )		->							Optional[int]:
       SCREAMING_SNAKE_CASE__   =   {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
       SCREAMING_SNAKE_CASE__   =   [
           {
               '''paragraphs''': [
                   {
                       '''qas''': [
                           {
                               '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
                               '''id''': ref['''id'''],
                           }
                           for ref in references
                       ]
                   }
               ]
           }
       ]
       SCREAMING_SNAKE_CASE__   =   evaluate(dataset=__lowerCamelCase     ,       predictions=__lowerCamelCase )
       return score


