






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


lowercase           =							logging.getLogger(__name__)

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






def _lowerCAmelCase						(	__lowerCamelCase:ModelArguments			,    __lowerCamelCase:TrainingArguments ):

						'''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 )]			,    )
						__magic_name__      =  logging.WARNING
						if model_args.verbose_logging:
												__magic_name__      =  logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank ):
												__magic_name__      =  logging.INFO
						logger.setLevel(__lowerCamelCase )

@dataclass
class     A_				:
				UpperCAmelCase__										=					field(
				    default=snake_case_       ,				metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''}	)
				UpperCAmelCase__										=					field(
				    default=snake_case_       ,				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=snake_case_       ,				metadata={'''help''': '''Resample loaded audio to target feature extractor\'s sampling rate or not.'''}       ,				)
				UpperCAmelCase__										=					field(
				    default=snake_case_       ,				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=snake_case_       ,				metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}	)
				UpperCAmelCase__										=					field(
				    default=snake_case_       ,				metadata={'''help''': '''The number of processes to use for the preprocessing.'''}       ,				)





@dataclass
class     A_				:
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					None
				UpperCAmelCase__										=					"|"
				UpperCAmelCase__										=					field(default_factory=snake_case_	)
				UpperCAmelCase__										=					field(default_factory=snake_case_	)
				UpperCAmelCase__										=					None







				@classmethod
				def      _snake_case       (				cls				:    List[Any]    ,     __lowerCamelCase				:    str						)					->       Union[str, Any]:
										if name == "librispeech":
																return cls()
										if name == "timit":
																return cls(
																    do_lower_case=__lowerCamelCase    ,     translation_table=str.maketrans({"-": " "}						)    ,     )
										if name == "buckwalter":
																__magic_name__      =  {
																    "-": " ",  # 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[Any]    ,     __lowerCamelCase				:    str						)					->       str:
										# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
										if len(self.translation_table						) > 0:
																__magic_name__      =  text.translate(self.translation_table						)
										if len(self.words_to_remove						) == 0:
																__magic_name__      =  " ".join(text.split()						)  # clean up whitespaces
										else:
																__magic_name__      =  " ".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				:    Optional[int]    ,     __lowerCamelCase				:    ModelArguments						)					->       WavaVecaProcessor:
										__magic_name__      =  WavaVecaFeatureExtractor.from_pretrained(
										    model_args.model_name_or_path    ,     cache_dir=model_args.cache_dir						)
										if self.vocab_file:
																__magic_name__      =  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:
																__magic_name__      =  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]:
										# split inputs and labels since they have to be of different lenghts and need
										# different padding methods
										__magic_name__      =  [{"input_values": feature["input_values"]} for feature in features]
										__magic_name__      =  [{"input_ids": feature["labels"]} for feature in features]

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

										__magic_name__      =  labels

										return batch





class     A_				(   snake_case_	):







				def      _snake_case       (				self				:    int    ,     __lowerCamelCase				:    nn.Module    ,     __lowerCamelCase				:    Dict[str, Union[torch.Tensor, Any]]						)					->       torch.Tensor:
										model.train()
										__magic_name__      =  self._prepare_inputs(__lowerCamelCase						)

										if self.use_amp:
																with autocast():
																						__magic_name__      =  self.compute_loss(__lowerCamelCase    ,     __lowerCamelCase						)
										else:
																__magic_name__      =  self.compute_loss(__lowerCamelCase    ,     __lowerCamelCase						)

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

						'''simple docstring'''






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

						__magic_name__   ,     __magic_name__   ,     __magic_name__      =  parser.parse_args_into_dataclasses()
						configure_logger(__lowerCamelCase			,    __lowerCamelCase )

						__magic_name__      =  Orthography.from_name(data_args.orthography.lower() )
						__magic_name__      =  orthography.create_processor(__lowerCamelCase )
						__magic_name__      =  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 )			,    )

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

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

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

						__magic_name__      =  train_dataset.map(__lowerCamelCase			,    remove_columns=[data_args.speech_file_column] )
						__magic_name__      =  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:Optional[int] ):
																		return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

												__magic_name__      =  len(__lowerCamelCase )
												__magic_name__      =  len(__lowerCamelCase )
												__magic_name__      =  train_dataset.filter(__lowerCamelCase			,    remove_columns=["duration_in_seconds"] )
												__magic_name__      =  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}"''' )
						__magic_name__      =  None

						def prepare_dataset(__lowerCamelCase:int ):
												# 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}.'''

												__magic_name__      =  processor(
												    audio=batch["speech"]			,    text=batch[data_args.target_text_column]			,    sampling_rate=batch["sampling_rate"][0] )
												batch.update(__lowerCamelCase )
												return batch

						__magic_name__      =  train_dataset.map(
						    __lowerCamelCase			,    batch_size=training_args.per_device_train_batch_size			,    batched=__lowerCamelCase			,    num_proc=data_args.preprocessing_num_workers			,    )
						__magic_name__      =  val_dataset.map(
						    __lowerCamelCase			,    batch_size=training_args.per_device_train_batch_size			,    batched=__lowerCamelCase			,    num_proc=data_args.preprocessing_num_workers			,    )

						__magic_name__      =  DataCollatorCTCWithPadding(processor=__lowerCamelCase			,    padding=__lowerCamelCase )

						def compute_metrics(__lowerCamelCase:Optional[Any] ):
												__magic_name__      =  pred.predictions
												__magic_name__      =  np.argmax(__lowerCamelCase			,    axis=-1 )

												__magic_name__      =  processor.tokenizer.pad_token_id

												__magic_name__      =  processor.batch_decode(__lowerCamelCase )
												# we do not want to group tokens when computing the metrics
												__magic_name__      =  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 )}"''' )

												__magic_name__      =  wer_metric.compute(predictions=__lowerCamelCase			,    references=__lowerCamelCase )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						__magic_name__      =  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()











"""simple docstring"""

import warnings

from ...utils import logging
from .image_processing_conditional_detr import ConditionalDetrImageProcessor


lowercase           =							logging.get_logger(__name__)

class     A_				(   snake_case_	):







				def __init__(				self				:    str    ,     *__lowerCamelCase				:    List[Any]    ,     **__lowerCamelCase				:    List[str]						)					->       None:
										warnings.warn(
										    "The class ConditionalDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
										    " Please use ConditionalDetrImageProcessor instead."    ,     __lowerCamelCase    ,     )
										super().__init__(*__lowerCamelCase    ,     **__lowerCamelCase						)



