


'''simple docstring'''




import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import MobileNetVaForImageClassification, MobileNetVaModel
       from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileNetVaImageProcessor




class 			_lowercase (	__lowercase							):
   def a  (						self       :      Any      ) ->							int:
        __snake_case           =						self.config_class(**self.inputs_dict      )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,   'tf_padding'      )      )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,   'depth_multiplier'      )      )




class 			_lowercase :
   def __init__(						self       :      Tuple       ,   SCREAMING_SNAKE_CASE_       :      int       ,   SCREAMING_SNAKE_CASE_       :      Optional[int]=13       ,   SCREAMING_SNAKE_CASE_       :      Union[str, Any]=3       ,   SCREAMING_SNAKE_CASE_       :      str=32       ,   SCREAMING_SNAKE_CASE_       :      Tuple=0.2_5       ,   SCREAMING_SNAKE_CASE_       :      Tuple=8       ,   SCREAMING_SNAKE_CASE_       :      Tuple=True       ,   SCREAMING_SNAKE_CASE_       :      Dict=1024       ,   SCREAMING_SNAKE_CASE_       :      Optional[Any]=32       ,   SCREAMING_SNAKE_CASE_       :      Optional[int]="relu6"       ,   SCREAMING_SNAKE_CASE_       :      Any=0.1       ,   SCREAMING_SNAKE_CASE_       :      Tuple=0.0_2       ,   SCREAMING_SNAKE_CASE_       :      Union[str, Any]=True       ,   SCREAMING_SNAKE_CASE_       :      List[str]=True       ,   SCREAMING_SNAKE_CASE_       :      Any=10       ,   SCREAMING_SNAKE_CASE_       :      List[str]=None       ,   ) ->							int:
        __snake_case           =						parent
        __snake_case           =						batch_size
        __snake_case           =						num_channels
        __snake_case           =						image_size
        __snake_case           =						depth_multiplier
        __snake_case           =						min_depth
        __snake_case           =						tf_padding
        __snake_case           =						int(last_hidden_size * depth_multiplier      )
        __snake_case           =						output_stride
        __snake_case           =						hidden_act
        __snake_case           =						classifier_dropout_prob
        __snake_case           =						use_labels
        __snake_case           =						is_training
        __snake_case           =						num_labels
        __snake_case           =						initializer_range
        __snake_case           =						scope
   def a  (						self       :      int      ) ->							List[str]:
        __snake_case           =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

        __snake_case           =						None
        __snake_case           =						None
        if self.use_labels:
             __snake_case           =						ids_tensor([self.batch_size]       ,   self.num_labels      )
             __snake_case           =						ids_tensor([self.batch_size, self.image_size, self.image_size]       ,   self.num_labels      )

        __snake_case           =						self.get_config()

        return config, pixel_values, labels, pixel_labels
   def a  (						self       :      List[Any]      ) ->							Tuple:
        return MobileNetVaConfig(
            num_channels=self.num_channels       ,   image_size=self.image_size       ,   depth_multiplier=self.depth_multiplier       ,   min_depth=self.min_depth       ,   tf_padding=self.tf_padding       ,   hidden_act=self.hidden_act       ,   classifier_dropout_prob=self.classifier_dropout_prob       ,   initializer_range=self.initializer_range       ,   )
   def a  (						self       :      int       ,   SCREAMING_SNAKE_CASE_       :      Optional[int]       ,   SCREAMING_SNAKE_CASE_       :      Optional[int]       ,   SCREAMING_SNAKE_CASE_       :      List[Any]       ,   SCREAMING_SNAKE_CASE_       :      Tuple      ) ->							Union[str, Any]:
        __snake_case           =						MobileNetVaModel(config=SCREAMING_SNAKE_CASE_      )
        model.to(SCREAMING_SNAKE_CASE_      )
        model.eval()
        __snake_case           =						model(SCREAMING_SNAKE_CASE_      )
        self.parent.assertEqual(
            result.last_hidden_state.shape       ,   (
                self.batch_size,
                self.last_hidden_size,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )       ,   )
   def a  (						self       :      Union[str, Any]       ,   SCREAMING_SNAKE_CASE_       :      str       ,   SCREAMING_SNAKE_CASE_       :      Tuple       ,   SCREAMING_SNAKE_CASE_       :      int       ,   SCREAMING_SNAKE_CASE_       :      Tuple      ) ->							int:
        __snake_case           =						self.num_labels
        __snake_case           =						MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE_      )
        model.to(SCREAMING_SNAKE_CASE_      )
        model.eval()
        __snake_case           =						model(SCREAMING_SNAKE_CASE_       ,   labels=SCREAMING_SNAKE_CASE_      )
        self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_labels)      )





   def a  (						self       :      Optional[Any]      ) ->							Dict:
        __snake_case           =						self.prepare_config_and_inputs()
        __snake_case      ,       __snake_case      ,       __snake_case      ,       __snake_case           =						config_and_inputs
        __snake_case           =						{'pixel_values': pixel_values}
        return config, inputs_dict




