
"""simple docstring"""






import argparse
import os

import transformers

from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
from .utils import logging


logging.set_verbosity_info()

_lowercase							=				logging.get_logger(__name__)


_lowercase							=				{name: getattr(transformers, name + '''Fast''') for name in SLOW_TO_FAST_CONVERTERS}



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__			,   __magic_name__      )						->Optional[int]:
			if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES:
						raise ValueError(F'''Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys()      )}.'''      )

			if tokenizer_name is None:
						__lowercase       =       TOKENIZER_CLASSES
			else:
						__lowercase       =       {tokenizer_name: getattr(lowerCamelCase__			,   tokenizer_name + "Fast"      )}

			logger.info(F'''Loading tokenizer classes: {tokenizer_names}'''      )

			for tokenizer_name in tokenizer_names:
						__lowercase       =       TOKENIZER_CLASSES[tokenizer_name]

						__lowercase       =       True
						if checkpoint_name is None:
									__lowercase       =       list(tokenizer_class.max_model_input_sizes.keys()      )
						else:
									__lowercase       =       [checkpoint_name]

						logger.info(F'''For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}'''      )

						for checkpoint in checkpoint_names:
									logger.info(F'''Loading {tokenizer_class.__class__.__name__} {checkpoint}'''      )

									# Load tokenizer
									__lowercase       =       tokenizer_class.from_pretrained(lowerCamelCase__			,   force_download=lowerCamelCase__      )

									# Save fast tokenizer
									logger.info(F'''Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}'''      )

									# For organization names we create sub-directories
									if "/" in checkpoint:
												__lowercase   ,					__lowercase       =       checkpoint.split("/"      )
												__lowercase       =       os.path.join(lowerCamelCase__			,   lowerCamelCase__      )
									elif add_prefix:
												__lowercase       =       checkpoint
												__lowercase       =       dump_path
									else:
												__lowercase       =       None
												__lowercase       =       dump_path

									logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}'''      )

									if checkpoint in list(tokenizer.pretrained_vocab_files_map.values()      )[0]:
												__lowercase       =       list(tokenizer.pretrained_vocab_files_map.values()      )[0][checkpoint]
												__lowercase       =       file_path.split(lowerCamelCase__      )[-1][0]
												if next_char == "/":
															__lowercase       =       os.path.join(lowerCamelCase__			,   lowerCamelCase__      )
															__lowercase       =       None

												logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}'''      )

									__lowercase       =       tokenizer.save_pretrained(
									    lowerCamelCase__			,   legacy_format=lowerCamelCase__			,   filename_prefix=lowerCamelCase__      )
									logger.info(F'''=> File names {file_names}'''      )

									for file_name in file_names:
												if not file_name.endswith("tokenizer.json"      ):
															os.remove(lowerCamelCase__      )
															logger.info(F'''=> removing {file_name}'''      )


if __name__ == "__main__":
					_lowercase							=				argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '''--dump_path''', default=None, type=str, required=True, help='''Path to output generated fast tokenizer files.'''
					)
					parser.add_argument(
					    '''--tokenizer_name''',
					    default=None,
					    type=str,
					    help=(
					        F"Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will "
					        '''download and convert all the checkpoints from AWS.'''
					    ),
					)
					parser.add_argument(
					    '''--checkpoint_name''',
					    default=None,
					    type=str,
					    help='''Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.''',
					)
					parser.add_argument(
					    '''--force_download''',
					    action='''store_true''',
					    help='''Re-download checkpoints.''',
					)
					_lowercase							=				parser.parse_args()

					convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)







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


__A							=''''''


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




			class        _SCREAMING_SNAKE_CASE	( tr.AbstractTransform		):



				def __init__(       self		,    lowercase = " "					)							->			List[str]:
								lowerCamelCase_         =     sentence_delimiter



				def        SCREAMING_SNAKE_CASE_(       self		,    lowercase					)							->			Optional[int]:
								return list(lowercase					)



				def        SCREAMING_SNAKE_CASE_(       self		,    lowercase					)							->			List[str]:
								lowerCamelCase_         =     []
								for sent_idx, sentence in enumerate(lowercase					):
												chars.extend(self.process_string(lowercase					)					)
												if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowercase					) - 1:
																chars.append(self.sentence_delimiter					)
								return chars



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


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

__A							='''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'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
performance of the ASR system with a CER of 0 being a perfect score.
'''

__A							='''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''




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



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Union[str, Any]:
					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        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase		,    lowercase=False					)							->			List[str]:
					if concatenate_texts:
									return jiwer.compute_measures(
									    lowercase		,    lowercase		,    truth_transform=lowercase		,    hypothesis_transform=lowercase		,    )["wer"]

					lowerCamelCase_         =     0
					lowerCamelCase_         =     0
					for prediction, reference in zip(lowercase		,    lowercase					):
									lowerCamelCase_         =     jiwer.compute_measures(
									    lowercase		,    lowercase		,    truth_transform=lowercase		,    hypothesis_transform=lowercase		,    )
									incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
									total += measures["substitutions"] + measures["deletions"] + measures["hits"]

					return incorrect / total


