



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


lowerCAmelCase__		:					int							=''''''


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

			class        UpperCAmelCase_  (       tr.AbstractTransform	):

						'''simple docstring'''




						def __init__(   self				,							_A = " "		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= sentence_delimiter






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													return list(__lowerCAmelCase		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= []
													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







			lowerCAmelCase__		:					List[Any]							=tr.Compose(
			    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
			)
else:
			lowerCAmelCase__		:					List[str]							=tr.Compose(
			    [
			        tr.RemoveMultipleSpaces(),
			        tr.Strip(),
			        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
			        tr.ReduceToListOfListOfChars(),
			    ]
			)


lowerCAmelCase__		:					str							='''\\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'''

lowerCAmelCase__		:					str							='''\\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'''

lowerCAmelCase__		:					str							='''\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        UpperCAmelCase_  (       datasets.Metric	):

			'''simple docstring'''




			def 	_A     (   self		):







										'''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',
										        'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates',
										    ]				,							)






			def 	_A     (   self				,							_A				,							_A				,							_A=False		):







										'''simple docstring'''

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

										__SCREAMING_SNAKE_CASE									= 0
										__SCREAMING_SNAKE_CASE									= 0
										for prediction, reference in zip(__lowerCAmelCase				,							__lowerCAmelCase		):
																	__SCREAMING_SNAKE_CASE									= 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











import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__		:					Dict							=logging.get_logger(__name__)

lowerCAmelCase__		:					Optional[int]							={
    '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''',
    # See all SEW models at https://huggingface.co/models?filter=sew
}

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Optional[Any]      =  '''sew'''






						def __init__(   self				,							_A=32				,							_A=768				,							_A=12				,							_A=12				,							_A=3_072				,							_A=2				,							_A="gelu"				,							_A=0.1				,							_A=0.1				,							_A=0.1				,							_A=0.0				,							_A=0.1				,							_A=0.1				,							_A=0.0_2				,							_A=1e-5				,							_A="group"				,							_A="gelu"				,							_A=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)				,							_A=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)				,							_A=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)				,							_A=False				,							_A=128				,							_A=16				,							_A=True				,							_A=0.0_5				,							_A=10				,							_A=2				,							_A=0.0				,							_A=10				,							_A=0				,							_A="mean"				,							_A=False				,							_A=False				,							_A=256				,							_A=0				,							_A=1				,							_A=2				,							**_A				,							):







													'''simple docstring'''

													super().__init__(**_A				,							pad_token_id=_A				,							bos_token_id=_A				,							eos_token_id=_A		)
													__SCREAMING_SNAKE_CASE									= hidden_size
													__SCREAMING_SNAKE_CASE									= feat_extract_norm
													__SCREAMING_SNAKE_CASE									= feat_extract_activation
													__SCREAMING_SNAKE_CASE									= list(_A		)
													__SCREAMING_SNAKE_CASE									= list(_A		)
													__SCREAMING_SNAKE_CASE									= list(_A		)
													__SCREAMING_SNAKE_CASE									= conv_bias
													__SCREAMING_SNAKE_CASE									= num_conv_pos_embeddings
													__SCREAMING_SNAKE_CASE									= num_conv_pos_embedding_groups
													__SCREAMING_SNAKE_CASE									= len(self.conv_dim		)
													__SCREAMING_SNAKE_CASE									= num_hidden_layers
													__SCREAMING_SNAKE_CASE									= intermediate_size
													__SCREAMING_SNAKE_CASE									= squeeze_factor
													__SCREAMING_SNAKE_CASE									= hidden_act
													__SCREAMING_SNAKE_CASE									= num_attention_heads
													__SCREAMING_SNAKE_CASE									= hidden_dropout
													__SCREAMING_SNAKE_CASE									= attention_dropout
													__SCREAMING_SNAKE_CASE									= activation_dropout
													__SCREAMING_SNAKE_CASE									= feat_proj_dropout
													__SCREAMING_SNAKE_CASE									= final_dropout
													__SCREAMING_SNAKE_CASE									= layerdrop
													__SCREAMING_SNAKE_CASE									= layer_norm_eps
													__SCREAMING_SNAKE_CASE									= initializer_range
													__SCREAMING_SNAKE_CASE									= vocab_size

													if (
													    (len(self.conv_stride		) != self.num_feat_extract_layers)
													    or (len(self.conv_kernel		) != self.num_feat_extract_layers)
													    or (len(self.conv_dim		) != self.num_feat_extract_layers)
													):
																				raise ValueError(
																				    'Configuration for convolutional layers is incorrect.'
																				    'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'
																				    f"""but is `len(config.conv_dim) = {len(self.conv_dim		)}`, `len(config.conv_stride)"""
																				    f"""= {len(self.conv_stride		)}`, `len(config.conv_kernel) = {len(self.conv_kernel		)}`."""		)

													# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
													__SCREAMING_SNAKE_CASE									= apply_spec_augment
													__SCREAMING_SNAKE_CASE									= mask_time_prob
													__SCREAMING_SNAKE_CASE									= mask_time_length
													__SCREAMING_SNAKE_CASE									= mask_time_min_masks
													__SCREAMING_SNAKE_CASE									= mask_feature_prob
													__SCREAMING_SNAKE_CASE									= mask_feature_length
													__SCREAMING_SNAKE_CASE									= mask_feature_min_masks

													# ctc loss
													__SCREAMING_SNAKE_CASE									= ctc_loss_reduction
													__SCREAMING_SNAKE_CASE									= ctc_zero_infinity

													# sequence classification
													__SCREAMING_SNAKE_CASE									= use_weighted_layer_sum
													__SCREAMING_SNAKE_CASE									= classifier_proj_size






						@property
						def 	_A     (   self		):







													'''simple docstring'''

													return functools.reduce(operator.mul				,							self.conv_stride				,							1		)