@require_torch
class 			_lowercase (	__lowercase						,					__lowercase						,					unittest.TestCase							):
   _SCREAMING_SNAKE_CASE  :  Any          =	(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   _SCREAMING_SNAKE_CASE  :  str          =	(
       {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE  :  List[str]          =	False
   _SCREAMING_SNAKE_CASE  :  Any          =	False
   _SCREAMING_SNAKE_CASE  :  List[Any]          =	False
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	False
   def a  (						self       :      str      ) ->							str:
        __snake_case           =						MobileNetVaModelTester(self      )
        __snake_case           =						MobileNetVaConfigTester(self       ,   config_class=SCREAMING_SNAKE_CASE_       ,   has_text_modality=SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      List[Any]      ) ->							List[str]:
        self.config_tester.run_common_tests()
   @unittest.skip(reason='MobileNetV1 does not use inputs_embeds'      )
   def a  (						self       :      Tuple      ) ->							Dict:
        pass
   @unittest.skip(reason='MobileNetV1 does not support input and output embeddings'      )
   def a  (						self       :      Any      ) ->							Dict:
        pass
   @unittest.skip(reason='MobileNetV1 does not output attentions'      )
   def a  (						self       :      Dict      ) ->							Any:
        pass
   def a  (						self       :      int      ) ->							Any:
        __snake_case      ,       __snake_case           =						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case           =						model_class(SCREAMING_SNAKE_CASE_      )
             __snake_case           =						inspect.signature(model.forward      )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             __snake_case           =						[*signature.parameters.keys()]

             __snake_case           =						['pixel_values']
             self.assertListEqual(arg_names[:1]       ,   SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      List[Any]      ) ->							List[str]:
        __snake_case           =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      List[Any]      ) ->							List[str]:
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_       :      Tuple       ,   SCREAMING_SNAKE_CASE_       :      Union[str, Any]       ,   SCREAMING_SNAKE_CASE_       :      List[Any]      ):
             __snake_case           =						model_class(SCREAMING_SNAKE_CASE_      )
             model.to(SCREAMING_SNAKE_CASE_      )
             model.eval()

             with torch.no_grad():
                  __snake_case           =						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_      )      )

             __snake_case           =						outputs.hidden_states

             __snake_case           =						26
             self.assertEqual(len(SCREAMING_SNAKE_CASE_      )       ,   SCREAMING_SNAKE_CASE_      )

        __snake_case      ,       __snake_case           =						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case           =						True
             check_hidden_states_output(SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_      )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             __snake_case           =						True

             check_hidden_states_output(SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      List[Any]      ) ->							List[Any]:
        __snake_case           =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_      )





   @slow
   def a  (						self       :      Union[str, Any]      ) ->							List[Any]:
        for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __snake_case           =						MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE_      )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_      )





def   _a		()			->			int:






     """simple docstring"""
     __snake_case           =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
     return image




@require_torch
@require_vision
class 			_lowercase (	unittest.TestCase							):
   @cached_property
   def a  (						self       :      List[Any]      ) ->							int:
        return (
            MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'      ) if is_vision_available() else None
        )





   @slow
   def a  (						self       :      Dict      ) ->							List[str]:
        __snake_case           =						MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'      ).to(SCREAMING_SNAKE_CASE_      )

        __snake_case           =						self.default_image_processor
        __snake_case           =						prepare_img()
        __snake_case           =						image_processor(images=SCREAMING_SNAKE_CASE_       ,   return_tensors='pt'      ).to(SCREAMING_SNAKE_CASE_      )

        # forward pass
        with torch.no_grad():
             __snake_case           =						model(**SCREAMING_SNAKE_CASE_      )

        # verify the logits
        __snake_case           =						torch.Size((1, 1001)      )
        self.assertEqual(outputs.logits.shape       ,   SCREAMING_SNAKE_CASE_      )

        __snake_case           =						torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]      ).to(SCREAMING_SNAKE_CASE_      )

        self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,   SCREAMING_SNAKE_CASE_       ,   atol=1e-4      )      )










'''simple docstring'''







import re
import string

import numpy as np

import datasets


lowerCAmelCase_     						=				'''
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
'''

lowerCAmelCase_     						=				'''
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    25.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    50.0


    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results["exact_match"], 1))
    75.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["the cat", "theater", "YELLING", "agent007"]
    >>> preds = ["cat?", "theater", "yelling", "agent"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results["exact_match"], 1))
    100.0

    >>> exact_match = datasets.load_metric("exact_match")
    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]
    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results["exact_match"], 1))
    33.3

'''

lowerCAmelCase_     						=				'''
'''

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






 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   Dict:






    """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 						_UpperCamelCase (self       :  List[str]    ,		a       :  str    ,		a       :  Tuple    ,		a       :  Tuple=None    ,		a       :  Dict=False    ,		a       :  Dict=False    ,		a       :  List[str]=False    ,		)       ->   int:






    """simple docstring"""


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

    if ignore_case:
       A__       =     np.char.lower(a    )
       A__       =     np.char.lower(a    )

    if ignore_punctuation:
       A__       =     string.punctuation.maketrans(''    ,		''    ,		string.punctuation    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    if ignore_numbers:
       A__       =     string.digits.maketrans(''    ,		''    ,		string.digits    )
       A__       =     np.char.translate(a    ,		table=a    )
       A__       =     np.char.translate(a    ,		table=a    )

    A__       =     predictions == references

    return {"exact_match": np.mean(a    ) * 1_00}


