
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"):
				lowercase__				:				Optional[int]						=      True
				from torch.cuda.amp import autocast


lowercase__				:				List[Any]						=      logging.getLogger(__name__)






@dataclass
class 							SCREAMING_SNAKE_CASE__     :

							"""simple docstring"""






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





def 						A_			(				snake_case				: ModelArguments			,   snake_case				: TrainingArguments			)   ->     Dict:



						'''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(snake_case			)






@dataclass
class 							SCREAMING_SNAKE_CASE__     :

							"""simple docstring"""






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






@dataclass
class 							SCREAMING_SNAKE_CASE__     :

							"""simple docstring"""






							_snake_case  		=	False
							_snake_case  		=	None
							_snake_case  		=	"|"
							_snake_case  		=	field(default_factory=SCREAMING_SNAKE_CASE_     )
							_snake_case  		=	field(default_factory=SCREAMING_SNAKE_CASE_     )
							_snake_case  		=	None



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_      )-> Optional[Any]:





													'''simple docstring'''






													if name == "librispeech":
																			return cls()
													if name == "timit":
																			return cls(
																			    do_lower_case=SCREAMING_SNAKE_CASE_  ,						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(SCREAMING_SNAKE_CASE_      ).parent.joinpath('''vocab/buckwalter.json'''      )  ,						word_delimiter_token='''/'''  ,						translation_table=str.maketrans(SCREAMING_SNAKE_CASE_      )  ,						words_to_remove={'''sil'''}  ,						untransliterator=arabic.buckwalter.untransliterate  ,						)
													raise ValueError(F"Unsupported orthography: '{name}'."      )



							def      A__		(	self  ,						SCREAMING_SNAKE_CASE_      )-> str:





													'''simple docstring'''






													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      A__		(	self  ,						SCREAMING_SNAKE_CASE_      )-> WavaVecaProcessor:





													'''simple docstring'''






													__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(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )






@dataclass
class 							SCREAMING_SNAKE_CASE__     :

							"""simple docstring"""






							_snake_case  		=	42
							_snake_case  		=	True
							_snake_case  		=	None
							_snake_case  		=	None
							_snake_case  		=	None
							_snake_case  		=	None



							def __call__(	self  ,						SCREAMING_SNAKE_CASE_      )-> Dict[str, torch.Tensor]:





													'''simple docstring'''






													__UpperCamelCase  	=      [{'''input_values''': feature['''input_values''']} for feature in features]
													__UpperCamelCase  	=      [{'''input_ids''': feature['''labels''']} for feature in features]

													__UpperCamelCase  	=      self.processor.pad(
													    SCREAMING_SNAKE_CASE_  ,						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=SCREAMING_SNAKE_CASE_  ,						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__     (				SCREAMING_SNAKE_CASE_     ):

							"""simple docstring"""






							def      A__		(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )-> torch.Tensor:





													'''simple docstring'''






													model.train()
													__UpperCamelCase  	=      self._prepare_inputs(SCREAMING_SNAKE_CASE_      )

													if self.use_amp:
																			with autocast():
																									__UpperCamelCase  	=      self.compute_loss(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )
													else:
																			__UpperCamelCase  	=      self.compute_loss(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )

													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(SCREAMING_SNAKE_CASE_      ).backward()
													elif self.use_apex:
																			with amp.scale_loss(SCREAMING_SNAKE_CASE_  ,						self.optimizer      ) as scaled_loss:
																									scaled_loss.backward()
													elif self.deepspeed:
																			self.deepspeed.backward(SCREAMING_SNAKE_CASE_      )
													else:
																			loss.backward()

													return loss.detach()





def 						A_			(				)   ->     Union[str, Any]:



						'''simple docstring'''

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

						__UpperCamelCase	,				__UpperCamelCase	,				__UpperCamelCase  	=      parser.parse_args_into_dataclasses()
						configure_logger(snake_case			,   snake_case			)

						__UpperCamelCase  	=      Orthography.from_name(data_args.orthography.lower()			)
						__UpperCamelCase  	=      orthography.create_processor(snake_case			)
						__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(snake_case			) == 1			)
						__UpperCamelCase  	=      re.compile(  # remove characters not in vocabulary
						    rf"[^\s{re.escape(snake_case			)}]"			,   flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0			,   )
						__UpperCamelCase  	=      []

						def prepare_example(snake_case				: Union[str, Any]			):  # TODO(elgeish) make use of multiprocessing?
												__UpperCamelCase	,				__UpperCamelCase  	=      librosa.load(example[data_args.speech_file_column]			,   sr=snake_case			)
												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(''''''			,   snake_case			)
												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(snake_case			,   remove_columns=[data_args.speech_file_column]			)
						__UpperCamelCase  	=      val_dataset.map(snake_case			,   remove_columns=[data_args.speech_file_column]			)

						if data_args.max_duration_in_seconds is not None:

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

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

						logger.warning(f"Updated {len(snake_case			)} 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(snake_case				: Union[str, Any]			):
												# 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(snake_case			)
												return batch

						__UpperCamelCase  	=      train_dataset.map(
						    snake_case			,   batch_size=training_args.per_device_train_batch_size			,   batched=snake_case			,   num_proc=data_args.preprocessing_num_workers			,   )
						__UpperCamelCase  	=      val_dataset.map(
						    snake_case			,   batch_size=training_args.per_device_train_batch_size			,   batched=snake_case			,   num_proc=data_args.preprocessing_num_workers			,   )

						__UpperCamelCase  	=      DataCollatorCTCWithPadding(processor=snake_case			,   padding=snake_case			)

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

												__UpperCamelCase  	=      processor.tokenizer.pad_token_id

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

												__UpperCamelCase  	=      wer_metric.compute(predictions=snake_case			,   references=snake_case			)

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						__UpperCamelCase  	=      CTCTrainer(
						    model=snake_case			,   data_collator=snake_case			,   args=snake_case			,   compute_metrics=snake_case			,   train_dataset=snake_case			,   eval_dataset=snake_case			,   tokenizer=processor.feature_extractor			,   )

						trainer.train()


if __name__ == "__main__":
				main()









"""simple docstring"""
# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

from .config_args import default_config_file, load_config_from_file
from .config_utils import SubcommandHelpFormatter


__a           =							"Update an existing config file with the latest defaults while maintaining the old configuration."
def   A_    (     _lowercase      ):







						'''simple docstring'''


						snake_case_					:int		=     args.config_file
						if config_file is None and Path(_lowercase      ).exists():
												snake_case_					:str		=     default_config_file
						elif not Path(_lowercase      ).exists():
												raise ValueError(f"""The passed config file located at {config_file} doesn't exist."""      )
						snake_case_					:str		=     load_config_from_file(_lowercase      )

						if config_file.endswith(""".json"""      ):
												config.to_json_file(_lowercase      )
						else:
												config.to_yaml_file(_lowercase      )
						return config_file
def   A_    (     _lowercase,   _lowercase      ):







						'''simple docstring'''


						snake_case_					:Any		=     parser.add_parser("""update""",   parents=_lowercase,   help=_lowercase,   formatter_class=_lowercase      )
						parser.add_argument(
						    """--config_file""",   default=_lowercase,   help=(
						        """The path to the config file to update. Will default to a file named default_config.yaml in the cache """
						        """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
						        """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
						        """with 'huggingface'."""
						    ),   )

						parser.set_defaults(func=_lowercase      )
						return parser

def   A_    (     _lowercase      ):







						'''simple docstring'''


						snake_case_					:str		=     update_config(_lowercase      )
						print(f"""Sucessfully updated the configuration file at {config_file}."""      )
