





'''simple docstring'''







from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
					import timm


if is_torch_available():
					from torch import Tensor


class     __a					(_A				,						_A   ):
							__a    :      Optional[int]  	=				"pixel_values"
							__a    :      List[Any]  	=				False
							__a    :      Tuple  	=				TimmBackboneConfig

							def __init__(							self							:   str				,   __magic_name__							:   List[str]				,   **__magic_name__							:   Any      )    ->				str:







													"""simple docstring"""
													requires_backends(self				,   '''timm'''      )
													super().__init__(UpperCamelCase__      )
													UpperCAmelCase_	:					Dict     =     config

													if config.backbone is None:
																			raise ValueError('''backbone is not set in the config. Please set it to a timm model name.'''      )

													if config.backbone not in timm.list_models():
																			raise ValueError(F"""backbone {config.backbone} is not supported by timm."""      )

													if hasattr(UpperCamelCase__				,   '''out_features'''      ) and config.out_features is not None:
																			raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''      )

													UpperCAmelCase_	:					Tuple     =     getattr(UpperCamelCase__				,   '''use_pretrained_backbone'''				,   UpperCamelCase__      )
													if pretrained is None:
																			raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.'''      )

													# We just take the final layer by default. This matches the default for the transformers models.
													UpperCAmelCase_	:					Optional[int]     =     config.out_indices if getattr(UpperCamelCase__				,   '''out_indices'''				,   UpperCamelCase__      ) is not None else (-1,)

													UpperCAmelCase_	:					Optional[int]     =     timm.create_model(
													    config.backbone				,   pretrained=UpperCamelCase__				,   features_only=config.features_only				,   in_chans=config.num_channels				,   out_indices=UpperCamelCase__				,   **UpperCamelCase__				,   )
													# These are used to control the output of the model when called. If output_hidden_states is True, then
													# return_layers is modified to include all layers.
													UpperCAmelCase_	:					Union[str, Any]     =     self._backbone.return_layers
													UpperCAmelCase_	:					Dict     =     {layer['''module''']: str(UpperCamelCase__      ) for i, layer in enumerate(self._backbone.feature_info.info      )}
													super()._init_backbone(UpperCamelCase__      )

							@classmethod
							def 			UpperCAmelCase__		(							cls							:   Optional[Any]				,   __magic_name__							:   Dict				,   *__magic_name__							:   Optional[Any]				,   **__magic_name__							:   List[Any]      )    ->				Optional[Any]:







													"""simple docstring"""
													requires_backends(cls				,   ['''vision''', '''timm''']      )
													from ...models.timm_backbone import TimmBackboneConfig

													UpperCAmelCase_	:					List[str]     =     kwargs.pop('''config'''				,   TimmBackboneConfig()      )

													UpperCAmelCase_	:					Dict     =     kwargs.pop('''use_timm_backbone'''				,   UpperCamelCase__      )
													if not use_timm:
																			raise ValueError('''use_timm_backbone must be True for timm backbones'''      )

													UpperCAmelCase_	:					Optional[Any]     =     kwargs.pop('''num_channels'''				,   config.num_channels      )
													UpperCAmelCase_	:					str     =     kwargs.pop('''features_only'''				,   config.features_only      )
													UpperCAmelCase_	:					Union[str, Any]     =     kwargs.pop('''use_pretrained_backbone'''				,   config.use_pretrained_backbone      )
													UpperCAmelCase_	:					Optional[int]     =     kwargs.pop('''out_indices'''				,   config.out_indices      )
													UpperCAmelCase_	:					Optional[Any]     =     TimmBackboneConfig(
													    backbone=UpperCamelCase__				,   num_channels=UpperCamelCase__				,   features_only=UpperCamelCase__				,   use_pretrained_backbone=UpperCamelCase__				,   out_indices=UpperCamelCase__				,   )
													return super()._from_config(UpperCamelCase__				,   **UpperCamelCase__      )

							def 			UpperCAmelCase__		(							self							:   Tuple				,   __magic_name__							:   Optional[Any]      )    ->				int:







													"""simple docstring"""
													pass



							def 			UpperCAmelCase__		(							self							:   Optional[Any]				,   __magic_name__							:   Tuple				,   __magic_name__							:   Tuple=None				,   __magic_name__							:   List[str]=None				,   __magic_name__							:   int=None				,   **__magic_name__							:   Dict      )    ->				Union[BackboneOutput, Tuple[Tensor, ...]]:







													"""simple docstring"""
													UpperCAmelCase_	:					Tuple     =     return_dict if return_dict is not None else self.config.use_return_dict
													UpperCAmelCase_	:					str     =     (
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)
													UpperCAmelCase_	:					Optional[int]     =     output_attentions if output_attentions is not None else self.config.output_attentions

													if output_attentions:
																			raise ValueError('''Cannot output attentions for timm backbones at the moment'''      )

													if output_hidden_states:
																			# We modify the return layers to include all the stages of the backbone
																			UpperCAmelCase_	:					List[str]     =     self._all_layers
																			UpperCAmelCase_	:					int     =     self._backbone(UpperCamelCase__				,   **UpperCamelCase__      )
																			UpperCAmelCase_	:					Optional[int]     =     self._return_layers
																			UpperCAmelCase_	:					Union[str, Any]     =     tuple(hidden_states[i] for i in self.out_indices      )
													else:
																			UpperCAmelCase_	:					Dict     =     self._backbone(UpperCamelCase__				,   **UpperCamelCase__      )
																			UpperCAmelCase_	:					List[Any]     =     None

													UpperCAmelCase_	:					Any     =     tuple(UpperCamelCase__      )
													UpperCAmelCase_	:					Optional[Any]     =     tuple(UpperCamelCase__      ) if hidden_states is not None else None

													if not return_dict:
																			UpperCAmelCase_	:					Optional[int]     =     (feature_maps,)
																			if output_hidden_states:
																									UpperCAmelCase_	:					str     =     output + (hidden_states,)
																			return output

													return BackboneOutput(feature_maps=UpperCamelCase__				,   hidden_states=UpperCamelCase__				,   attentions=UpperCamelCase__      )







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}

