





'''simple docstring'''



from jiwer import compute_measures

import datasets


_SCREAMING_SNAKE_CASE   =      '''\\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   =      '''\\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   =      '''\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 							__lowercase    ( datasets.Metric  ):







 '''simple docstring'''

 def   _UpperCAmelCase       (self	)							->							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'''	),
            }	)       ,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	)							->							Any:







    '''simple docstring'''





    if concatenate_texts:
       return compute_measures(lowercase_       ,lowercase_	)["wer"]
    else:
       __lowercase			  =							0
       __lowercase			  =							0
       for prediction, reference in zip(lowercase_       ,lowercase_	):
          __lowercase			  =							compute_measures(lowercase_       ,lowercase_	)
          incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
          total += measures["substitutions"] + measures["deletions"] + measures["hits"]
       return incorrect / total












'''simple docstring'''



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig


_SCREAMING_SNAKE_CASE   =      logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE   =      {
    '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''',
    # See all DPT models at https://huggingface.co/models?filter=dpt
}






class 							__lowercase    ( lowerCAmelCase__  ):







	'''simple docstring'''

	a      :			Union[str, Any]     =    "dpt"


	def __init__(self       ,_lowerCamelCase=768       ,_lowerCamelCase=12       ,_lowerCamelCase=12       ,_lowerCamelCase=3072       ,_lowerCamelCase="gelu"       ,_lowerCamelCase=0.0       ,_lowerCamelCase=0.0       ,_lowerCamelCase=0.0_2       ,_lowerCamelCase=1E-1_2       ,_lowerCamelCase=384       ,_lowerCamelCase=16       ,_lowerCamelCase=3       ,_lowerCamelCase=False       ,_lowerCamelCase=True       ,_lowerCamelCase=[2, 5, 8, 11]       ,_lowerCamelCase="project"       ,_lowerCamelCase=[4, 2, 1, 0.5]       ,_lowerCamelCase=[96, 192, 384, 768]       ,_lowerCamelCase=256       ,_lowerCamelCase=-1       ,_lowerCamelCase=False       ,_lowerCamelCase=True       ,_lowerCamelCase=0.4       ,_lowerCamelCase=255       ,_lowerCamelCase=0.1       ,_lowerCamelCase=[1, 1024, 24, 24]       ,_lowerCamelCase=[0, 1]       ,_lowerCamelCase=None       ,**_lowerCamelCase       ,)							->							Tuple:







				'''simple docstring'''





				super().__init__(**_lowerCamelCase	)

				__lowercase			  =							hidden_size
				__lowercase			  =							is_hybrid

				if self.is_hybrid:
							if backbone_config is None:
										logger.info('''Initializing the config with a `BiT` backbone.'''	)
										__lowercase			  =							{
										    '''global_padding''': '''same''',
										    '''layer_type''': '''bottleneck''',
										    '''depths''': [3, 4, 9],
										    '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
										    '''embedding_dynamic_padding''': True,
										}
										__lowercase			  =							BitConfig(**_lowerCamelCase	)
							elif isinstance(_lowerCamelCase       ,_lowerCamelCase	):
										logger.info('''Initializing the config with a `BiT` backbone.'''	)
										__lowercase			  =							BitConfig(**_lowerCamelCase	)
							elif isinstance(_lowerCamelCase       ,_lowerCamelCase	):
										__lowercase			  =							backbone_config
							else:
										raise ValueError(
										    f"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}."	)

							__lowercase			  =							backbone_featmap_shape
							__lowercase			  =							neck_ignore_stages

							if readout_type != "project":
										raise ValueError('''Readout type must be \'project\' when using `DPT-hybrid` mode.'''	)
				else:
							__lowercase			  =							None
							__lowercase			  =							None
							__lowercase			  =							[]

				__lowercase			  =							num_hidden_layers
				__lowercase			  =							num_attention_heads
				__lowercase			  =							intermediate_size
				__lowercase			  =							hidden_act
				__lowercase			  =							hidden_dropout_prob
				__lowercase			  =							attention_probs_dropout_prob
				__lowercase			  =							initializer_range
				__lowercase			  =							layer_norm_eps
				__lowercase			  =							image_size
				__lowercase			  =							patch_size
				__lowercase			  =							num_channels
				__lowercase			  =							qkv_bias
				__lowercase			  =							backbone_out_indices
				if readout_type not in ["ignore", "add", "project"]:
							raise ValueError('''Readout_type must be one of [\'ignore\', \'add\', \'project\']'''	)
				__lowercase			  =							readout_type
				__lowercase			  =							reassemble_factors
				__lowercase			  =							neck_hidden_sizes
				__lowercase			  =							fusion_hidden_size
				__lowercase			  =							head_in_index
				__lowercase			  =							use_batch_norm_in_fusion_residual
				# auxiliary head attributes (semantic segmentation)
				__lowercase			  =							use_auxiliary_head
				__lowercase			  =							auxiliary_loss_weight
				__lowercase			  =							semantic_loss_ignore_index
				__lowercase			  =							semantic_classifier_dropout


	def   _UpperCAmelCase       (self	)							->							Union[str, Any]:







				'''simple docstring'''





				__lowercase			  =							copy.deepcopy(self.__dict__	)

				if output["backbone_config"] is not None:
							__lowercase			  =							self.backbone_config.to_dict()

				__lowercase			  =							self.__class__.model_type
				return output





