






'''simple docstring'''

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import (
          TFDeiTForImageClassification,
          TFDeiTForImageClassificationWithTeacher,
          TFDeiTForMaskedImageModeling,
          TFDeiTModel,
      )
      from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import DeiTImageProcessor




class     A    :






 """simple docstring"""





 def __init__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase=13			,     __lowerCAmelCase=30			,     __lowerCAmelCase=2			,     __lowerCAmelCase=3			,     __lowerCAmelCase=True			,     __lowerCAmelCase=True			,     __lowerCAmelCase=32			,     __lowerCAmelCase=2			,     __lowerCAmelCase=4			,     __lowerCAmelCase=37			,     __lowerCAmelCase="gelu"			,     __lowerCAmelCase=0.1			,     __lowerCAmelCase=0.1			,     __lowerCAmelCase=10			,     __lowerCAmelCase=0.02			,     __lowerCAmelCase=3			,     __lowerCAmelCase=None			,     __lowerCAmelCase=2			,     ):
       UpperCamelCase_				:   Any					    =							parent
       UpperCamelCase_				:   str					    =							batch_size
       UpperCamelCase_				:   Optional[int]					    =							image_size
       UpperCamelCase_				:   Tuple					    =							patch_size
       UpperCamelCase_				:   Dict					    =							num_channels
       UpperCamelCase_				:   Optional[Any]					    =							is_training
       UpperCamelCase_				:   List[str]					    =							use_labels
       UpperCamelCase_				:   int					    =							hidden_size
       UpperCamelCase_				:   Optional[Any]					    =							num_hidden_layers
       UpperCamelCase_				:   Union[str, Any]					    =							num_attention_heads
       UpperCamelCase_				:   str					    =							intermediate_size
       UpperCamelCase_				:   Any					    =							hidden_act
       UpperCamelCase_				:   List[str]					    =							hidden_dropout_prob
       UpperCamelCase_				:   int					    =							attention_probs_dropout_prob
       UpperCamelCase_				:   List[str]					    =							type_sequence_label_size
       UpperCamelCase_				:   Dict					    =							initializer_range
       UpperCamelCase_				:   Any					    =							scope
       UpperCamelCase_				:   Dict					    =							encoder_stride

       # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
       UpperCamelCase_				:   Dict					    =							(image_size // patch_size) ** 2
       UpperCamelCase_				:   Dict					    =							num_patches + 2
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   int					    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

       UpperCamelCase_				:   Optional[Any]					    =							None
       if self.use_labels:
             UpperCamelCase_				:   Tuple					    =							ids_tensor([self.batch_size]			,     self.type_sequence_label_size )

       UpperCamelCase_				:   List[str]					    =							self.get_config()

       return config, pixel_values, labels
 def   _UpperCAmelCase       (							self ):
       return DeiTConfig(
           image_size=self.image_size			,     patch_size=self.patch_size			,     num_channels=self.num_channels			,     hidden_size=self.hidden_size			,     num_hidden_layers=self.num_hidden_layers			,     num_attention_heads=self.num_attention_heads			,     intermediate_size=self.intermediate_size			,     hidden_act=self.hidden_act			,     hidden_dropout_prob=self.hidden_dropout_prob			,     attention_probs_dropout_prob=self.attention_probs_dropout_prob			,     is_decoder=UpperCamelCase__			,     initializer_range=self.initializer_range			,     encoder_stride=self.encoder_stride			,     )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Dict					    =							TFDeiTModel(config=UpperCamelCase__ )
       UpperCamelCase_				:   int					    =							model(UpperCamelCase__ )
       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size) )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[Any]					    =							TFDeiTForMaskedImageModeling(config=UpperCamelCase__ )
       UpperCamelCase_				:   Tuple					    =							model(UpperCamelCase__ )
       self.parent.assertEqual(
           result.reconstruction.shape			,     (self.batch_size, self.num_channels, self.image_size, self.image_size) )

       # test greyscale images
       UpperCamelCase_				:   Optional[Any]					    =							1
       UpperCamelCase_				:   Any					    =							TFDeiTForMaskedImageModeling(UpperCamelCase__ )

       UpperCamelCase_				:   Dict					    =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
       UpperCamelCase_				:   List[Any]					    =							model(UpperCamelCase__ )
       self.parent.assertEqual(result.reconstruction.shape			,     (self.batch_size, 1, self.image_size, self.image_size) )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[Any]					    =							self.type_sequence_label_size
       UpperCamelCase_				:   str					    =							TFDeiTForImageClassification(UpperCamelCase__ )
       UpperCamelCase_				:   Any					    =							model(UpperCamelCase__			,     labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size) )

       # test greyscale images
       UpperCamelCase_				:   Optional[Any]					    =							1
       UpperCamelCase_				:   Optional[int]					    =							TFDeiTForImageClassification(UpperCamelCase__ )

       UpperCamelCase_				:   Any					    =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
       UpperCamelCase_				:   Optional[int]					    =							model(UpperCamelCase__			,     labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size) )





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Dict					    =							self.prepare_config_and_inputs()
       UpperCamelCase_				:   Tuple					    =							config_and_inputs
       UpperCamelCase_				:   Optional[Any]					    =							{'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_tf
class     A    (      SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   unittest.TestCase						):






 """simple docstring"""





 __a			:						Union[str, Any]      =						(
     (
         TFDeiTModel,
         TFDeiTForImageClassification,
         TFDeiTForImageClassificationWithTeacher,
         TFDeiTForMaskedImageModeling,
     )
     if is_tf_available()
     else ()
 )
 __a			:						Optional[Any]      =						(
     {
         '''feature-extraction''': TFDeiTModel,
         '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
     }
     if is_tf_available()
     else {}
 )

 __a			:						str      =						False
 __a			:						Dict      =						False
 __a			:						Optional[int]      =						False
 __a			:						Tuple      =						False
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   int					    =							TFDeiTModelTester(self )
       UpperCamelCase_				:   List[Any]					    =							ConfigTester(self			,     config_class=UpperCamelCase__			,     has_text_modality=UpperCamelCase__			,     hidden_size=37 )
 def   _UpperCAmelCase       (							self ):
       self.config_tester.run_common_tests()
 @unittest.skip(reason="""DeiT does not use inputs_embeds""" )
 def   _UpperCAmelCase       (							self ):
       pass
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   str					    =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   List[Any]					    =							model_class(UpperCamelCase__ )
             self.assertIsInstance(model.get_input_embeddings()			,     (tf.keras.layers.Layer) )
             UpperCamelCase_				:   List[Any]					    =							model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(UpperCamelCase__			,     tf.keras.layers.Dense ) )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Dict					    =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   List[Any]					    =							model_class(UpperCamelCase__ )
             UpperCamelCase_				:   Optional[Any]					    =							inspect.signature(model.call )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             UpperCamelCase_				:   List[str]					    =							[*signature.parameters.keys()]

             UpperCamelCase_				:   Dict					    =							['''pixel_values''']
             self.assertListEqual(arg_names[:1]			,     UpperCamelCase__ )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__ )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__ )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   str					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       UpperCamelCase_				:   Any					    =							super()._prepare_for_class(UpperCamelCase__			,     UpperCamelCase__			,     return_labels=UpperCamelCase__ )

       if return_labels:
             if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters:
                   del inputs_dict["labels"]

       return inputs_dict





 @slow
 def   _UpperCAmelCase       (							self ):
       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase_				:   List[str]					    =							TFDeiTModel.from_pretrained(UpperCamelCase__ )
             self.assertIsNotNone(UpperCamelCase__ )






