


"""simple docstring"""



import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
  from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
  __snake_case         =					True
  from torch.cuda.amp import autocast

__snake_case         =					logging.getLogger(__name__)







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]=None		,							lowercase						:						Union[str, Any]=None				)			->		Any:


    """simple docstring"""





    return field(default_factory=lambda: default		,							metadata=lowercase				)







@dataclass
class _lowerCAmelCase       :
   __UpperCAmelCase				: str													=						field(
       metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}			)
   __UpperCAmelCase				: Optional[str]													=						field(
       default=snake_case_					,							metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}					,							)
   __UpperCAmelCase				: Optional[bool]													=						field(
       default=snake_case_					,							metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}			)
   __UpperCAmelCase				: Optional[float]													=						field(
       default=0.1					,							metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}			)
   __UpperCAmelCase				: Optional[float]													=						field(
       default=0.1					,							metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}			)
   __UpperCAmelCase				: Optional[float]													=						field(
       default=0.1					,							metadata={
           '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
       }					,							)
   __UpperCAmelCase				: Optional[float]													=						field(
       default=0.1					,							metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}					,							)
   __UpperCAmelCase				: Optional[float]													=						field(
       default=0.05					,							metadata={
           '''help''': (
               '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
               '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
               '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
           )
       }					,							)
   __UpperCAmelCase				: Optional[float]													=						field(default=0.0					,							metadata={'''help''': '''The LayerDrop probability.'''}			)







