



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"""):
     SCREAMING_SNAKE_CASE_:List[str]             =						True
     from torch.cuda.amp import autocast

SCREAMING_SNAKE_CASE_:Any             =						logging.getLogger(__name__)




def 	__UpperCamelCase	(  _lowerCAmelCase=None      ,     _lowerCAmelCase=None		)       ->  Tuple:



    """simple docstring"""






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






@dataclass
class SCREAMING_SNAKE_CASE__     :




    '''simple docstring'''






    __lowerCamelCase			: str					=      field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}    )
    __lowerCamelCase			: Optional[str]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,						)
    __lowerCamelCase			: Optional[bool]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={"help": "Whether to freeze the feature extractor layers of the model."}    )
    __lowerCamelCase			: Optional[float]					=      field(
        default=0.1 ,						metadata={"help": "The dropout ratio for the attention probabilities."}    )
    __lowerCamelCase			: Optional[float]					=      field(
        default=0.1 ,						metadata={"help": "The dropout ratio for activations inside the fully connected layer."}    )
    __lowerCamelCase			: Optional[float]					=      field(
        default=0.1 ,						metadata={
            "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
        } ,						)
    __lowerCamelCase			: Optional[float]					=      field(
        default=0.1 ,						metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} ,						)
    __lowerCamelCase			: 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``."
            )
        } ,						)
    __lowerCamelCase			: Optional[float]					=      field(default=0.0 ,						metadata={"help": "The LayerDrop probability."}    )






@dataclass
class SCREAMING_SNAKE_CASE__     :




    '''simple docstring'''






    __lowerCamelCase			: Optional[str]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}    )
    __lowerCamelCase			: 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'"
        } ,						)
    __lowerCamelCase			: bool					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={"help": "Overwrite the cached preprocessed datasets or not."}    )
    __lowerCamelCase			: Optional[int]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={"help": "The number of processes to use for the preprocessing."} ,						)
    __lowerCamelCase			: Optional[int]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of training examples to this "
                "value if set."
            )
        } ,						)
    __lowerCamelCase			: Optional[int]					=      field(
        default=SCREAMING_SNAKE_CASE__ ,						metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of validation examples to this "
                "value if set."
            )
        } ,						)
    __lowerCamelCase			: List[str]					=      list_field(
        default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"] ,						metadata={"help": "A list of characters to remove from the transcripts."} ,						)






@dataclass
class SCREAMING_SNAKE_CASE__     :




    '''simple docstring'''






    __lowerCamelCase			: WavaVecaProcessor
    __lowerCamelCase			: Union[bool, str]					=      True
    __lowerCamelCase			: Optional[int]					=      None
    __lowerCamelCase			: Optional[int]					=      None
    __lowerCamelCase			: Optional[int]					=      None
    __lowerCamelCase			: Optional[int]					=      None






    def __call__(       self,		lowerCamelCase__		):
        # split inputs and labels since they have to be of different lenghts and need
        # different padding methods
        A :       Optional[int]          =   [{"""input_values""": feature["""input_values"""]} for feature in features]
        A :       Union[str, Any]          =   [{"""input_ids""": feature["""labels"""]} for feature in features]

        A :       List[Any]          =   self.processor.pad(
            lowerCamelCase__,		padding=self.padding,		max_length=self.max_length,		pad_to_multiple_of=self.pad_to_multiple_of,		return_tensors="""pt""",		)
        A :       str          =   self.processor.pad(
            labels=lowerCamelCase__,		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
        A :       str          =   labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1		),		-100		)

        A :       Any          =   labels

        return batch






class SCREAMING_SNAKE_CASE__     (		SCREAMING_SNAKE_CASE__    ):




    '''simple docstring'''






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__		):
        model.train()
        A :       Union[str, Any]          =   self._prepare_inputs(lowerCamelCase__		)

        if self.use_amp:
            with autocast():
                A :       Union[str, Any]          =   self.compute_loss(lowerCamelCase__,		lowerCamelCase__		)
        else:
            A :       Optional[int]          =   self.compute_loss(lowerCamelCase__,		lowerCamelCase__		)

        if self.args.n_gpu > 1:
            if model.module.config.ctc_loss_reduction == "mean":
                A :       str          =   loss.mean()
            elif model.module.config.ctc_loss_reduction == "sum":
                A :       Tuple          =   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:
            A :       Tuple          =   loss / self.args.gradient_accumulation_steps

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

        return loss.detach()




def 	__UpperCamelCase	(  )       ->  List[str]:



    """simple docstring"""






    A :       Optional[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.
        A     ,							A     ,							A :       int          =   parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
    else:
        A     ,							A     ,							A :       Union[str, Any]          =   parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    A :       str          =   None
    if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
        A :       int          =   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"""      ,     _lowerCAmelCase		)

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

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

    # Create and save tokenizer
    A :       List[Any]          =   f'''[{"".join(data_args.chars_to_ignore		)}]'''

    def remove_special_characters(_lowerCAmelCase		):
        A :       List[Any]          =   re.sub(_lowerCAmelCase      ,     """"""      ,     batch["""sentence"""]		).lower() + """ """
        return batch

    A :       Dict          =   train_dataset.map(_lowerCAmelCase      ,     remove_columns=["""sentence"""]		)
    A :       Optional[Any]          =   eval_dataset.map(_lowerCAmelCase      ,     remove_columns=["""sentence"""]		)

    def extract_all_chars(_lowerCAmelCase		):
        A :       Dict          =   """ """.join(batch["""text"""]		)
        A :       List[str]          =   list(set(_lowerCAmelCase		)		)
        return {"vocab": [vocab], "all_text": [all_text]}

    A :       str          =   train_dataset.map(
        _lowerCAmelCase      ,     batched=_lowerCAmelCase      ,     batch_size=-1      ,     keep_in_memory=_lowerCAmelCase      ,     remove_columns=train_dataset.column_names      ,     )
    A :       Tuple          =   train_dataset.map(
        _lowerCAmelCase      ,     batched=_lowerCAmelCase      ,     batch_size=-1      ,     keep_in_memory=_lowerCAmelCase      ,     remove_columns=eval_dataset.column_names      ,     )

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

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

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    A :       Tuple          =   WavaVecaCTCTokenizer(
        """vocab.json"""      ,     unk_token="""[UNK]"""      ,     pad_token="""[PAD]"""      ,     word_delimiter_token="""|"""      ,     )
    A :       Optional[int]          =   WavaVecaFeatureExtractor(
        feature_size=1      ,     sampling_rate=1_6000      ,     padding_value=0.0      ,     do_normalize=_lowerCAmelCase      ,     return_attention_mask=_lowerCAmelCase		)
    A :       Any          =   WavaVecaProcessor(feature_extractor=_lowerCAmelCase      ,     tokenizer=_lowerCAmelCase		)
    A :       Any          =   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:
        A :       List[Any]          =   min(len(_lowerCAmelCase		)      ,     data_args.max_train_samples		)
        A :       Dict          =   train_dataset.select(range(_lowerCAmelCase		)		)

    if data_args.max_val_samples is not None:
        A :       Dict          =   eval_dataset.select(range(data_args.max_val_samples		)		)

    A :       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(_lowerCAmelCase		):
        A     ,							A :       Optional[Any]          =   torchaudio.load(batch["""path"""]		)
        A :       Optional[int]          =   resampler(_lowerCAmelCase		).squeeze().numpy()
        A :       Optional[Any]          =   1_6000
        A :       Optional[Any]          =   batch["""text"""]
        return batch

    A :       Tuple          =   train_dataset.map(
        _lowerCAmelCase      ,     remove_columns=train_dataset.column_names      ,     num_proc=data_args.preprocessing_num_workers      ,     )
    A :       List[str]          =   eval_dataset.map(
        _lowerCAmelCase      ,     remove_columns=eval_dataset.column_names      ,     num_proc=data_args.preprocessing_num_workers      ,     )

    def prepare_dataset(_lowerCAmelCase		):
        # 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}.'''

        A :       int          =   processor(
            audio=batch["""speech"""]      ,     text=batch["""target_text"""]      ,     sampling_rate=batch["""sampling_rate"""][0]		)
        batch.update(_lowerCAmelCase		)
        return batch

    A :       str          =   train_dataset.map(
        _lowerCAmelCase      ,     remove_columns=train_dataset.column_names      ,     batch_size=training_args.per_device_train_batch_size      ,     batched=_lowerCAmelCase      ,     num_proc=data_args.preprocessing_num_workers      ,     )
    A :       Union[str, Any]          =   eval_dataset.map(
        _lowerCAmelCase      ,     remove_columns=eval_dataset.column_names      ,     batch_size=training_args.per_device_train_batch_size      ,     batched=_lowerCAmelCase      ,     num_proc=data_args.preprocessing_num_workers      ,     )

    # Metric
    A :       List[str]          =   datasets.load_metric("""wer"""		)

    def compute_metrics(_lowerCAmelCase		):
        A :       int          =   pred.predictions
        A :       Tuple          =   np.argmax(_lowerCAmelCase      ,     axis=-1		)

        A :       List[Any]          =   processor.tokenizer.pad_token_id

        A :       Optional[int]          =   processor.batch_decode(_lowerCAmelCase		)
        # we do not want to group tokens when computing the metrics
        A :       int          =   processor.batch_decode(pred.label_ids      ,     group_tokens=_lowerCAmelCase		)

        A :       Optional[int]          =   wer_metric.compute(predictions=_lowerCAmelCase      ,     references=_lowerCAmelCase		)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    # Data collator
    A :       int          =   DataCollatorCTCWithPadding(processor=_lowerCAmelCase      ,     padding=_lowerCAmelCase		)

    # Initialize our Trainer
    A :       int          =   CTCTrainer(
        model=_lowerCAmelCase      ,     data_collator=_lowerCAmelCase      ,     args=_lowerCAmelCase      ,     compute_metrics=_lowerCAmelCase      ,     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:
            A :       Dict          =   last_checkpoint
        elif os.path.isdir(model_args.model_name_or_path		):
            A :       Optional[Any]          =   model_args.model_name_or_path
        else:
            A :       Tuple          =   None

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

        A :       Dict          =   trainer.train(resume_from_checkpoint=_lowerCAmelCase		)
        trainer.save_model()

        A :       str          =   train_result.metrics
        A :       Tuple          =   (
            data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCAmelCase		)
        )
        A :       List[str]          =   min(_lowerCAmelCase      ,     len(_lowerCAmelCase		)		)

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

    # Evaluation
    A :       Optional[int]          =   {}
    if training_args.do_eval:
        logger.info("""*** Evaluate ***"""		)
        A :       List[str]          =   trainer.evaluate()
        A :       int          =   data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowerCAmelCase		)
        A :       str          =   min(_lowerCAmelCase      ,     len(_lowerCAmelCase		)		)

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

    return results


