






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

__A		:       Any  				=		logging.getLogger(__name__)



def 						lowercase    (				__snake_case				: Any=None		,					__snake_case				: Union[str, Any]=None	):
		return field(default_factory=lambda: default		,					metadata=__snake_case	)





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





@dataclass
class 					_UpperCAmelCase       :
					SCREAMING_SNAKE_CASE_		:				Optional[str]							    =   field(
					    default=_A   ,						metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}							)
					SCREAMING_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'"
					    }   ,						)
					SCREAMING_SNAKE_CASE_		:				bool							    =   field(
					    default=_A   ,						metadata={"help": "Overwrite the cached preprocessed datasets or not."}							)
					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   field(
					    default=_A   ,						metadata={"help": "The number of processes to use for the preprocessing."}   ,						)
					SCREAMING_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."
					        )
					    }   ,						)
					SCREAMING_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."
					        )
					    }   ,						)
					SCREAMING_SNAKE_CASE_		:				List[str]							    =   list_field(
					    default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"]   ,						metadata={"help": "A list of characters to remove from the transcripts."}   ,						)





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




					def __call__(				self     :						Optional[int]    ,						A     :						List[Dict[str, Union[List[int], torch.Tensor]]]   )  ->  Dict[str, torch.Tensor]:
							# split inputs and labels since they have to be of different lenghts and need
							# different padding methods
							lowercase_ : List[Any]							       =   [{'''input_values''': feature['''input_values''']} for feature in features]
							lowercase_ : Optional[int]							       =   [{'''input_ids''': feature['''labels''']} for feature in features]

							lowercase_ : Tuple							       =   self.processor.pad(
							    A    ,						padding=self.padding    ,						max_length=self.max_length    ,						pad_to_multiple_of=self.pad_to_multiple_of    ,						return_tensors='''pt'''    ,						)
							lowercase_ : Any							       =   self.processor.pad(
							    labels=A    ,						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
							lowercase_ : Tuple							       =   labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1   )    ,						-1_00   )

							lowercase_ : List[Any]							       =   labels

							return batch





