





'''simple docstring'''







from collections import OrderedDict
from typing import Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging


snake_case_   :				Any		=     logging.get_logger(__name__)

snake_case_   :				Any		=     {
    'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json',
    # See all Perceiver models at https://huggingface.co/models?filter=perceiver
}


class     __a					(_A   ):
							__a    :      int  	=				"perceiver"

							def __init__(							self							:   List[str]				,   __magic_name__							:   Any=2_56				,   __magic_name__							:   Union[str, Any]=12_80				,   __magic_name__							:   Optional[int]=7_68				,   __magic_name__							:   Optional[Any]=1				,   __magic_name__							:   Tuple=26				,   __magic_name__							:   Optional[Any]=8				,   __magic_name__							:   Dict=8				,   __magic_name__							:   int=None				,   __magic_name__							:   str=None				,   __magic_name__							:   List[str]="kv"				,   __magic_name__							:   List[Any]=1				,   __magic_name__							:   List[str]=1				,   __magic_name__							:   List[Any]="gelu"				,   __magic_name__							:   List[str]=0.1				,   __magic_name__							:   List[str]=0.0_2				,   __magic_name__							:   Optional[int]=1E-12				,   __magic_name__							:   Dict=True				,   __magic_name__							:   Dict=2_62				,   __magic_name__							:   List[Any]=20_48				,   __magic_name__							:   Tuple=56				,   __magic_name__							:   Optional[int]=[3_68, 4_96]				,   __magic_name__							:   str=16				,   __magic_name__							:   Union[str, Any]=19_20				,   __magic_name__							:   Tuple=16				,   __magic_name__							:   List[Any]=[1, 16, 2_24, 2_24]				,   **__magic_name__							:   str				,   )    ->				List[Any]:







													"""simple docstring"""
													super().__init__(**UpperCamelCase__      )

													UpperCAmelCase_	:					Tuple     =     num_latents
													UpperCAmelCase_	:					Union[str, Any]     =     d_latents
													UpperCAmelCase_	:					List[Any]     =     d_model
													UpperCAmelCase_	:					List[Any]     =     num_blocks
													UpperCAmelCase_	:					Any     =     num_self_attends_per_block
													UpperCAmelCase_	:					List[Any]     =     num_self_attention_heads
													UpperCAmelCase_	:					Any     =     num_cross_attention_heads
													UpperCAmelCase_	:					Any     =     qk_channels
													UpperCAmelCase_	:					int     =     v_channels
													UpperCAmelCase_	:					str     =     cross_attention_shape_for_attention
													UpperCAmelCase_	:					int     =     self_attention_widening_factor
													UpperCAmelCase_	:					Any     =     cross_attention_widening_factor
													UpperCAmelCase_	:					Optional[Any]     =     hidden_act
													UpperCAmelCase_	:					Optional[Any]     =     attention_probs_dropout_prob
													UpperCAmelCase_	:					str     =     initializer_range
													UpperCAmelCase_	:					Tuple     =     layer_norm_eps
													UpperCAmelCase_	:					int     =     use_query_residual
													# masked language modeling attributes
													UpperCAmelCase_	:					List[Any]     =     vocab_size
													UpperCAmelCase_	:					int     =     max_position_embeddings
													# image classification attributes
													UpperCAmelCase_	:					Optional[int]     =     image_size
													# flow attributes
													UpperCAmelCase_	:					Tuple     =     train_size
													# multimodal autoencoding attributes
													UpperCAmelCase_	:					Dict     =     num_frames
													UpperCAmelCase_	:					Any     =     audio_samples_per_frame
													UpperCAmelCase_	:					Dict     =     samples_per_patch
													UpperCAmelCase_	:					Union[str, Any]     =     output_shape





