


import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
	from apex import amp

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


lowerCAmelCase					 =	logging.getLogger(__name__)





@dataclass
class    A					:
							UpperCamelCase_     :							str =field(
							    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}				)
							UpperCamelCase_     :							Optional[str] =field(
							    default=A_      ,       metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}      ,       )
							UpperCamelCase_     :							Optional[bool] =field(
							    default=A_      ,       metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}				)
							UpperCamelCase_     :							Optional[bool] =field(
							    default=A_      ,       metadata={'''help''': '''Whether to log verbose messages or not.'''}      ,       )







def  _lowerCamelCase(			lowercase__     ,				lowercase__			)		->			List[Any]:

		'''simple docstring'''







		logging.basicConfig(
		    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,				datefmt='%m/%d/%Y %H:%M:%S'     ,				handlers=[logging.StreamHandler(sys.stdout			)]     ,				)
		__lowercase=    logging.WARNING
		if model_args.verbose_logging:
				__lowercase=    logging.DEBUG
		elif trainer_utils.is_main_process(training_args.local_rank			):
				__lowercase=    logging.INFO
		logger.setLevel(lowercase__			)





@dataclass
class    A					:
							UpperCamelCase_     :							str =field(
							    default=A_      ,       metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''}				)
							UpperCamelCase_     :							Optional[str] =field(
							    default=A_      ,       metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}				)
							UpperCamelCase_     :							Optional[str] =field(
							    default='''train'''      ,       metadata={
							        '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
							    }      ,       )
							UpperCamelCase_     :							Optional[str] =field(
							    default='''validation'''      ,       metadata={
							        '''help''': (
							            '''The name of the validation data set split to use (via the datasets library). Defaults to \'validation\''''
							        )
							    }      ,       )
							UpperCamelCase_     :							Optional[str] =field(
							    default='''text'''      ,       metadata={'''help''': '''Column in the dataset that contains label (target text). Defaults to \'text\''''}      ,       )
							UpperCamelCase_     :							Optional[str] =field(
							    default='''file'''      ,       metadata={'''help''': '''Column in the dataset that contains speech file path. Defaults to \'file\''''}      ,       )
							UpperCamelCase_     :							Optional[bool] =field(
							    default=A_      ,       metadata={'''help''': '''Resample loaded audio to target feature extractor\'s sampling rate or not.'''}      ,       )
							UpperCamelCase_     :							Optional[float] =field(
							    default=A_      ,       metadata={'''help''': '''Filters out examples longer than specified. Defaults to no filtering.'''}      ,       )
							UpperCamelCase_     :							Optional[str] =field(
							    default='''librispeech'''      ,       metadata={
							        '''help''': (
							            '''Orthography used for normalization and tokenization: \'librispeech\' (default), \'timit\', or'''
							            ''' \'buckwalter\'.'''
							        )
							    }      ,       )
							UpperCamelCase_     :							bool =field(
							    default=A_      ,       metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}				)
							UpperCamelCase_     :							Optional[int] =field(
							    default=A_      ,       metadata={'''help''': '''The number of processes to use for the preprocessing.'''}      ,       )