if __name__ == "__main__":
     main()







from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar

SCREAMING_SNAKE_CASE_:List[Any]             =						TypeVar("""KEY""")
SCREAMING_SNAKE_CASE_:Dict             =						TypeVar("""VAL""")






@dataclass(frozen=SCREAMING_SNAKE_CASE__ ,						slots=SCREAMING_SNAKE_CASE__    )
class SCREAMING_SNAKE_CASE__     (		Generic[KEY, VAL]    ):




    '''simple docstring'''






    __lowerCamelCase			: KEY
    __lowerCamelCase			: VAL






class SCREAMING_SNAKE_CASE__     (		_Item    ):




    '''simple docstring'''






    def __init__(       self		):
        super().__init__(lowerCamelCase__,		lowerCamelCase__		)






    def __bool__(       self		):
        return False


SCREAMING_SNAKE_CASE_:Optional[Any]             =						_DeletedItem()






class SCREAMING_SNAKE_CASE__     (		MutableMapping[KEY, VAL]    ):




    '''simple docstring'''






    def __init__(       self,		lowerCamelCase__ = 8,		lowerCamelCase__ = 0.75		):
        A :       List[str]          =   initial_block_size
        A :       list[_Item | None]          =   [None] * initial_block_size
        assert 0.0 < capacity_factor < 1.0
        A :       Dict          =   capacity_factor
        A :       Optional[Any]          =   0






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        return hash(lowerCamelCase__		) % len(self._buckets		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        return (ind + 1) % len(self._buckets		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        A :       List[Any]          =   self._buckets[ind]
        if not stored:
            A :       Optional[int]          =   _Item(lowerCamelCase__,		lowerCamelCase__		)
            self._len += 1
            return True
        elif stored.key == key:
            A :       int          =   _Item(lowerCamelCase__,		lowerCamelCase__		)
            return True
        else:
            return False






    def 			_lowerCAmelCase					(       self		):
        A :       Union[str, Any]          =   len(self._buckets		) * self._capacity_factor
        return len(self		) >= int(lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self		):
        if len(self._buckets		) <= self._initial_block_size:
            return False
        A :       Optional[Any]          =   len(self._buckets		) * self._capacity_factor / 2
        return len(self		) < limit






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        A :       Dict          =   self._buckets
        A :       Optional[Any]          =   [None] * new_size
        A :       List[str]          =   0
        for item in old_buckets:
            if item:
                self._add_item(item.key,		item.val		)






    def 			_lowerCAmelCase					(       self		):
        self._resize(len(self._buckets		) * 2		)






    def 			_lowerCAmelCase					(       self		):
        self._resize(len(self._buckets		) // 2		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        A :       Union[str, Any]          =   self._get_bucket_index(lowerCamelCase__		)
        for _ in range(len(self._buckets		)		):
            yield ind
            A :       Dict          =   self._get_next_ind(lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            if self._try_set(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
                break






    def __setitem__(       self,		lowerCamelCase__,		lowerCamelCase__		):
        if self._is_full():
            self._size_up()

        self._add_item(lowerCamelCase__,		lowerCamelCase__		)






    def __delitem__(       self,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            A :       Tuple          =   self._buckets[ind]
            if item is None:
                raise KeyError(lowerCamelCase__		)
            if item is _deleted:
                continue
            if item.key == key:
                A :       int          =   _deleted
                self._len -= 1
                break
        if self._is_sparse():
            self._size_down()






    def __getitem__(       self,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            A :       int          =   self._buckets[ind]
            if item is None:
                break
            if item is _deleted:
                continue
            if item.key == key:
                return item.val
        raise KeyError(lowerCamelCase__		)






    def __len__(       self		):
        return self._len






    def __iter__(       self		):
        yield from (item.key for item in self._buckets if item)






    def __repr__(       self		):
        A :       Union[str, Any]          =   """ ,""".join(
            f'''{item.key}: {item.val}''' for item in self._buckets if item		)
        return f'''HashMap({val_string})'''