class 					_UpperCAmelCase       ( _A							):




					def   A  (				self     :						Optional[int]    ,						A     :						nn.Module    ,						A     :						Dict[str, Union[torch.Tensor, Any]]   )  ->  torch.Tensor:
							model.train()
							lowercase_ : Dict							       =   self._prepare_inputs(A   )

							if self.use_amp:
									with autocast():
											lowercase_ : Union[str, Any]							       =   self.compute_loss(A    ,						A   )
							else:
									lowercase_ : List[str]							       =   self.compute_loss(A    ,						A   )

							if self.args.n_gpu > 1:
									if model.module.config.ctc_loss_reduction == "mean":
											lowercase_ : Tuple							       =   loss.mean()
									elif model.module.config.ctc_loss_reduction == "sum":
											lowercase_ : Optional[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:
									lowercase_ : Union[str, Any]							       =   loss / self.args.gradient_accumulation_steps

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

							return loss.detach()



def 						lowercase    (				):
		# See all possible arguments in src/transformers/training_args.py
		# or by passing the --help flag to this script.
		# We now keep distinct sets of args, for a cleaner separation of concerns.

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

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

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

		# Get the datasets:
		lowercase_ : Tuple							       =   datasets.load_dataset(
		    '''common_voice'''		,					data_args.dataset_config_name		,					split=data_args.train_split_name	)
		lowercase_ : Tuple							       =   datasets.load_dataset('''common_voice'''		,					data_args.dataset_config_name		,					split='''test'''	)

		# Create and save tokenizer
		lowercase_ : Optional[Any]							       =   F'''[{''.join(data_args.chars_to_ignore	)}]'''

		def remove_special_characters(__snake_case				: Dict	):
				lowercase_ : Optional[int]							       =   re.sub(__snake_case		,					''''''		,					batch['''sentence''']	).lower() + ''' '''
				return batch

		lowercase_ : Optional[Any]							       =   train_dataset.map(__snake_case		,					remove_columns=['''sentence''']	)
		lowercase_ : Union[str, Any]							       =   eval_dataset.map(__snake_case		,					remove_columns=['''sentence''']	)

		def extract_all_chars(__snake_case				: Optional[int]	):
				lowercase_ : str							       =   ''' '''.join(batch['''text''']	)
				lowercase_ : Optional[int]							       =   list(set(__snake_case	)	)
				return {"vocab": [vocab], "all_text": [all_text]}

		lowercase_ : int							       =   train_dataset.map(
		    __snake_case		,					batched=__snake_case		,					batch_size=-1		,					keep_in_memory=__snake_case		,					remove_columns=train_dataset.column_names		,					)
		lowercase_ : Any							       =   train_dataset.map(
		    __snake_case		,					batched=__snake_case		,					batch_size=-1		,					keep_in_memory=__snake_case		,					remove_columns=eval_dataset.column_names		,					)

		lowercase_ : int							       =   list(set(vocab_train['''vocab'''][0]	) | set(vocab_test['''vocab'''][0]	)	)
		lowercase_ : Optional[int]							       =   {v: k for k, v in enumerate(__snake_case	)}
		lowercase_ : List[Any]							       =   vocab_dict[''' ''']
		del vocab_dict[" "]
		lowercase_ : int							       =   len(__snake_case	)
		lowercase_ : Tuple							       =   len(__snake_case	)

		with open('''vocab.json'''		,					'''w'''	) as vocab_file:
				json.dump(__snake_case		,					__snake_case	)

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

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

		lowercase_ : Tuple							       =   torchaudio.transforms.Resample(4_8_0_0_0		,					1_6_0_0_0	)

		# Preprocessing the datasets.
		# We need to read the aduio files as arrays and tokenize the targets.
		def speech_file_to_array_fn(__snake_case				: List[str]	):
				lowercase_       ,					lowercase_ : List[Any]							       =   torchaudio.load(batch['''path''']	)
				lowercase_ : Any							       =   resampler(__snake_case	).squeeze().numpy()
				lowercase_ : Any							       =   1_6_0_0_0
				lowercase_ : Any							       =   batch['''text''']
				return batch

		lowercase_ : List[str]							       =   train_dataset.map(
		    __snake_case		,					remove_columns=train_dataset.column_names		,					num_proc=data_args.preprocessing_num_workers		,					)
		lowercase_ : List[str]							       =   eval_dataset.map(
		    __snake_case		,					remove_columns=eval_dataset.column_names		,					num_proc=data_args.preprocessing_num_workers		,					)

		def prepare_dataset(__snake_case				: 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}.'''

				lowercase_ : str							       =   processor(
				    audio=batch['''speech''']		,					text=batch['''target_text''']		,					sampling_rate=batch['''sampling_rate'''][0]	)
				batch.update(__snake_case	)
				return batch

		lowercase_ : str							       =   train_dataset.map(
		    __snake_case		,					remove_columns=train_dataset.column_names		,					batch_size=training_args.per_device_train_batch_size		,					batched=__snake_case		,					num_proc=data_args.preprocessing_num_workers		,					)
		lowercase_ : Any							       =   eval_dataset.map(
		    __snake_case		,					remove_columns=eval_dataset.column_names		,					batch_size=training_args.per_device_train_batch_size		,					batched=__snake_case		,					num_proc=data_args.preprocessing_num_workers		,					)

		# Metric
		lowercase_ : Any							       =   datasets.load_metric('''wer'''	)

		def compute_metrics(__snake_case				: Tuple	):
				lowercase_ : str							       =   pred.predictions
				lowercase_ : Optional[Any]							       =   np.argmax(__snake_case		,					axis=-1	)

				lowercase_ : int							       =   processor.tokenizer.pad_token_id

				lowercase_ : List[Any]							       =   processor.batch_decode(__snake_case	)
				# we do not want to group tokens when computing the metrics
				lowercase_ : Union[str, Any]							       =   processor.batch_decode(pred.label_ids		,					group_tokens=__snake_case	)

				lowercase_ : List[str]							       =   wer_metric.compute(predictions=__snake_case		,					references=__snake_case	)

				return {"wer": wer}

		if model_args.freeze_feature_extractor:
				model.freeze_feature_extractor()

		# Data collator
		lowercase_ : int							       =   DataCollatorCTCWithPadding(processor=__snake_case		,					padding=__snake_case	)

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

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

				lowercase_ : Tuple							       =   trainer.train(resume_from_checkpoint=__snake_case	)
				trainer.save_model()

				lowercase_ : List[str]							       =   train_result.metrics
				lowercase_ : Optional[int]							       =   (
				    data_args.max_train_samples if data_args.max_train_samples is not None else len(__snake_case	)
				)
				lowercase_ : Union[str, Any]							       =   min(__snake_case		,					len(__snake_case	)	)

				trainer.log_metrics('''train'''		,					__snake_case	)
				trainer.save_metrics('''train'''		,					__snake_case	)
				trainer.save_state()

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

				trainer.log_metrics('''eval'''		,					__snake_case	)
				trainer.save_metrics('''eval'''		,					__snake_case	)

		return results


if __name__ == "__main__":
						main()




"""simple docstring"""






__A			   = [
    (1_0_0_0, "M"),
    (9_0_0, "CM"),
    (5_0_0, "D"),
    (4_0_0, "CD"),
    (1_0_0, "C"),
    (9_0, "XC"),
    (5_0, "L"),
    (4_0, "XL"),
    (1_0, "X"),
    (9, "IX"),
    (5, "V"),
    (4, "IV"),
    (1, "I"),
]



def SCREAMING_SNAKE_CASE__			(   __UpperCAmelCase )  ->  int:
   lowercase__:   Dict					=      {'''I''': 1, '''V''': 5, '''X''': 1_0, '''L''': 5_0, '''C''': 1_0_0, '''D''': 5_0_0, '''M''': 1_0_0_0}
   lowercase__:   List[str]					=      0
   lowercase__:   List[Any]					=      0
   while place < len(__UpperCAmelCase ):
      if (place + 1 < len(__UpperCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]):
         total += vals[roman[place + 1]] - vals[roman[place]]
         place += 2
      else:
         total += vals[roman[place]]
         place += 1
   return total



def SCREAMING_SNAKE_CASE__			(   __UpperCAmelCase )  ->  str:
   lowercase__:   Optional[Any]					=      []
   for arabic, roman in ROMAN:
      ((lowercase__), (lowercase__)):   Tuple					=      divmod(__UpperCAmelCase       ,    __UpperCAmelCase )
      result.append(roman * factor )
      if number == 0:
         break
   return "".join(__UpperCAmelCase )


if __name__ == "__main__":
       import doctest

       doctest.testmod()