@dataclass
class    A					:
							UpperCamelCase_     :							bool =False
							UpperCamelCase_     :							Optional[str] =None
							UpperCamelCase_     :							Optional[str] ="|"
							UpperCamelCase_     :							Optional[Dict[str, str]] =field(default_factory=A_				)
							UpperCamelCase_     :							Optional[Set[str]] =field(default_factory=A_				)
							UpperCamelCase_     :							Optional[Callable[[str], str]] =None


							@classmethod
							def     _A (cls   ,       lowerCAmelCase      ):
									if name == "librispeech":
											return cls()
									if name == "timit":
											return cls(
											    do_lower_case=lowerCAmelCase   ,       translation_table=str.maketrans({'-': ' '}      )   ,       )
									if name == "buckwalter":
											__lowercase=    {
											    '-': ' ',  # sometimes used to represent pauses
											    '^': 'v',  # fixing "tha" in arabic_speech_corpus dataset
											}
											return cls(
											    vocab_file=pathlib.Path(lowerCAmelCase      ).parent.joinpath('vocab/buckwalter.json'      )   ,       word_delimiter_token='/'   ,       translation_table=str.maketrans(lowerCAmelCase      )   ,       words_to_remove={'sil'}   ,       untransliterator=arabic.buckwalter.untransliterate   ,       )
									raise ValueError(f'Unsupported orthography: \'{name}\'.'      )


							def     _A (self   ,       lowerCAmelCase      ):
									# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
									if len(self.translation_table      ) > 0:
											__lowercase=    text.translate(self.translation_table      )
									if len(self.words_to_remove      ) == 0:
											__lowercase=    ' '.join(text.split()      )  # clean up whitespaces
									else:
											__lowercase=    ' '.join(w for w in text.split() if w not in self.words_to_remove      )  # and clean up whilespaces
									return text







							def     _A (self   ,       lowerCAmelCase      ):
									__lowercase=    WavaVecaFeatureExtractor.from_pretrained(
									    model_args.model_name_or_path   ,       cache_dir=model_args.cache_dir      )
									if self.vocab_file:
											__lowercase=    WavaVecaCTCTokenizer(
											    self.vocab_file   ,       cache_dir=model_args.cache_dir   ,       do_lower_case=self.do_lower_case   ,       word_delimiter_token=self.word_delimiter_token   ,       )
									else:
											__lowercase=    WavaVecaCTCTokenizer.from_pretrained(
											    model_args.model_name_or_path   ,       cache_dir=model_args.cache_dir   ,       do_lower_case=self.do_lower_case   ,       word_delimiter_token=self.word_delimiter_token   ,       )
									return WavaVecaProcessor(lowerCAmelCase   ,       lowerCAmelCase      )





@dataclass
class    A					:
							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   ,       lowerCAmelCase      ):
									# split inputs and labels since they have to be of different lenghts and need
									# different padding methods
									__lowercase=    [{'input_values': feature['input_values']} for feature in features]
									__lowercase=    [{'input_ids': feature['labels']} for feature in features]

									__lowercase=    self.processor.pad(
									    lowerCAmelCase   ,       padding=self.padding   ,       max_length=self.max_length   ,       pad_to_multiple_of=self.pad_to_multiple_of   ,       return_tensors='pt'   ,       )
									__lowercase=    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
									__lowercase=    labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1      )   ,       -1_0_0      )

									__lowercase=    labels

									return batch