class     __a					(_A   ):

							@property
							def 			UpperCAmelCase__		(							self							:   Union[str, Any]      )    ->				Mapping[str, Mapping[int, str]]:







													"""simple docstring"""






													if self.task == "multiple-choice":
																			UpperCAmelCase_	:					Optional[Any]     =     {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
													else:
																			UpperCAmelCase_	:					List[str]     =     {0: '''batch''', 1: '''sequence'''}
													return OrderedDict(
													    [
													        ('''inputs''', dynamic_axis),
													        ('''attention_mask''', dynamic_axis),
													    ]      )

							@property
							def 			UpperCAmelCase__		(							self							:   str      )    ->				float:







													"""simple docstring"""
													return 1E-4



							def 			UpperCAmelCase__		(							self							:   int				,   __magic_name__							:   Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]				,   __magic_name__							:   int = -1				,   __magic_name__							:   int = -1				,   __magic_name__							:   int = -1				,   __magic_name__							:   bool = False				,   __magic_name__							:   Optional[TensorType] = None				,   __magic_name__							:   int = 3				,   __magic_name__							:   int = 40				,   __magic_name__							:   int = 40				,   )    ->				Mapping[str, Any]:







													"""simple docstring"""






													if isinstance(UpperCamelCase__				,   UpperCamelCase__      ):
																			# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
																			UpperCAmelCase_	:					Dict     =     compute_effective_axis_dimension(
																			    UpperCamelCase__				,   fixed_dimension=OnnxConfig.default_fixed_batch				,   num_token_to_add=0      )
																			# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
																			UpperCAmelCase_	:					List[Any]     =     preprocessor.num_special_tokens_to_add(UpperCamelCase__      )
																			UpperCAmelCase_	:					Dict     =     compute_effective_axis_dimension(
																			    UpperCamelCase__				,   fixed_dimension=OnnxConfig.default_fixed_sequence				,   num_token_to_add=UpperCamelCase__      )
																			# Generate dummy inputs according to compute batch and sequence
																			UpperCAmelCase_	:					Tuple     =     [''' '''.join(['''a''']      ) * seq_length] * batch_size
																			UpperCAmelCase_	:					str     =     dict(preprocessor(UpperCamelCase__				,   return_tensors=UpperCamelCase__      )      )
																			UpperCAmelCase_	:					List[Any]     =     inputs.pop('''input_ids'''      )
																			return inputs
													elif isinstance(UpperCamelCase__				,   UpperCamelCase__      ) and preprocessor.model_input_names[0] == "pixel_values":
																			# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
																			UpperCAmelCase_	:					List[str]     =     compute_effective_axis_dimension(UpperCamelCase__				,   fixed_dimension=OnnxConfig.default_fixed_batch      )
																			UpperCAmelCase_	:					Tuple     =     self._generate_dummy_images(UpperCamelCase__				,   UpperCamelCase__				,   UpperCamelCase__				,   UpperCamelCase__      )
																			UpperCAmelCase_	:					str     =     dict(preprocessor(images=UpperCamelCase__				,   return_tensors=UpperCamelCase__      )      )
																			UpperCAmelCase_	:					Dict     =     inputs.pop('''pixel_values'''      )
																			return inputs
													else:
																			raise ValueError(
																			    '''Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.'''      )







import re
import string

import numpy as np

import datasets


__lowerCAmelCase			:     Optional[int]           =   '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowerCAmelCase			:     Optional[int]           =   '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowerCAmelCase			:     Optional[int]           =   '\n'




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


  '''simple docstring'''







  def 							_lowercase							( self			: str    )			->	Optional[int]:







    """simple docstring"""






    return datasets.MetricInfo(
        description=_DESCRIPTION			,							citation=_CITATION			,							inputs_description=_KWARGS_DESCRIPTION			,							features=datasets.Features(
            {
                """predictions""": datasets.Value("""string"""			,							id="""sequence"""    ),
                """references""": datasets.Value("""string"""			,							id="""sequence"""    ),
            }    )			,							reference_urls=[]			,							)





  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]=None			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: int=False			,							UpperCamelCase__			: Tuple=False			,							)			->	Dict:







    """simple docstring"""






    if regexes_to_ignore is not None:
      for s in regexes_to_ignore:
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in predictions]    )
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in references]    )
    else:
      __magic_name__				     =       np.asarray(UpperCamelCase__    )
      __magic_name__				     =       np.asarray(UpperCamelCase__    )

    if ignore_case:
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )

    if ignore_punctuation:
      __magic_name__				     =       string.punctuation.maketrans(""""""			,							""""""			,							string.punctuation    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    if ignore_numbers:
      __magic_name__				     =       string.digits.maketrans(""""""			,							""""""			,							string.digits    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    __magic_name__				     =       predictions == references

    return {"exact_match": np.mean(UpperCamelCase__    ) * 100}

