
"""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 			_lowercase  :
	lowercase_								=      field(
	    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}						)
	lowercase_								=      field(
	    default=snake_case_							,			metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}							,			)
	lowercase_								=      field(
	    default=snake_case_							,			metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}						)
	lowercase_								=      field(
	    default=snake_case_							,			metadata={'help': 'Whether to log verbose messages or not.'}							,			)


def 						UpperCAmelCase   (						a_,		a_     ):





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






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






@dataclass
class 			_lowercase  :
	lowercase_								=      False
	lowercase_								=      None
	lowercase_								=      '|'
	lowercase_								=      field(default_factory=snake_case_						)
	lowercase_								=      field(default_factory=snake_case_						)
	lowercase_								=      None




	@classmethod
	def      _UpperCamelCase       (					cls						,					UpperCAmelCase_   )						->				Union[str, Any]:
			if name == "librispeech":
					return cls()
			if name == "timit":
					return cls(
					    do_lower_case=__lowerCamelCase						,					translation_table=str.maketrans({'-': ' '}   )						,					)
			if name == "buckwalter":
					lowerCamelCase	:     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      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				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	:     Dict            =       text.translate(self.translation_table   )
			if len(self.words_to_remove   ) == 0:
					lowerCamelCase	:     int            =       ' '.join(text.split()   )  # clean up whitespaces
			else:
					lowerCamelCase	:     Optional[Any]            =       ' '.join(w for w in text.split() if w not in self.words_to_remove   )  # and clean up whilespaces
			return text




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				WavaVecaProcessor:
			lowerCamelCase	:     List[str]            =       WavaVecaFeatureExtractor.from_pretrained(
			    model_args.model_name_or_path						,					cache_dir=model_args.cache_dir   )
			if self.vocab_file:
					lowerCamelCase	:     Optional[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:
					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(__lowerCamelCase						,					__lowerCamelCase   )






@dataclass
class 			_lowercase  :
	lowercase_								=      4_2
	lowercase_								=      True
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None




	def __call__(					self						,					UpperCAmelCase_   )						->				Dict[str, torch.Tensor]:
			# split inputs and labels since they have to be of different lenghts and need
			# different padding methods
			lowerCamelCase	:     Union[str, Any]            =       [{'input_values': feature['input_values']} for feature in features]
			lowerCamelCase	:     Tuple            =       [{'input_ids': feature['labels']} for feature in features]

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

			lowerCamelCase	:     Union[str, Any]            =       labels

			return batch






class 			_lowercase  (							snake_case_						):




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				torch.Tensor:
			model.train()
			lowerCamelCase	:     Any            =       self._prepare_inputs(__lowerCamelCase   )

			if self.use_amp:
					with autocast():
							lowerCamelCase	:     Union[str, Any]            =       self.compute_loss(__lowerCamelCase						,					__lowerCamelCase   )
			else:
					lowerCamelCase	:     Tuple            =       self.compute_loss(__lowerCamelCase						,					__lowerCamelCase   )

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





		'''simple docstring'''


		lowerCamelCase	:     Any            =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

		lowerCamelCase      ,       lowerCamelCase      ,       lowerCamelCase	:     Optional[int]            =       parser.parse_args_into_dataclasses()
		configure_logger(__lowerCamelCase,		__lowerCamelCase     )

		lowerCamelCase	:     Any            =       Orthography.from_name(data_args.orthography.lower()     )
		lowerCamelCase	:     Any            =       orthography.create_processor(__lowerCamelCase     )
		lowerCamelCase	:     Optional[int]            =       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	:     Tuple            =       datasets.load_dataset(
		    data_args.dataset_name,		data_args.dataset_config_name,		split=data_args.train_split_name     )
		lowerCamelCase	:     Optional[int]            =       datasets.load_dataset(
		    data_args.dataset_name,		data_args.dataset_config_name,		split=data_args.validation_split_name     )

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

		def prepare_example(a_     ):  # TODO(elgeish) make use of multiprocessing?
				lowerCamelCase      ,       lowerCamelCase	:     Union[str, Any]            =       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	:     Union[str, 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	:     List[str]            =       train_dataset.map(__lowerCamelCase,		remove_columns=[data_args.speech_file_column]     )
		lowerCamelCase	:     List[Any]            =       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(a_     ):
						return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

				lowerCamelCase	:     int            =       len(__lowerCamelCase     )
				lowerCamelCase	:     List[Any]            =       len(__lowerCamelCase     )
				lowerCamelCase	:     List[str]            =       train_dataset.filter(__lowerCamelCase,		remove_columns=['duration_in_seconds']     )
				lowerCamelCase	:     Tuple            =       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	:     Optional[Any]            =       None

		def prepare_dataset(a_     ):
				# 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	:     List[Any]            =       processor(
				    audio=batch['speech'],		text=batch[data_args.target_text_column],		sampling_rate=batch['sampling_rate'][0]     )
				batch.update(__lowerCamelCase     )
				return batch

		lowerCamelCase	:     Optional[Any]            =       train_dataset.map(
		    __lowerCamelCase,		batch_size=training_args.per_device_train_batch_size,		batched=__lowerCamelCase,		num_proc=data_args.preprocessing_num_workers,		)
		lowerCamelCase	:     Optional[Any]            =       val_dataset.map(
		    __lowerCamelCase,		batch_size=training_args.per_device_train_batch_size,		batched=__lowerCamelCase,		num_proc=data_args.preprocessing_num_workers,		)

		lowerCamelCase	:     str            =       DataCollatorCTCWithPadding(processor=__lowerCamelCase,		padding=__lowerCamelCase     )

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

				lowerCamelCase	:     Optional[Any]            =       processor.tokenizer.pad_token_id

				lowerCamelCase	:     List[Any]            =       processor.batch_decode(__lowerCamelCase     )
				# we do not want to group tokens when computing the metrics
				lowerCamelCase	:     str            =       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	:     Union[str, Any]            =       wer_metric.compute(predictions=__lowerCamelCase,		references=__lowerCamelCase     )

				return {"wer": wer}

		if model_args.freeze_feature_extractor:
				model.freeze_feature_extractor()

		lowerCamelCase	:     Union[str, Any]            =       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 copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase           =							logging.get_logger(__name__)

lowercase           =							{
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}

class     A_				(   snake_case_	):







				def __init__(				self				:    List[Any]    ,     __lowerCamelCase				:    str=2_5_6    ,     __lowerCamelCase				:    str=1_0_2_4    ,     __lowerCamelCase				:    Optional[Any]=1_6    ,     __lowerCamelCase				:    Union[str, Any]=1_6    ,     __lowerCamelCase				:    str=4    ,     __lowerCamelCase				:    Union[str, Any]="gelu"    ,     __lowerCamelCase				:    Optional[int]=1e-6    ,     **__lowerCamelCase				:    str    ,     )					->       List[Any]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  image_size // patch_size
										__magic_name__      =  mask_input_channels
										__magic_name__      =  num_point_embeddings
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    List[str]    ,     __lowerCamelCase				:    Optional[Any]=2_5_6    ,     __lowerCamelCase				:    int="relu"    ,     __lowerCamelCase				:    List[str]=2_0_4_8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Optional[Any]=8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Dict=3    ,     __lowerCamelCase				:    Optional[int]=3    ,     __lowerCamelCase				:    Tuple=2_5_6    ,     __lowerCamelCase				:    List[str]=1e-6    ,     **__lowerCamelCase				:    Any    ,     )					->       str:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  hidden_act
										__magic_name__      =  mlp_dim
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  attention_downsample_rate
										__magic_name__      =  num_multimask_outputs
										__magic_name__      =  iou_head_depth
										__magic_name__      =  iou_head_hidden_dim
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    Union[str, Any]    ,     __lowerCamelCase				:    str=7_6_8    ,     __lowerCamelCase				:    Optional[int]=2_5_6    ,     __lowerCamelCase				:    Tuple=1_2    ,     __lowerCamelCase				:    int=1_2    ,     __lowerCamelCase				:    int=3    ,     __lowerCamelCase				:    int=1_0_2_4    ,     __lowerCamelCase				:    Any=1_6    ,     __lowerCamelCase				:    Tuple="gelu"    ,     __lowerCamelCase				:    Dict=1e-06    ,     __lowerCamelCase				:    List[Any]=0.0    ,     __lowerCamelCase				:    Optional[Any]=1e-10    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    List[str]=4.0    ,     __lowerCamelCase				:    Union[str, Any]=True    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    Optional[Any]=1_4    ,     __lowerCamelCase				:    str=[2, 5, 8, 1_1]    ,     __lowerCamelCase				:    List[Any]=1_2_8    ,     __lowerCamelCase				:    Dict=None    ,     **__lowerCamelCase				:    List[str]    ,     )					->       Optional[int]:
										super().__init__(**__lowerCamelCase						)

										__magic_name__      =  hidden_size
										__magic_name__      =  output_channels
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  num_channels
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps
										__magic_name__      =  attention_dropout
										__magic_name__      =  initializer_range
										__magic_name__      =  qkv_bias
										__magic_name__      =  mlp_ratio
										__magic_name__      =  use_abs_pos
										__magic_name__      =  use_rel_pos
										__magic_name__      =  window_size
										__magic_name__      =  global_attn_indexes
										__magic_name__      =  num_pos_feats
										__magic_name__      =  int(hidden_size * mlp_ratio						) if mlp_dim is None else mlp_dim





class     A_				(   snake_case_	):
				UpperCAmelCase__										=					'''sam'''
				UpperCAmelCase__										=					True







				def __init__(				self				:    Optional[Any]    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Optional[Any]=None    ,     __lowerCamelCase				:    int=0.02    ,     **__lowerCamelCase				:    List[Any]    ,     )					->       List[str]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  vision_config if vision_config is not None else {}
										__magic_name__      =  prompt_encoder_config if prompt_encoder_config is not None else {}
										__magic_name__      =  mask_decoder_config if mask_decoder_config is not None else {}

										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  vision_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  prompt_encoder_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  mask_decoder_config.to_dict()

										__magic_name__      =  SamVisionConfig(**__lowerCamelCase						)
										__magic_name__      =  SamPromptEncoderConfig(**__lowerCamelCase						)
										__magic_name__      =  SamMaskDecoderConfig(**__lowerCamelCase						)
										__magic_name__      =  initializer_range







				def      _snake_case       (				self				:    Optional[int]						)					->       str:
										__magic_name__      =  copy.deepcopy(self.__dict__						)
										__magic_name__      =  self.vision_config.to_dict()
										__magic_name__      =  self.prompt_encoder_config.to_dict()
										__magic_name__      =  self.mask_decoder_config.to_dict()
										__magic_name__      =  self.__class__.model_type
										return output



