


from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
 import tensorflow as tf

 from transformers import TFBlipTextModel
 from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=12,   lowerCamelCase=7,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=99,   lowerCamelCase=32,   lowerCamelCase=32,   lowerCamelCase=2,   lowerCamelCase=4,   lowerCamelCase=37,   lowerCamelCase=0.1,   lowerCamelCase=0.1,   lowerCamelCase=5_12,   lowerCamelCase=0.0_2,   lowerCamelCase=0,   lowerCamelCase=None,   ) ->     int:




           """simple docstring"""

           _lowercase :							Dict   	=	parent
           _lowercase :							Optional[Any]   	=	batch_size
           _lowercase :							str   	=	seq_length
           _lowercase :							Optional[int]   	=	is_training
           _lowercase :							List[Any]   	=	use_input_mask
           _lowercase :							List[str]   	=	use_labels
           _lowercase :							List[str]   	=	vocab_size
           _lowercase :							int   	=	hidden_size
           _lowercase :							Optional[int]   	=	projection_dim
           _lowercase :							str   	=	num_hidden_layers
           _lowercase :							Optional[Any]   	=	num_attention_heads
           _lowercase :							Optional[int]   	=	intermediate_size
           _lowercase :							Any   	=	dropout
           _lowercase :							int   	=	attention_dropout
           _lowercase :							Optional[Any]   	=	max_position_embeddings
           _lowercase :							Optional[Any]   	=	initializer_range
           _lowercase :							List[str]   	=	scope
           _lowercase :							str   	=	bos_token_id
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	ids_tensor([self.batch_size, self.seq_length],   self.vocab_size)

           _lowercase :							Tuple   	=	None
           if self.use_input_mask:
               _lowercase :							Optional[Any]   	=	random_attention_mask([self.batch_size, self.seq_length])

           if input_mask is not None:
               _lowercase :							Optional[int]   	=	input_mask.numpy()
               _lowercase	,       _lowercase :							int   	=	input_mask.shape
               _lowercase :							int   	=	np.random.randint(1,   seq_length - 1,   size=(batch_size,))
               for batch_idx, start_index in enumerate(lowerCamelCase):
                   _lowercase :							str   	=	1
                   _lowercase :							Any   	=	0

           _lowercase :							Optional[int]   	=	self.get_config()

           return config, input_ids, tf.convert_to_tensor(lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           return BlipTextConfig(
               vocab_size=self.vocab_size,   hidden_size=self.hidden_size,   projection_dim=self.projection_dim,   num_hidden_layers=self.num_hidden_layers,   num_attention_heads=self.num_attention_heads,   intermediate_size=self.intermediate_size,   dropout=self.dropout,   attention_dropout=self.attention_dropout,   max_position_embeddings=self.max_position_embeddings,   initializer_range=self.initializer_range,   bos_token_id=self.bos_token_id,   )
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	TFBlipTextModel(config=lowerCamelCase)
           _lowercase :							int   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   training=lowerCamelCase)
           _lowercase :							Union[str, Any]   	=	model(lowerCamelCase,   training=lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size))
           self.parent.assertEqual(result.pooler_output.shape,   (self.batch_size, self.hidden_size))




       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.prepare_config_and_inputs()
           _lowercase	,       _lowercase	,       _lowercase :							Any   	=	config_and_inputs
           _lowercase :							Optional[int]   	=	{'input_ids': input_ids, 'attention_mask': input_mask}
           return config, inputs_dict






@require_tf
class _lowerCamelCase(		_a,				unittest.TestCase     ):
       lowercase_				:			List[Any]									=    (TFBlipTextModel,) if is_tf_available() else ()
       lowercase_				:			Any									=    False
       lowercase_				:			Optional[int]									=    False
       lowercase_				:			Optional[int]									=    False
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           _lowercase :							int   	=	BlipTextModelTester(self)
           _lowercase :							str   	=	ConfigTester(self,   config_class=lowerCamelCase,   hidden_size=37)
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							str   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           pass
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           pass
       @unittest.skip(reason='Blip does not use inputs_embeds')
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           pass
       @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING')
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           pass
       @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING')
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           pass
       @slow
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase :							Optional[int]   	=	TFBlipTextModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)




       def     UpperCamelCase  (      self,   lowerCamelCase=True) ->     int:




           """simple docstring"""

           super().test_pt_tf_model_equivalence(allow_missing_keys=lowerCamelCase)






from jiwer import compute_measures

import datasets


SCREAMING_SNAKE_CASE :   Tuple							      =				"\\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"

SCREAMING_SNAKE_CASE :   Optional[Any]							      =				"\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (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 words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

SCREAMING_SNAKE_CASE :   Any							      =				"\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word 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    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,				_KWARGS_DESCRIPTION     )
class _lowerCamelCase(		datasets.Metric     ):
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """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'),
                   }),   codebase_urls=['https://github.com/jitsi/jiwer/'],   reference_urls=[
                   'https://en.wikipedia.org/wiki/Word_error_rate',
               ],   )




       def     UpperCamelCase  (      self,   lowerCamelCase=None,   lowerCamelCase=None,   lowerCamelCase=False) ->     Optional[Any]:




           """simple docstring"""

           if concatenate_texts:
               return compute_measures(lowerCamelCase,   lowerCamelCase)["wer"]
           else:
               _lowercase :							Dict   	=	0
               _lowercase :							Optional[int]   	=	0
               for prediction, reference in zip(lowerCamelCase,   lowerCamelCase):
                   _lowercase :							List[Any]   	=	compute_measures(lowerCamelCase,   lowerCamelCase)
                   incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                   total += measures["substitutions"] + measures["deletions"] + measures["hits"]
               return incorrect / total


