


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


__a      			= logging.getLogger(__name__)
@dataclass
class 				lowerCamelCase							:


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   field(
							    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}			)
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,       )
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}			)
							SCREAMING_SNAKE_CASE              =   field(
							    default=__SCREAMING_SNAKE_CASE					,       metadata={"""help""": """Whether to log verbose messages or not."""}					,       )






def        a__			(							_UpperCamelCase						,      _UpperCamelCase			):





						"""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			)]						,      )
						UpperCAmelCase__												=     logging.WARNING
						if model_args.verbose_logging:
												UpperCAmelCase__												=     logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank			):
												UpperCAmelCase__												=     logging.INFO
						logger.setLevel(_UpperCamelCase			)
@dataclass
class 				lowerCamelCase							:


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




@dataclass
class 				lowerCamelCase							:


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   False
							SCREAMING_SNAKE_CASE              =   None
							SCREAMING_SNAKE_CASE              =   "|"
							SCREAMING_SNAKE_CASE              =   field(default_factory=__SCREAMING_SNAKE_CASE			)
							SCREAMING_SNAKE_CASE              =   field(default_factory=__SCREAMING_SNAKE_CASE			)
							SCREAMING_SNAKE_CASE              =   None






							@classmethod
							def        lowerCAmelCase  (    cls			:  Union[str, Any]		,			lowerCamelCase_			:  str					):
													if name == "librispeech":
																			return cls()
													if name == "timit":
																			return cls(
																			    do_lower_case=lowerCamelCase_		,			translation_table=str.maketrans({'''-''': ''' '''}					)		,			)
													if name == "buckwalter":
																			UpperCAmelCase__												=     {
																			    '''-''': ''' ''',  # 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        lowerCAmelCase  (    self			:  Dict		,			lowerCamelCase_			:  str					):
													# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
													if len(self.translation_table					) > 0:
																			UpperCAmelCase__												=     text.translate(self.translation_table					)
													if len(self.words_to_remove					) == 0:
																			UpperCAmelCase__												=     ''' '''.join(text.split()					)  # clean up whitespaces
													else:
																			UpperCAmelCase__												=     ''' '''.join(w for w in text.split() if w not in self.words_to_remove					)  # and clean up whilespaces
													return text






							def        lowerCAmelCase  (    self			:  List[str]		,			lowerCamelCase_			:  ModelArguments					):
													UpperCAmelCase__												=     WavaVecaFeatureExtractor.from_pretrained(
													    model_args.model_name_or_path		,			cache_dir=model_args.cache_dir					)
													if self.vocab_file:
																			UpperCAmelCase__												=     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__												=     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 				lowerCamelCase							:


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   42
							SCREAMING_SNAKE_CASE              =   True
							SCREAMING_SNAKE_CASE              =   None
							SCREAMING_SNAKE_CASE              =   None
							SCREAMING_SNAKE_CASE              =   None
							SCREAMING_SNAKE_CASE              =   None






							def __call__(    self			:  int		,			lowerCamelCase_			:  List[Dict[str, Union[List[int], torch.Tensor]]]					):
													# 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 				lowerCamelCase							(      __SCREAMING_SNAKE_CASE			):


							"""simple docstring"""






							def        lowerCAmelCase  (    self			:  int		,			lowerCamelCase_			:  nn.Module		,			lowerCamelCase_			:  Dict[str, Union[torch.Tensor, Any]]					):
													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        a__			(							):





						"""simple docstring"""

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

						UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__												=     parser.parse_args_into_dataclasses()
						configure_logger(_UpperCamelCase						,      _UpperCamelCase			)

						UpperCAmelCase__												=     Orthography.from_name(data_args.orthography.lower()			)
						UpperCAmelCase__												=     orthography.create_processor(_UpperCamelCase			)
						UpperCAmelCase__												=     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__												=     datasets.load_dataset(
						    data_args.dataset_name						,      data_args.dataset_config_name						,      split=data_args.train_split_name			)
						UpperCAmelCase__												=     datasets.load_dataset(
						    data_args.dataset_name						,      data_args.dataset_config_name						,      split=data_args.validation_split_name			)

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

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

						UpperCAmelCase__												=     train_dataset.map(_UpperCamelCase						,      remove_columns=[data_args.speech_file_column]			)
						UpperCAmelCase__												=     val_dataset.map(_UpperCamelCase						,      remove_columns=[data_args.speech_file_column]			)

						if data_args.max_duration_in_seconds is not None:

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

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

						logger.warning(F"""Updated {len(_UpperCamelCase			)} 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__												=     None

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

						UpperCAmelCase__												=     train_dataset.map(
						    _UpperCamelCase						,      batch_size=training_args.per_device_train_batch_size						,      batched=_UpperCamelCase						,      num_proc=data_args.preprocessing_num_workers						,      )
						UpperCAmelCase__												=     val_dataset.map(
						    _UpperCamelCase						,      batch_size=training_args.per_device_train_batch_size						,      batched=_UpperCamelCase						,      num_proc=data_args.preprocessing_num_workers						,      )

						UpperCAmelCase__												=     DataCollatorCTCWithPadding(processor=_UpperCamelCase						,      padding=_UpperCamelCase			)

						def compute_metrics(_UpperCamelCase			):
												UpperCAmelCase__												=     pred.predictions
												UpperCAmelCase__												=     np.argmax(_UpperCamelCase						,      axis=-1			)

												UpperCAmelCase__												=     processor.tokenizer.pad_token_id

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

												UpperCAmelCase__												=     wer_metric.compute(predictions=_UpperCamelCase						,      references=_UpperCamelCase			)

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						UpperCAmelCase__												=     CTCTrainer(
						    model=_UpperCamelCase						,      data_collator=_UpperCamelCase						,      args=_UpperCamelCase						,      compute_metrics=_UpperCamelCase						,      train_dataset=_UpperCamelCase						,      eval_dataset=_UpperCamelCase						,      tokenizer=processor.feature_extractor						,      )

						trainer.train()


if __name__ == "__main__":
						main()



"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available


__a      			= {}

try:
						if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__a      			= ["BarthezTokenizer"]

try:
						if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__a      			= ["BarthezTokenizerFast"]


if TYPE_CHECKING:
						try:
												if not is_sentencepiece_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_barthez import BarthezTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_barthez_fast import BarthezTokenizerFast

else:
						import sys

						__a      			= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)