def 							snake_case					(     ):





      """simple docstring"""

      UpperCamelCase_				:   List[Any]					    =							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
      return image




@require_tf
@require_vision
class     A    (      unittest.TestCase						):






 """simple docstring"""





 @cached_property
 def   _UpperCAmelCase       (							self ):
       return (
           DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" )
           if is_vision_available()
           else None
       )





 @slow
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Any					    =							TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""" )

       UpperCamelCase_				:   Optional[int]					    =							self.default_image_processor
       UpperCamelCase_				:   Dict					    =							prepare_img()
       UpperCamelCase_				:   Any					    =							image_processor(images=UpperCamelCase__			,     return_tensors="""tf""" )

       # forward pass
       UpperCamelCase_				:   str					    =							model(**UpperCamelCase__ )

       # verify the logits
       UpperCamelCase_				:   Dict					    =							tf.TensorShape((1, 10_00) )
       self.assertEqual(outputs.logits.shape			,     UpperCamelCase__ )

       UpperCamelCase_				:   List[str]					    =							tf.constant([-1.02_66, 0.19_12, -1.28_61] )

       self.assertTrue(np.allclose(outputs.logits[0, :3]			,     UpperCamelCase__			,     atol=1E-4 ) )














'''simple docstring'''

from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse("3.8"):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


UpperCamelCase							=""


if version.parse(importlib_metadata.version("jiwer")) < version.parse("2.3.0"):




      class     A    (      tr.AbstractTransform						):






       """simple docstring"""





       def __init__(							self			,     __lowerCAmelCase = " " ):
             UpperCamelCase_				:   str					    =							sentence_delimiter
       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             return list(__lowerCAmelCase )





       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             UpperCamelCase_				:   List[Any]					    =							[]
             for sent_idx, sentence in enumerate(__lowerCAmelCase ):
                   chars.extend(self.process_string(__lowerCAmelCase ) )
                   if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowerCAmelCase ) - 1:
                         chars.append(self.sentence_delimiter )
             return chars






      UpperCamelCase							=tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      UpperCamelCase							=tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


UpperCamelCase							="\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n"

UpperCamelCase							="\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n"

UpperCamelCase							="\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> cer = datasets.load_metric(\"cer\")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n"




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






 """simple docstring"""





 def   _UpperCAmelCase       (							self ):
       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""" ),
               } )			,     codebase_urls=["""https://github.com/jitsi/jiwer/"""]			,     reference_urls=[
               """https://en.wikipedia.org/wiki/Word_error_rate""",
               """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
           ]			,     )





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       if concatenate_texts:
             return jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )["wer"]

       UpperCamelCase_				:   Optional[Any]					    =							0
       UpperCamelCase_				:   str					    =							0
       for prediction, reference in zip(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   Optional[int]					    =							jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total






