





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"):
					UpperCamelCase__     =	True
					from torch.cuda.amp import autocast

UpperCamelCase__     =	logging.getLogger(__name__)





def       _UpperCamelCase       (a__				:List[Any]=None				,     a__				:List[str]=None    ):






				"""simple docstring"""





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

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






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






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






							def __call__(  self					,	__lowerCAmelCase					):
											# split inputs and labels since they have to be of different lenghts and need
											# different padding methods
											UpperCamelCase__			       =     [{"""input_values""": feature["""input_values"""]} for feature in features]
											UpperCamelCase__			       =     [{"""input_ids""": feature["""labels"""]} for feature in features]

											UpperCamelCase__			       =     self.processor.pad(
											    __lowerCAmelCase					,	padding=self.padding					,	max_length=self.max_length					,	pad_to_multiple_of=self.pad_to_multiple_of					,	return_tensors="""pt"""					,	)
											UpperCamelCase__			       =     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
											UpperCamelCase__			       =     labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1					)					,	-100					)

											UpperCamelCase__			       =     labels

											return batch






class     __SCREAMING_SNAKE_CASE   (       _a    ):






							def 			_lowerCamelCase						(  self					,	__lowerCAmelCase					,	__lowerCAmelCase					):
											model.train()
											UpperCamelCase__			       =     self._prepare_inputs(__lowerCAmelCase					)

											if self.use_amp:
															with autocast():
																			UpperCamelCase__			       =     self.compute_loss(__lowerCAmelCase					,	__lowerCAmelCase					)
											else:
															UpperCamelCase__			       =     self.compute_loss(__lowerCAmelCase					,	__lowerCAmelCase					)

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






				"""simple docstring"""





				UpperCamelCase__			       =     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.
								UpperCamelCase__       ,       UpperCamelCase__       ,       UpperCamelCase__			       =     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]    )    )
				else:
								UpperCamelCase__       ,       UpperCamelCase__       ,       UpperCamelCase__			       =     parser.parse_args_into_dataclasses()

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

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

				# Get the datasets:
				UpperCamelCase__			       =     datasets.load_dataset(
				    """common_voice"""				,     data_args.dataset_config_name				,     split=data_args.train_split_name    )
				UpperCamelCase__			       =     datasets.load_dataset("""common_voice"""				,     data_args.dataset_config_name				,     split="""test"""    )

				# Create and save tokenizer
				UpperCamelCase__			       =     f"""[{"".join(data_args.chars_to_ignore    )}]"""

				def remove_special_characters(a__				:Tuple    ):
								UpperCamelCase__			       =     re.sub(a__				,     """"""				,     batch["""sentence"""]    ).lower() + """ """
								return batch

				UpperCamelCase__			       =     train_dataset.map(a__				,     remove_columns=["""sentence"""]    )
				UpperCamelCase__			       =     eval_dataset.map(a__				,     remove_columns=["""sentence"""]    )

				def extract_all_chars(a__				:Dict    ):
								UpperCamelCase__			       =     """ """.join(batch["""text"""]    )
								UpperCamelCase__			       =     list(set(a__    )    )
								return {"vocab": [vocab], "all_text": [all_text]}

				UpperCamelCase__			       =     train_dataset.map(
				    a__				,     batched=a__				,     batch_size=-1				,     keep_in_memory=a__				,     remove_columns=train_dataset.column_names				,     )
				UpperCamelCase__			       =     train_dataset.map(
				    a__				,     batched=a__				,     batch_size=-1				,     keep_in_memory=a__				,     remove_columns=eval_dataset.column_names				,     )

				UpperCamelCase__			       =     list(set(vocab_train["""vocab"""][0]    ) | set(vocab_test["""vocab"""][0]    )    )
				UpperCamelCase__			       =     {v: k for k, v in enumerate(a__    )}
				UpperCamelCase__			       =     vocab_dict[""" """]
				del vocab_dict[" "]
				UpperCamelCase__			       =     len(a__    )
				UpperCamelCase__			       =     len(a__    )

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

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

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

				UpperCamelCase__			       =     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(a__				:str    ):
								UpperCamelCase__       ,       UpperCamelCase__			       =     torchaudio.load(batch["""path"""]    )
								UpperCamelCase__			       =     resampler(a__    ).squeeze().numpy()
								UpperCamelCase__			       =     1_6000
								UpperCamelCase__			       =     batch["""text"""]
								return batch

				UpperCamelCase__			       =     train_dataset.map(
				    a__				,     remove_columns=train_dataset.column_names				,     num_proc=data_args.preprocessing_num_workers				,     )
				UpperCamelCase__			       =     eval_dataset.map(
				    a__				,     remove_columns=eval_dataset.column_names				,     num_proc=data_args.preprocessing_num_workers				,     )

				def prepare_dataset(a__				:int    ):
								# 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}."""

								UpperCamelCase__			       =     processor(
								    audio=batch["""speech"""]				,     text=batch["""target_text"""]				,     sampling_rate=batch["""sampling_rate"""][0]    )
								batch.update(a__    )
								return batch

				UpperCamelCase__			       =     train_dataset.map(
				    a__				,     remove_columns=train_dataset.column_names				,     batch_size=training_args.per_device_train_batch_size				,     batched=a__				,     num_proc=data_args.preprocessing_num_workers				,     )
				UpperCamelCase__			       =     eval_dataset.map(
				    a__				,     remove_columns=eval_dataset.column_names				,     batch_size=training_args.per_device_train_batch_size				,     batched=a__				,     num_proc=data_args.preprocessing_num_workers				,     )

				# Metric
				UpperCamelCase__			       =     datasets.load_metric("""wer"""    )

				def compute_metrics(a__				:Any    ):
								UpperCamelCase__			       =     pred.predictions
								UpperCamelCase__			       =     np.argmax(a__				,     axis=-1    )

								UpperCamelCase__			       =     processor.tokenizer.pad_token_id

								UpperCamelCase__			       =     processor.batch_decode(a__    )
								# we do not want to group tokens when computing the metrics
								UpperCamelCase__			       =     processor.batch_decode(pred.label_ids				,     group_tokens=a__    )

								UpperCamelCase__			       =     wer_metric.compute(predictions=a__				,     references=a__    )

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				# Data collator
				UpperCamelCase__			       =     DataCollatorCTCWithPadding(processor=a__				,     padding=a__    )

				# Initialize our Trainer
				UpperCamelCase__			       =     CTCTrainer(
				    model=a__				,     data_collator=a__				,     args=a__				,     compute_metrics=a__				,     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:
												UpperCamelCase__			       =     last_checkpoint
								elif os.path.isdir(model_args.model_name_or_path    ):
												UpperCamelCase__			       =     model_args.model_name_or_path
								else:
												UpperCamelCase__			       =     None

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

								UpperCamelCase__			       =     trainer.train(resume_from_checkpoint=a__    )
								trainer.save_model()

								UpperCamelCase__			       =     train_result.metrics
								UpperCamelCase__			       =     (
								    data_args.max_train_samples if data_args.max_train_samples is not None else len(a__    )
								)
								UpperCamelCase__			       =     min(a__				,     len(a__    )    )

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

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

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

				return results


if __name__ == "__main__":
					main()











def       _UpperCamelCase       (a__				:dict    ):






							"""simple docstring"""





							UpperCamelCase__			       =     set()
							# To detect a back edge, keep track of vertices currently in the recursion stack
							UpperCamelCase__			       =     set()
							return any(
							    node not in visited and depth_first_search(a__				,     a__				,     a__				,     a__    )
							    for node in graph    )





def       _UpperCamelCase       (a__				:dict				,     a__				:int				,     a__				:set				,     a__				:set    ):






							"""simple docstring"""





							visited.add(a__    )
							rec_stk.add(a__    )

							for node in graph[vertex]:
														if node not in visited:
																					if depth_first_search(a__				,     a__				,     a__				,     a__    ):
																												return True
														elif node in rec_stk:
																					return True

    # The node needs to be removed from recursion stack before function ends
							rec_stk.remove(a__    )
							return False


if __name__ == "__main__":
					from doctest import testmod

					testmod()