class    A					(     A_				):


							def     _A (self   ,       lowerCAmelCase   ,       lowerCAmelCase      ):
									model.train()
									__lowercase=    self._prepare_inputs(lowerCAmelCase      )

									if self.use_amp:
											with autocast():
													__lowercase=    self.compute_loss(lowerCAmelCase   ,       lowerCAmelCase      )
									else:
											__lowercase=    self.compute_loss(lowerCAmelCase   ,       lowerCAmelCase      )

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

		'''simple docstring'''







		__lowercase=    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)

		__lowercase,							__lowercase,							__lowercase=    parser.parse_args_into_dataclasses()
		configure_logger(lowercase__     ,				lowercase__			)

		__lowercase=    Orthography.from_name(data_args.orthography.lower()			)
		__lowercase=    orthography.create_processor(lowercase__			)
		__lowercase=    WavaVecaForCTC.from_pretrained(
		    model_args.model_name_or_path     ,				cache_dir=model_args.cache_dir     ,				gradient_checkpointing=training_args.gradient_checkpointing     ,				vocab_size=len(processor.tokenizer			)     ,				)

		__lowercase=    datasets.load_dataset(
		    data_args.dataset_name     ,				data_args.dataset_config_name     ,				split=data_args.train_split_name			)
		__lowercase=    datasets.load_dataset(
		    data_args.dataset_name     ,				data_args.dataset_config_name     ,				split=data_args.validation_split_name			)

		__lowercase=    datasets.load_metric('wer'			)
		__lowercase=    processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
		__lowercase=    ''.join(t for t in processor.tokenizer.get_vocab().keys() if len(lowercase__			) == 1			)
		__lowercase=    re.compile(  # remove characters not in vocabulary
		    RF'[^\s{re.escape(lowercase__			)}]'     ,				flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0     ,				)
		__lowercase=    []

		def prepare_example(lowercase__			):  # TODO(elgeish) make use of multiprocessing?
				__lowercase,							__lowercase=    librosa.load(example[data_args.speech_file_column]     ,				sr=lowercase__			)
				if data_args.max_duration_in_seconds is not None:
						__lowercase=    len(example['speech']			) / example['sampling_rate']
				# Normalize and clean up text; order matters!
				__lowercase=    orthography.preprocess_for_training(example[data_args.target_text_column]			)
				__lowercase=    vocabulary_text_cleaner.sub(''     ,				lowercase__			)
				if updated_text != example[data_args.target_text_column]:
						text_updates.append((example[data_args.target_text_column], updated_text)			)
						__lowercase=    updated_text
				return example

		__lowercase=    train_dataset.map(lowercase__     ,				remove_columns=[data_args.speech_file_column]			)
		__lowercase=    val_dataset.map(lowercase__     ,				remove_columns=[data_args.speech_file_column]			)

		if data_args.max_duration_in_seconds is not None:

				def filter_by_max_duration(lowercase__			):
						return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

				__lowercase=    len(lowercase__			)
				__lowercase=    len(lowercase__			)
				__lowercase=    train_dataset.filter(lowercase__     ,				remove_columns=['duration_in_seconds']			)
				__lowercase=    val_dataset.filter(lowercase__     ,				remove_columns=['duration_in_seconds']			)
				if len(lowercase__			) > old_train_size:
						logger.warning(
						    F'Filtered out {len(lowercase__			) - old_train_size} train example(s) longer than'
						    F' {data_args.max_duration_in_seconds} second(s).'			)
				if len(lowercase__			) > old_val_size:
						logger.warning(
						    F'Filtered out {len(lowercase__			) - old_val_size} validation example(s) longer than'
						    F' {data_args.max_duration_in_seconds} second(s).'			)
		logger.info(F'Split sizes: {len(lowercase__			)} train and {len(lowercase__			)} validation.'			)

		logger.warning(F'Updated {len(lowercase__			)} transcript(s) using \'{data_args.orthography}\' orthography rules.'			)
		if logger.isEnabledFor(logging.DEBUG			):
				for original_text, updated_text in text_updates:
						logger.debug(F'Updated text: "{original_text}" -> "{updated_text}"'			)
		__lowercase=    None

		def prepare_dataset(lowercase__			):
				# 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=    processor(
				    audio=batch['speech']     ,				text=batch[data_args.target_text_column]     ,				sampling_rate=batch['sampling_rate'][0]			)
				batch.update(lowercase__			)
				return batch

		__lowercase=    train_dataset.map(
		    lowercase__     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=lowercase__     ,				num_proc=data_args.preprocessing_num_workers     ,				)
		__lowercase=    val_dataset.map(
		    lowercase__     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=lowercase__     ,				num_proc=data_args.preprocessing_num_workers     ,				)

		__lowercase=    DataCollatorCTCWithPadding(processor=lowercase__     ,				padding=lowercase__			)

		def compute_metrics(lowercase__			):
				__lowercase=    pred.predictions
				__lowercase=    np.argmax(lowercase__     ,				axis=-1			)

				__lowercase=    processor.tokenizer.pad_token_id

				__lowercase=    processor.batch_decode(lowercase__			)
				# we do not want to group tokens when computing the metrics
				__lowercase=    processor.batch_decode(pred.label_ids     ,				group_tokens=lowercase__			)
				if logger.isEnabledFor(logging.DEBUG			):
						for reference, predicted in zip(lowercase__     ,				lowercase__			):
								logger.debug(F'reference: "{reference}"'			)
								logger.debug(F'predicted: "{predicted}"'			)
								if orthography.untransliterator is not None:
										logger.debug(F'reference (untransliterated): "{orthography.untransliterator(lowercase__			)}"'			)
										logger.debug(F'predicted (untransliterated): "{orthography.untransliterator(lowercase__			)}"'			)

				__lowercase=    wer_metric.compute(predictions=lowercase__     ,				references=lowercase__			)

				return {"wer": wer}

		if model_args.freeze_feature_extractor:
				model.freeze_feature_extractor()

		__lowercase=    CTCTrainer(
		    model=lowercase__     ,				data_collator=lowercase__     ,				args=lowercase__     ,				compute_metrics=lowercase__     ,				train_dataset=lowercase__     ,				eval_dataset=lowercase__     ,				tokenizer=processor.feature_extractor     ,				)

		trainer.train()


if __name__ == "__main__":
	main()










def  _lowerCamelCase(			lowercase__			)		->			str:

		'''simple docstring'''







		return " ".join([word[::-1] for word in input_str.split()]			)


if __name__ == "__main__":
	import doctest

	doctest.testmod()






