


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


_UpperCAmelCase     :					Dict       =logging.getLogger(__name__)







@dataclass
class 			snake_case__:







						'''simple docstring'''




						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=UpperCAmelCase__,  metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""},  )
						SCREAMING_SNAKE_CASE__ :					Optional[bool]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}							)
						SCREAMING_SNAKE_CASE__ :					Optional[bool]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """Whether to log verbose messages or not."""},  )






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







@dataclass
class 			snake_case__:







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__ :					str   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}							)
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}							)
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							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__ :					Optional[str]   =							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__ :					Optional[str]   =							field(
						    default="""text""",  metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""},  )
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							field(
						    default="""file""",  metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""},  )
						SCREAMING_SNAKE_CASE__ :					Optional[bool]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""},  )
						SCREAMING_SNAKE_CASE__ :					Optional[float]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""},  )
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							field(
						    default="""librispeech""",  metadata={
						        """help""": (
						            """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
						            """ 'buckwalter'."""
						        )
						    },  )
						SCREAMING_SNAKE_CASE__ :					bool   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}							)
						SCREAMING_SNAKE_CASE__ :					Optional[int]   =							field(
						    default=UpperCAmelCase__,  metadata={"""help""": """The number of processes to use for the preprocessing."""},  )







@dataclass
class 			snake_case__:







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__ :					bool   =							False
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							None
						SCREAMING_SNAKE_CASE__ :					Optional[str]   =							"|"
						SCREAMING_SNAKE_CASE__ :					Optional[Dict[str, str]]   =							field(default_factory=UpperCAmelCase__							)
						SCREAMING_SNAKE_CASE__ :					Optional[Set[str]]   =							field(default_factory=UpperCAmelCase__							)
						SCREAMING_SNAKE_CASE__ :					Optional[Callable[[str], str]]   =							None




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




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




						def   lowercase_	(			self				,  __lowercase							)   ->      WavaVecaProcessor:
										lowerCAmelCase_	: Tuple      			=			WavaVecaFeatureExtractor.from_pretrained(
										    model_args.model_name_or_path				,  cache_dir=model_args.cache_dir							)
										if self.vocab_file:
														lowerCAmelCase_	: Tuple      			=			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:
														lowerCAmelCase_	: str      			=			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(__lowercase				,  __lowercase							)







@dataclass
class 			snake_case__:







						'''simple docstring'''




						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				,  __lowercase							)   ->      Dict[str, torch.Tensor]:
										# split inputs and labels since they have to be of different lenghts and need
										# different padding methods
										lowerCAmelCase_	: int      			=			[{'''input_values''': feature['''input_values''']} for feature in features]
										lowerCAmelCase_	: List[str]      			=			[{'''input_ids''': feature['''labels''']} for feature in features]

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

										lowerCAmelCase_	: Dict      			=			labels

										return batch







class 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						def   lowercase_	(			self				,  __lowercase				,  __lowercase							)   ->      torch.Tensor:
										model.train()
										lowerCAmelCase_	: List[Any]      			=			self._prepare_inputs(__lowercase							)

										if self.use_amp:
														with autocast():
																		lowerCAmelCase_	: int      			=			self.compute_loss(__lowercase				,  __lowercase							)
										else:
														lowerCAmelCase_	: str      			=			self.compute_loss(__lowercase				,  __lowercase							)

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

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

										return loss.detach()






def      lowerCAmelCase	(						)->	Optional[Any]:
				# 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.

				lowerCAmelCase_	: str      			=			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

				lowerCAmelCase_			,					lowerCAmelCase_			,					lowerCAmelCase_	: Optional[Any]      			=			parser.parse_args_into_dataclasses()
				configure_logger(lowerCAmelCase_	,				lowerCAmelCase_	)

				lowerCAmelCase_	: int      			=			Orthography.from_name(data_args.orthography.lower()	)
				lowerCAmelCase_	: Tuple      			=			orthography.create_processor(lowerCAmelCase_	)
				lowerCAmelCase_	: List[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	)	,				)

				lowerCAmelCase_	: List[Any]      			=			datasets.load_dataset(
				    data_args.dataset_name	,				data_args.dataset_config_name	,				split=data_args.train_split_name	)
				lowerCAmelCase_	: Union[str, Any]      			=			datasets.load_dataset(
				    data_args.dataset_name	,				data_args.dataset_config_name	,				split=data_args.validation_split_name	)

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

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

				lowerCAmelCase_	: str      			=			train_dataset.map(lowerCAmelCase_	,				remove_columns=[data_args.speech_file_column]	)
				lowerCAmelCase_	: int      			=			val_dataset.map(lowerCAmelCase_	,				remove_columns=[data_args.speech_file_column]	)

				if data_args.max_duration_in_seconds is not None:

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

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

				logger.warning(f"""Updated {len(lowerCAmelCase_	)} 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}\""""	)
				lowerCAmelCase_	: List[str]      			=			None

				def prepare_dataset(lowerCAmelCase_	):
								# 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}."""

								lowerCAmelCase_	: int      			=			processor(
								    audio=batch['''speech''']	,				text=batch[data_args.target_text_column]	,				sampling_rate=batch['''sampling_rate'''][0]	)
								batch.update(lowerCAmelCase_	)
								return batch

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

				lowerCAmelCase_	: List[Any]      			=			DataCollatorCTCWithPadding(processor=lowerCAmelCase_	,				padding=lowerCAmelCase_	)

				def compute_metrics(lowerCAmelCase_	):
								lowerCAmelCase_	: Union[str, Any]      			=			pred.predictions
								lowerCAmelCase_	: Dict      			=			np.argmax(lowerCAmelCase_	,				axis=-1	)

								lowerCAmelCase_	: Tuple      			=			processor.tokenizer.pad_token_id

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

								lowerCAmelCase_	: Dict      			=			wer_metric.compute(predictions=lowerCAmelCase_	,				references=lowerCAmelCase_	)

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				lowerCAmelCase_	: Tuple      			=			CTCTrainer(
				    model=lowerCAmelCase_	,				data_collator=lowerCAmelCase_	,				args=lowerCAmelCase_	,				compute_metrics=lowerCAmelCase_	,				train_dataset=lowerCAmelCase_	,				eval_dataset=lowerCAmelCase_	,				tokenizer=processor.feature_extractor	,				)

				trainer.train()


if __name__ == "__main__":
						main()



import argparse
import logging
import sys
import time

import tensorflow as tf
from datasets import load_dataset

from transformers import AutoTokenizer, TFAutoModelForSequenceClassification


if __name__ == "__main__":
						_UpperCAmelCase     :					Optional[int]       =argparse.ArgumentParser()

						# Hyperparameters sent by the client are passed as command-line arguments to the script.
						parser.add_argument("""--epochs""", type=int, default=1)
						parser.add_argument("""--per_device_train_batch_size""", type=int, default=16)
						parser.add_argument("""--per_device_eval_batch_size""", type=int, default=8)
						parser.add_argument("""--model_name_or_path""", type=str)
						parser.add_argument("""--learning_rate""", type=str, default=5E-5)
						parser.add_argument("""--do_train""", type=bool, default=True)
						parser.add_argument("""--do_eval""", type=bool, default=True)
						parser.add_argument("""--output_dir""", type=str)

						_UpperCAmelCase       ,   _UpperCAmelCase     :					List[str]       =parser.parse_known_args()

						# overwrite batch size until we have tf_glue.py
						_UpperCAmelCase     :					Optional[Any]       =16
						_UpperCAmelCase     :					List[str]       =16

						# Set up logging
						_UpperCAmelCase     :					Optional[Any]       =logging.getLogger(__name__)

						logging.basicConfig(
						    level=logging.getLevelName("""INFO"""),
						    handlers=[logging.StreamHandler(sys.stdout)],
						    format="""%(asctime)s - %(name)s - %(levelname)s - %(message)s""",
						)

						# Load model and tokenizer
						_UpperCAmelCase     :					List[str]       =TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
						_UpperCAmelCase     :					Any       =AutoTokenizer.from_pretrained(args.model_name_or_path)

						# Load dataset
						_UpperCAmelCase       ,   _UpperCAmelCase     :					Union[str, Any]       =load_dataset("""imdb""", split=["""train""", """test"""])
						_UpperCAmelCase     :					int       =train_dataset.shuffle().select(range(5000))  # smaller the size for train dataset to 5k
						_UpperCAmelCase     :					str       =test_dataset.shuffle().select(range(500))  # smaller the size for test dataset to 500

						# Preprocess train dataset
						_UpperCAmelCase     :					str       =train_dataset.map(
						    lambda e: tokenizer(e["""text"""], truncation=True, padding="""max_length"""), batched=True
						)
						train_dataset.set_format(type="""tensorflow""", columns=["""input_ids""", """attention_mask""", """label"""])

						_UpperCAmelCase     :					List[Any]       ={
						    x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
						    for x in ["""input_ids""", """attention_mask"""]
						}
						_UpperCAmelCase     :					Optional[Any]       =tf.data.Dataset.from_tensor_slices((train_features, train_dataset["""label"""])).batch(
						    args.per_device_train_batch_size
						)

						# Preprocess test dataset
						_UpperCAmelCase     :					List[Any]       =test_dataset.map(
						    lambda e: tokenizer(e["""text"""], truncation=True, padding="""max_length"""), batched=True
						)
						test_dataset.set_format(type="""tensorflow""", columns=["""input_ids""", """attention_mask""", """label"""])

						_UpperCAmelCase     :					Dict       ={
						    x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
						    for x in ["""input_ids""", """attention_mask"""]
						}
						_UpperCAmelCase     :					Any       =tf.data.Dataset.from_tensor_slices((test_features, test_dataset["""label"""])).batch(
						    args.per_device_eval_batch_size
						)

						# fine optimizer and loss
						_UpperCAmelCase     :					List[Any]       =tf.keras.optimizers.Adam(learning_rate=args.learning_rate)
						_UpperCAmelCase     :					str       =tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
						_UpperCAmelCase     :					Optional[Any]       =[tf.keras.metrics.SparseCategoricalAccuracy()]
						model.compile(optimizer=optimizer, loss=loss, metrics=metrics)

						_UpperCAmelCase     :					Tuple       =time.time()
						_UpperCAmelCase     :					List[str]       =model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size)
						_UpperCAmelCase     :					Optional[int]       =time.time() - start_train_time

						logger.info("""*** Train ***""")
						logger.info(f"""train_runtime = {end_train_time}""")
						for key, value in train_results.history.items():
												logger.info(f"""  {key} = {value}""")