





"""simple docstring"""




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


UpperCamelCase_           =logging.getLogger(__name__)




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





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




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




@dataclass
class  _a						:
				UpperCamelCase								=    False
				UpperCamelCase								=    None
				UpperCamelCase								=    "|"
				UpperCamelCase								=    field(default_factory=_lowerCAmelCase				)
				UpperCamelCase								=    field(default_factory=_lowerCAmelCase				)
				UpperCamelCase								=    None






				@classmethod
				def 				snake_case	( cls		:    Union[str, Any], lowerCAmelCase__		:    str							)	->      str:




										'''simple docstring'''



										if name == "librispeech":
																return cls()
										if name == "timit":
																return cls(
																    do_lower_case=lowerCAmelCase__, translation_table=str.maketrans({'''-''': ''' '''}							), )
										if name == "buckwalter":
																_UpperCamelCase			:					List[Any]     =    {
																    '''-''': ''' ''',  # 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 				snake_case	( self		:    List[str], lowerCAmelCase__		:    str							)	->      str:




										'''simple docstring'''



										if len(self.translation_table							) > 0:
																_UpperCamelCase			:					Tuple     =    text.translate(self.translation_table							)
										if len(self.words_to_remove							) == 0:
																_UpperCamelCase			:					Optional[int]     =    ''' '''.join(text.split()							)  # clean up whitespaces
										else:
																_UpperCamelCase			:					List[Any]     =    ''' '''.join(w for w in text.split() if w not in self.words_to_remove							)  # and clean up whilespaces
										return text






				def 				snake_case	( self		:    str, lowerCAmelCase__		:    ModelArguments							)	->      WavaVecaProcessor:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    WavaVecaFeatureExtractor.from_pretrained(
										    model_args.model_name_or_path, cache_dir=model_args.cache_dir							)
										if self.vocab_file:
																_UpperCamelCase			:					List[Any]     =    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:
																_UpperCamelCase			:					Optional[int]     =    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								=    42
				UpperCamelCase								=    True
				UpperCamelCase								=    None
				UpperCamelCase								=    None
				UpperCamelCase								=    None
				UpperCamelCase								=    None






				def __call__( self		:    str, lowerCAmelCase__		:    List[Dict[str, Union[List[int], torch.Tensor]]]							)	->      Dict[str, torch.Tensor]:




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    [{'''input_values''': feature['''input_values''']} for feature in features]
										_UpperCamelCase			:					str     =    [{'''input_ids''': feature['''labels''']} for feature in features]

										_UpperCamelCase			:					Optional[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''', )
										_UpperCamelCase			:					List[Any]     =    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			:					Optional[int]     =    labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1							), -1_0_0							)

										_UpperCamelCase			:					Dict     =    labels

										return batch




class  _a						(      _lowerCAmelCase				):






				def 				snake_case	( self		:    List[str], lowerCAmelCase__		:    nn.Module, lowerCAmelCase__		:    Dict[str, Union[torch.Tensor, Any]]							)	->      torch.Tensor:




										'''simple docstring'''



										model.train()
										_UpperCamelCase			:					Union[str, Any]     =    self._prepare_inputs(lowerCAmelCase__							)

										if self.use_amp:
																with autocast():
																						_UpperCamelCase			:					Any     =    self.compute_loss(lowerCAmelCase__, lowerCAmelCase__							)
										else:
																_UpperCamelCase			:					List[str]     =    self.compute_loss(lowerCAmelCase__, lowerCAmelCase__							)

										if self.args.n_gpu > 1:
																if model.module.config.ctc_loss_reduction == "mean":
																						_UpperCamelCase			:					int     =    loss.mean()
																elif model.module.config.ctc_loss_reduction == "sum":
																						_UpperCamelCase			:					Optional[Any]     =    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			:					Dict     =    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        a_				(							):
						# 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.

						_UpperCamelCase			:					List[str]     =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )

						_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase			:					List[str]     =    parser.parse_args_into_dataclasses()
						configure_logger(_lowercase       ,						_lowercase   )

						_UpperCamelCase			:					Optional[int]     =    Orthography.from_name(data_args.orthography.lower()   )
						_UpperCamelCase			:					Tuple     =    orthography.create_processor(_lowercase   )
						_UpperCamelCase			:					Any     =    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   )       ,						)

						_UpperCamelCase			:					Optional[int]     =    datasets.load_dataset(
						    data_args.dataset_name       ,						data_args.dataset_config_name       ,						split=data_args.train_split_name   )
						_UpperCamelCase			:					str     =    datasets.load_dataset(
						    data_args.dataset_name       ,						data_args.dataset_config_name       ,						split=data_args.validation_split_name   )

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

						def prepare_example(_lowercase   ):  # TODO(elgeish) make use of multiprocessing?
												_UpperCamelCase   ,							_UpperCamelCase			:					Optional[int]     =    librosa.load(example[data_args.speech_file_column]       ,						sr=_lowercase   )
												if data_args.max_duration_in_seconds is not None:
																		_UpperCamelCase			:					List[Any]     =    len(example['''speech''']   ) / example['''sampling_rate''']
												# Normalize and clean up text; order matters!
												_UpperCamelCase			:					List[str]     =    orthography.preprocess_for_training(example[data_args.target_text_column]   )
												_UpperCamelCase			:					Any     =    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)   )
																		_UpperCamelCase			:					Union[str, Any]     =    updated_text
												return example

						_UpperCamelCase			:					Dict     =    train_dataset.map(_lowercase       ,						remove_columns=[data_args.speech_file_column]   )
						_UpperCamelCase			:					int     =    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

												_UpperCamelCase			:					Union[str, Any]     =    len(_lowercase   )
												_UpperCamelCase			:					List[Any]     =    len(_lowercase   )
												_UpperCamelCase			:					List[str]     =    train_dataset.filter(_lowercase       ,						remove_columns=['''duration_in_seconds''']   )
												_UpperCamelCase			:					Dict     =    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}\""""   )
						_UpperCamelCase			:					str     =    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}."""

												_UpperCamelCase			:					Optional[Any]     =    processor(
												    audio=batch['''speech''']       ,						text=batch[data_args.target_text_column]       ,						sampling_rate=batch['''sampling_rate'''][0]   )
												batch.update(_lowercase   )
												return batch

						_UpperCamelCase			:					Union[str, Any]     =    train_dataset.map(
						    _lowercase       ,						batch_size=training_args.per_device_train_batch_size       ,						batched=_lowercase       ,						num_proc=data_args.preprocessing_num_workers       ,						)
						_UpperCamelCase			:					Tuple     =    val_dataset.map(
						    _lowercase       ,						batch_size=training_args.per_device_train_batch_size       ,						batched=_lowercase       ,						num_proc=data_args.preprocessing_num_workers       ,						)

						_UpperCamelCase			:					int     =    DataCollatorCTCWithPadding(processor=_lowercase       ,						padding=_lowercase   )

						def compute_metrics(_lowercase   ):
												_UpperCamelCase			:					Any     =    pred.predictions
												_UpperCamelCase			:					List[Any]     =    np.argmax(_lowercase       ,						axis=-1   )

												_UpperCamelCase			:					List[str]     =    processor.tokenizer.pad_token_id

												_UpperCamelCase			:					Tuple     =    processor.batch_decode(_lowercase   )
												# we do not want to group tokens when computing the metrics
												_UpperCamelCase			:					str     =    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   )}\""""   )

												_UpperCamelCase			:					Union[str, Any]     =    wer_metric.compute(predictions=_lowercase       ,						references=_lowercase   )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						_UpperCamelCase			:					str     =    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()










"""simple docstring"""




from __future__ import annotations





def        a_				(							_lowercase   ):
						assert (
						    isinstance(_lowercase       ,						_lowercase   ) and mask > 0
						), F"""mask needs to be positive integer, your input {mask}"""
						_UpperCamelCase			:					Union[str, Any]     =    []
						_UpperCamelCase			:					str     =    mask

						while submask:
												all_submasks.append(_lowercase   )
												_UpperCamelCase			:					int     =    (submask - 1) & mask

						return all_submasks


if __name__ == "__main__":
						import doctest

						doctest.testmod()