@dataclass
class _lowerCAmelCase       :
   __UpperCAmelCase				: Optional[str]													=						field(
       default=snake_case_					,							metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}			)
   __UpperCAmelCase				: Optional[str]													=						field(
       default='''train+validation'''					,							metadata={
           '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
       }					,							)
   __UpperCAmelCase				: bool													=						field(
       default=snake_case_					,							metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}			)
   __UpperCAmelCase				: Optional[int]													=						field(
       default=snake_case_					,							metadata={'''help''': '''The number of processes to use for the preprocessing.'''}					,							)
   __UpperCAmelCase				: Optional[int]													=						field(
       default=snake_case_					,							metadata={
           '''help''': (
               '''For debugging purposes or quicker training, truncate the number of training examples to this '''
               '''value if set.'''
           )
       }					,							)
   __UpperCAmelCase				: Optional[int]													=						field(
       default=snake_case_					,							metadata={
           '''help''': (
               '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
               '''value if set.'''
           )
       }					,							)
   __UpperCAmelCase				: List[str]													=						list_field(
       default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']					,							metadata={'''help''': '''A list of characters to remove from the transcripts.'''}					,							)







@dataclass
class _lowerCAmelCase       :
   __UpperCAmelCase				: WavaVecaProcessor
   __UpperCAmelCase				: Union[bool, str]													=						True
   __UpperCAmelCase				: Optional[int]													=						None
   __UpperCAmelCase				: Optional[int]													=						None
   __UpperCAmelCase				: Optional[int]													=						None
   __UpperCAmelCase				: Optional[int]													=						None







   def __call__(			self		,			UpperCamelCase__		)			->	Dict[str, torch.Tensor]:

       '''simple docstring'''




       snake_case					:   str         =					[{"input_values": feature["input_values"]} for feature in features]
       snake_case					:   Any         =					[{"input_ids": feature["labels"]} for feature in features]

       snake_case					:   Tuple         =					self.processor.pad(
           UpperCamelCase__		,			padding=self.padding		,			max_length=self.max_length		,			pad_to_multiple_of=self.pad_to_multiple_of		,			return_tensors="pt"		,			)
       snake_case					:   Optional[Any]         =					self.processor.pad(
           labels=UpperCamelCase__		,			padding=self.padding		,			max_length=self.max_length_labels		,			pad_to_multiple_of=self.pad_to_multiple_of_labels		,			return_tensors="pt"		,			)

       # replace padding with -100 to ignore loss correctly
       snake_case					:   Optional[Any]         =					labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1		)		,			-100		)

       snake_case					:   List[Any]         =					labels

       return batch







class _lowerCAmelCase       (   snake_case_			):







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__		)			->	torch.Tensor:

       '''simple docstring'''




       model.train()
       snake_case					:   List[str]         =					self._prepare_inputs(UpperCamelCase__		)

       if self.use_amp:
           with autocast():
               snake_case					:   List[str]         =					self.compute_loss(UpperCamelCase__		,			UpperCamelCase__		)
       else:
           snake_case					:   Tuple         =					self.compute_loss(UpperCamelCase__		,			UpperCamelCase__		)

       if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
               snake_case					:   Dict         =					loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
               snake_case					:   int         =					loss.sum() / (inputs["labels"] >= 0).sum()
           else:
               raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'		)

       if self.args.gradient_accumulation_steps > 1:
           snake_case					:   Optional[int]         =					loss / self.args.gradient_accumulation_steps

       if self.use_amp:
           self.scaler.scale(UpperCamelCase__		).backward()
       elif self.use_apex:
           with amp.scale_loss(UpperCamelCase__		,			self.optimizer		) as scaled_loss:
               scaled_loss.backward()
       elif self.deepspeed:
           self.deepspeed.backward(UpperCamelCase__		)
       else:
           loss.backward()

       return loss.detach()







def 						__lowerCAmelCase		(		)			->		Tuple:


    """simple docstring"""





    snake_case					:   int         =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
    if len(sys.argv				) == 2 and sys.argv[1].endswith(".json"				):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        snake_case      ,snake_case      ,snake_case					:   Tuple         =					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
    else:
        snake_case      ,snake_case      ,snake_case					:   List[Any]         =					parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    snake_case					:   List[str]         =					None
    if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
        snake_case					:   List[Any]         =					get_last_checkpoint(training_args.output_dir				)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
            raise ValueError(
                F'Output directory ({training_args.output_dir}) already exists and is not empty. '
                "Use --overwrite_output_dir to overcome."				)
        elif last_checkpoint is not None:
            logger.info(
                F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."				)

    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"		,							datefmt="%m/%d/%Y %H:%M:%S"		,							handlers=[logging.StreamHandler(sys.stdout				)]		,							)
    logger.setLevel(logging.INFO if is_main_process(training_args.local_rank				) else logging.WARN				)

    # Log on each process the small summary:
    logger.warning(
        F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
        + F'distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}'				)
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank				):
        transformers.utils.logging.set_verbosity_info()
    logger.info("Training/evaluation parameters %s"		,							lowercase				)

    # Set seed before initializing model.
    set_seed(training_args.seed				)

    # Get the datasets:
    snake_case					:   Union[str, Any]         =					datasets.load_dataset(
        "common_voice"		,							data_args.dataset_config_name		,							split=data_args.train_split_name				)
    snake_case					:   Optional[int]         =					datasets.load_dataset("common_voice"		,							data_args.dataset_config_name		,							split="test"				)

    # Create and save tokenizer
    snake_case					:   Dict         =					F'[{"".join(data_args.chars_to_ignore				)}]'

    def remove_special_characters(lowercase						:						Optional[int]				):
        snake_case					:   Any         =					re.sub(lowercase		,							""		,							batch["sentence"]				).lower() + " "
        return batch

    snake_case					:   Any         =					train_dataset.map(lowercase		,							remove_columns=["sentence"]				)
    snake_case					:   int         =					eval_dataset.map(lowercase		,							remove_columns=["sentence"]				)

    def extract_all_chars(lowercase						:						Tuple				):
        snake_case					:   Union[str, Any]         =					" ".join(batch["text"]				)
        snake_case					:   Optional[int]         =					list(set(lowercase				)				)
        return {"vocab": [vocab], "all_text": [all_text]}

    snake_case					:   Tuple         =					train_dataset.map(
        lowercase		,							batched=lowercase		,							batch_size=-1		,							keep_in_memory=lowercase		,							remove_columns=train_dataset.column_names		,							)
    snake_case					:   Union[str, Any]         =					train_dataset.map(
        lowercase		,							batched=lowercase		,							batch_size=-1		,							keep_in_memory=lowercase		,							remove_columns=eval_dataset.column_names		,							)

    snake_case					:   Any         =					list(set(vocab_train["vocab"][0]				) | set(vocab_test["vocab"][0]				)				)
    snake_case					:   int         =					{v: k for k, v in enumerate(lowercase				)}
    snake_case					:   str         =					vocab_dict[" "]
    del vocab_dict[" "]
    snake_case					:   Union[str, Any]         =					len(lowercase				)
    snake_case					:   Optional[int]         =					len(lowercase				)

    with open("vocab.json"		,							"w"				) as vocab_file:
        json.dump(lowercase		,							lowercase				)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    snake_case					:   Dict         =					WavaVecaCTCTokenizer(
        "vocab.json"		,							unk_token="[UNK]"		,							pad_token="[PAD]"		,							word_delimiter_token="|"		,							)
    snake_case					:   Optional[int]         =					WavaVecaFeatureExtractor(
        feature_size=1		,							sampling_rate=1_6000		,							padding_value=0.0		,							do_normalize=lowercase		,							return_attention_mask=lowercase				)
    snake_case					:   List[Any]         =					WavaVecaProcessor(feature_extractor=lowercase		,							tokenizer=lowercase				)
    snake_case					:   Dict         =					WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path		,							cache_dir=model_args.cache_dir		,							activation_dropout=model_args.activation_dropout		,							attention_dropout=model_args.attention_dropout		,							hidden_dropout=model_args.hidden_dropout		,							feat_proj_dropout=model_args.feat_proj_dropout		,							mask_time_prob=model_args.mask_time_prob		,							gradient_checkpointing=training_args.gradient_checkpointing		,							layerdrop=model_args.layerdrop		,							ctc_loss_reduction="mean"		,							pad_token_id=processor.tokenizer.pad_token_id		,							vocab_size=len(processor.tokenizer				)		,							)

    if data_args.max_train_samples is not None:
        snake_case					:   Tuple         =					min(len(lowercase				)		,							data_args.max_train_samples				)
        snake_case					:   Optional[int]         =					train_dataset.select(range(lowercase				)				)

    if data_args.max_val_samples is not None:
        snake_case					:   int         =					eval_dataset.select(range(data_args.max_val_samples				)				)

    snake_case					:   Any         =					torchaudio.transforms.Resample(4_8000		,							1_6000				)

    # Preprocessing the datasets.
    # We need to read the aduio files as arrays and tokenize the targets.
    def speech_file_to_array_fn(lowercase						:						Any				):
        snake_case      ,snake_case					:   str         =					torchaudio.load(batch["path"]				)
        snake_case					:   Union[str, Any]         =					resampler(lowercase				).squeeze().numpy()
        snake_case					:   List[str]         =					1_6000
        snake_case					:   int         =					batch["text"]
        return batch

    snake_case					:   Optional[Any]         =					train_dataset.map(
        lowercase		,							remove_columns=train_dataset.column_names		,							num_proc=data_args.preprocessing_num_workers		,							)
    snake_case					:   int         =					eval_dataset.map(
        lowercase		,							remove_columns=eval_dataset.column_names		,							num_proc=data_args.preprocessing_num_workers		,							)

    def prepare_dataset(lowercase						:						str				):
        # check that all files have the correct sampling rate
        assert (
            len(set(batch["sampling_rate"]				)				) == 1
        ), F'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

        snake_case					:   str         =					processor(
            audio=batch["speech"]		,							text=batch["target_text"]		,							sampling_rate=batch["sampling_rate"][0]				)
        batch.update(lowercase				)
        return batch

    snake_case					:   List[Any]         =					train_dataset.map(
        lowercase		,							remove_columns=train_dataset.column_names		,							batch_size=training_args.per_device_train_batch_size		,							batched=lowercase		,							num_proc=data_args.preprocessing_num_workers		,							)
    snake_case					:   List[str]         =					eval_dataset.map(
        lowercase		,							remove_columns=eval_dataset.column_names		,							batch_size=training_args.per_device_train_batch_size		,							batched=lowercase		,							num_proc=data_args.preprocessing_num_workers		,							)

    # Metric
    snake_case					:   Any         =					datasets.load_metric("wer"				)

    def compute_metrics(lowercase						:						Any				):
        snake_case					:   str         =					pred.predictions
        snake_case					:   Any         =					np.argmax(lowercase		,							axis=-1				)

        snake_case					:   Dict         =					processor.tokenizer.pad_token_id

        snake_case					:   List[str]         =					processor.batch_decode(lowercase				)
        # we do not want to group tokens when computing the metrics
        snake_case					:   Tuple         =					processor.batch_decode(pred.label_ids		,							group_tokens=lowercase				)

        snake_case					:   Union[str, Any]         =					wer_metric.compute(predictions=lowercase		,							references=lowercase				)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    # Data collator
    snake_case					:   List[Any]         =					DataCollatorCTCWithPadding(processor=lowercase		,							padding=lowercase				)

    # Initialize our Trainer
    snake_case					:   Optional[Any]         =					CTCTrainer(
        model=lowercase		,							data_collator=lowercase		,							args=lowercase		,							compute_metrics=lowercase		,							train_dataset=train_dataset if training_args.do_train else None		,							eval_dataset=eval_dataset if training_args.do_eval else None		,							tokenizer=processor.feature_extractor		,							)

    # Training
    if training_args.do_train:
        if last_checkpoint is not None:
            snake_case					:   Optional[Any]         =					last_checkpoint
        elif os.path.isdir(model_args.model_name_or_path				):
            snake_case					:   List[str]         =					model_args.model_name_or_path
        else:
            snake_case					:   str         =					None

        # Save the feature_extractor and the tokenizer
        if is_main_process(training_args.local_rank				):
            processor.save_pretrained(training_args.output_dir				)

        snake_case					:   Dict         =					trainer.train(resume_from_checkpoint=lowercase				)
        trainer.save_model()

        snake_case					:   Optional[Any]         =					train_result.metrics
        snake_case					:   Union[str, Any]         =					(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase				)
        )
        snake_case					:   Optional[Any]         =					min(lowercase		,							len(lowercase				)				)

        trainer.log_metrics("train"		,							lowercase				)
        trainer.save_metrics("train"		,							lowercase				)
        trainer.save_state()

    # Evaluation
    snake_case					:   Tuple         =					{}
    if training_args.do_eval:
        logger.info("*** Evaluate ***"				)
        snake_case					:   int         =					trainer.evaluate()
        snake_case					:   Tuple         =					data_args.max_val_samples if data_args.max_val_samples is not None else len(lowercase				)
        snake_case					:   Dict         =					min(lowercase		,							len(lowercase				)				)

        trainer.log_metrics("eval"		,							lowercase				)
        trainer.save_metrics("eval"		,							lowercase				)

    return results


if __name__ == "__main__":
  main()









"""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


__snake_case         =					""""""


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







  class _lowerCAmelCase       (   tr.AbstractTransform			):







     def __init__(			self		,			UpperCamelCase__ = " "		)			->	Any:

         '''simple docstring'''




         snake_case					:   Optional[Any]         =					sentence_delimiter







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[Any]:

         '''simple docstring'''




         return list(UpperCamelCase__		)







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	List[Any]:

         '''simple docstring'''




         snake_case					:   Dict         =					[]
         for sent_idx, sentence in enumerate(UpperCamelCase__		):
             chars.extend(self.process_string(UpperCamelCase__		)		)
             if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(UpperCamelCase__		) - 1:
                 chars.append(self.sentence_delimiter		)
         return chars



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


__snake_case         =					"""\
@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.}
}
"""

__snake_case         =					"""\
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.
"""

__snake_case         =					"""
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 _lowerCAmelCase       (   datasets.Metric			):







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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__=False		)			->	Optional[int]:

       '''simple docstring'''




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

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

       return incorrect / total





