

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


_lowerCamelCase	 =			logging.getLogger(__name__)
@dataclass
class  _snake_case						:
			__A   :     str          =field(
			    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"})
			__A   :     Optional[str]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}       ,       )
			__A   :     Optional[bool]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Whether to freeze the feature extractor layers of the model."})
			__A   :     Optional[bool]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Whether to log verbose messages or not."}       ,       )




def       a__    (  _SCREAMING_SNAKE_CASE					:    ModelArguments     ,							_SCREAMING_SNAKE_CASE					:    TrainingArguments							)			-> int:


	"""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_			:	Union[str, Any]      =   logging.WARNING
	if model_args.verbose_logging:
		UpperCAmelCase_			:	Any      =   logging.DEBUG
	elif trainer_utils.is_main_process(training_args.local_rank							):
		UpperCAmelCase_			:	List[str]      =   logging.INFO
	logger.setLevel(_SCREAMING_SNAKE_CASE							)
@dataclass
class  _snake_case						:
			__A   :     str          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "The name of the dataset to use (via the datasets library)."})
			__A   :     Optional[str]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "The configuration name of the dataset to use (via the datasets library)."})
			__A   :     Optional[str]          =field(
			    default="train"       ,       metadata={
			        "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
			    }       ,       )
			__A   :     Optional[str]          =field(
			    default="validation"       ,       metadata={
			        "help": (
			            "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
			        )
			    }       ,       )
			__A   :     Optional[str]          =field(
			    default="text"       ,       metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}       ,       )
			__A   :     Optional[str]          =field(
			    default="file"       ,       metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}       ,       )
			__A   :     Optional[bool]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}       ,       )
			__A   :     Optional[float]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}       ,       )
			__A   :     Optional[str]          =field(
			    default="librispeech"       ,       metadata={
			        "help": (
			            "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
			            " 'buckwalter'."
			        )
			    }       ,       )
			__A   :     bool          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "Overwrite the cached preprocessed datasets or not."})
			__A   :     Optional[int]          =field(
			    default=__SCREAMING_SNAKE_CASE       ,       metadata={"help": "The number of processes to use for the preprocessing."}       ,       )




@dataclass
class  _snake_case						:
			__A   :     bool          =False
			__A   :     Optional[str]          =None
			__A   :     Optional[str]          ="|"
			__A   :     Optional[Dict[str, str]]          =field(default_factory=__SCREAMING_SNAKE_CASE)
			__A   :     Optional[Set[str]]          =field(default_factory=__SCREAMING_SNAKE_CASE)
			__A   :     Optional[Callable[[str], str]]          =None






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






			def 						UpperCamelCase__				(   self       ,_snake_case			):
				# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
				if len(self.translation_table			) > 0:
					UpperCAmelCase_			:	str      =   text.translate(self.translation_table			)
				if len(self.words_to_remove			) == 0:
					UpperCAmelCase_			:	List[str]      =   " ".join(text.split()			)  # clean up whitespaces
				else:
					UpperCAmelCase_			:	str      =   " ".join(w for w in text.split() if w not in self.words_to_remove			)  # and clean up whilespaces
				return text






			def 						UpperCamelCase__				(   self       ,_snake_case			):
				UpperCAmelCase_			:	Optional[Any]      =   WavaVecaFeatureExtractor.from_pretrained(
				    model_args.model_name_or_path       ,cache_dir=model_args.cache_dir			)
				if self.vocab_file:
					UpperCAmelCase_			:	List[str]      =   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_			:	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(_snake_case       ,_snake_case			)




@dataclass
class  _snake_case						:
			__A   :     WavaVecaProcessor
			__A   :     Union[bool, str]          =True
			__A   :     Optional[int]          =None
			__A   :     Optional[int]          =None
			__A   :     Optional[int]          =None
			__A   :     Optional[int]          =None






			def __call__(   self       ,_snake_case			):
				# split inputs and labels since they have to be of different lenghts and need
				# different padding methods
				UpperCAmelCase_			:	List[Any]      =   [{"input_values": feature["input_values"]} for feature in features]
				UpperCAmelCase_			:	Union[str, Any]      =   [{"input_ids": feature["labels"]} for feature in features]

				UpperCAmelCase_			:	Any      =   self.processor.pad(
				    _snake_case       ,padding=self.padding       ,max_length=self.max_length       ,pad_to_multiple_of=self.pad_to_multiple_of       ,return_tensors="pt"       ,)
				UpperCAmelCase_			:	Optional[int]      =   self.processor.pad(
				    labels=_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_			:	List[str]      =   labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1			)       ,-1_00			)

				UpperCAmelCase_			:	str      =   labels

				return batch




class  _snake_case						(__SCREAMING_SNAKE_CASE):






			def 						UpperCamelCase__				(   self       ,_snake_case       ,_snake_case			):
				model.train()
				UpperCAmelCase_			:	List[str]      =   self._prepare_inputs(_snake_case			)

				if self.use_amp:
					with autocast():
						UpperCAmelCase_			:	int      =   self.compute_loss(_snake_case       ,_snake_case			)
				else:
					UpperCAmelCase_			:	Any      =   self.compute_loss(_snake_case       ,_snake_case			)

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

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

				return loss.detach()




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


	"""simple docstring"""





	UpperCAmelCase_			:	Union[str, Any]      =   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)

	UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_			:	str      =   parser.parse_args_into_dataclasses()
	configure_logger(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)

	UpperCAmelCase_			:	int      =   Orthography.from_name(data_args.orthography.lower()							)
	UpperCAmelCase_			:	List[Any]      =   orthography.create_processor(_SCREAMING_SNAKE_CASE							)
	UpperCAmelCase_			:	List[str]      =   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_			:	Union[str, Any]      =   datasets.load_dataset(
	    data_args.dataset_name     ,							data_args.dataset_config_name     ,							split=data_args.train_split_name							)
	UpperCAmelCase_			:	Dict      =   datasets.load_dataset(
	    data_args.dataset_name     ,							data_args.dataset_config_name     ,							split=data_args.validation_split_name							)

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

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

	UpperCAmelCase_			:	Union[str, Any]      =   train_dataset.map(_SCREAMING_SNAKE_CASE     ,							remove_columns=[data_args.speech_file_column]							)
	UpperCAmelCase_			:	List[str]      =   val_dataset.map(_SCREAMING_SNAKE_CASE     ,							remove_columns=[data_args.speech_file_column]							)

	if data_args.max_duration_in_seconds is not None:

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

		UpperCAmelCase_			:	List[str]      =   len(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	Union[str, Any]      =   len(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	str      =   train_dataset.filter(_SCREAMING_SNAKE_CASE     ,							remove_columns=["duration_in_seconds"]							)
		UpperCAmelCase_			:	Optional[Any]      =   val_dataset.filter(_SCREAMING_SNAKE_CASE     ,							remove_columns=["duration_in_seconds"]							)
		if len(_SCREAMING_SNAKE_CASE							) > old_train_size:
			logger.warning(
			    F'''Filtered out {len(_SCREAMING_SNAKE_CASE							) - old_train_size} train example(s) longer than'''
			    F''' {data_args.max_duration_in_seconds} second(s).'''							)
		if len(_SCREAMING_SNAKE_CASE							) > old_val_size:
			logger.warning(
			    F'''Filtered out {len(_SCREAMING_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(_SCREAMING_SNAKE_CASE							)} train and {len(_SCREAMING_SNAKE_CASE							)} validation.'''							)

	logger.warning(F'''Updated {len(_SCREAMING_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_			:	List[Any]      =   None

	def prepare_dataset(_SCREAMING_SNAKE_CASE					:    str							):
		# 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_			:	Any      =   processor(
		    audio=batch["speech"]     ,							text=batch[data_args.target_text_column]     ,							sampling_rate=batch["sampling_rate"][0]							)
		batch.update(_SCREAMING_SNAKE_CASE							)
		return batch

	UpperCAmelCase_			:	int      =   train_dataset.map(
	    _SCREAMING_SNAKE_CASE     ,							batch_size=training_args.per_device_train_batch_size     ,							batched=_SCREAMING_SNAKE_CASE     ,							num_proc=data_args.preprocessing_num_workers     ,							)
	UpperCAmelCase_			:	List[Any]      =   val_dataset.map(
	    _SCREAMING_SNAKE_CASE     ,							batch_size=training_args.per_device_train_batch_size     ,							batched=_SCREAMING_SNAKE_CASE     ,							num_proc=data_args.preprocessing_num_workers     ,							)

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

	def compute_metrics(_SCREAMING_SNAKE_CASE					:    List[Any]							):
		UpperCAmelCase_			:	str      =   pred.predictions
		UpperCAmelCase_			:	int      =   np.argmax(_SCREAMING_SNAKE_CASE     ,							axis=-1							)

		UpperCAmelCase_			:	Dict      =   processor.tokenizer.pad_token_id

		UpperCAmelCase_			:	int      =   processor.batch_decode(_SCREAMING_SNAKE_CASE							)
		# we do not want to group tokens when computing the metrics
		UpperCAmelCase_			:	Union[str, Any]      =   processor.batch_decode(pred.label_ids     ,							group_tokens=_SCREAMING_SNAKE_CASE							)
		if logger.isEnabledFor(logging.DEBUG							):
			for reference, predicted in zip(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_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(_SCREAMING_SNAKE_CASE							)}"'''							)
					logger.debug(F'''predicted (untransliterated): "{orthography.untransliterator(_SCREAMING_SNAKE_CASE							)}"'''							)

		UpperCAmelCase_			:	Optional[Any]      =   wer_metric.compute(predictions=_SCREAMING_SNAKE_CASE     ,							references=_SCREAMING_SNAKE_CASE							)

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	UpperCAmelCase_			:	Any      =   CTCTrainer(
	    model=_SCREAMING_SNAKE_CASE     ,							data_collator=_SCREAMING_SNAKE_CASE     ,							args=_SCREAMING_SNAKE_CASE     ,							compute_metrics=_SCREAMING_SNAKE_CASE     ,							train_dataset=_SCREAMING_SNAKE_CASE     ,							eval_dataset=_SCREAMING_SNAKE_CASE     ,							tokenizer=processor.feature_extractor     ,							)

	trainer.train()


if __name__ == "__main__":
					main()










import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
      import sqlitea

      import sqlalchemy


__SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=datasets.utils.logging.get_logger(__name__)






@dataclass
class 	A	(						datasets.BuilderConfig						):
     """simple docstring"""

     _snake_case:		Union[str, "sqlalchemy.sql.Selectable"]   =None
     _snake_case:		Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]   =None
     _snake_case:		Optional[Union[str, List[str]]]   =None
     _snake_case:		bool   =True
     _snake_case:		Optional[Union[List, Tuple, Dict]]   =None
     _snake_case:		Optional[Union[List, Dict]]   =None
     _snake_case:		Optional[List[str]]   =None
     _snake_case:		Optional[int]   =10_000
     _snake_case:		Optional[datasets.Features]   =None




     def        __snake_case      (			self     :      Optional[Any]	) ->				Union[str, Any]:
           if self.sql is None:
                 raise ValueError('sql must be specified'	)
           if self.con is None:
                 raise ValueError('con must be specified'	)




     def        __snake_case      (			self     :      List[Any]		,     A__     :      dict		,     A__     :      Optional[datasets.Features] = None		,     ) ->				str:
           lowerCamelCase__					     = config_kwargs.copy()
           # We need to stringify the Selectable object to make its hash deterministic

           # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
           lowerCamelCase__					     = config_kwargs['sql']
           if not isinstance(A__		,     A__	):
                 if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                       import sqlalchemy

                       if isinstance(A__		,     sqlalchemy.sql.Selectable	):
                             lowerCamelCase__					     = sqlalchemy.create_engine(config_kwargs['con'].split('://'	)[0] + '://'	)
                             lowerCamelCase__					     = str(sql.compile(dialect=engine.dialect	)	)
                             lowerCamelCase__					     = sql_str
                       else:
                             raise TypeError(
                                 F"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(A__	)}: {sql}"""	)
                 else:
                       raise TypeError(
                           F"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(A__	)}: {sql}"""	)
           lowerCamelCase__					     = config_kwargs['con']
           if not isinstance(A__		,     A__	):
                 lowerCamelCase__					     = id(A__	)
                 logger.info(
                     F"""SQL connection 'con' of type {type(A__	)} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."""	)

           return super().create_config_id(A__		,     custom_features=A__	)




     @property
     def        __snake_case      (			self     :      Any	) ->				Union[str, Any]:
           lowerCamelCase__					     = {
               'index_col': self.index_col,
               'columns': self.columns,
               'params': self.params,
               'coerce_float': self.coerce_float,
               'parse_dates': self.parse_dates,
           }
           return pd_read_sql_kwargs






class 	A	(						datasets.ArrowBasedBuilder						):
     """simple docstring"""

     _snake_case:		List[str]   =SqlConfig




     def        __snake_case      (			self     :      Tuple	) ->				Dict:
           return datasets.DatasetInfo(features=self.config.features	)




     def        __snake_case      (			self     :      List[Any]		,     A__     :      Any	) ->				List[Any]:
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,     gen_kwargs={}	)]




     def        __snake_case      (			self     :      Union[str, Any]		,     A__     :      pa.Table	) ->				pa.Table:
           if self.config.features is not None:
                 lowerCamelCase__					     = self.config.features.arrow_schema
                 if all(not require_storage_cast(A__	) for feature in self.config.features.values()	):
                       # cheaper cast
                       lowerCamelCase__					     = pa.Table.from_arrays([pa_table[field.name] for field in schema]		,     schema=A__	)
                 else:
                       # more expensive cast; allows str <-> int/float or str to Audio for example
                       lowerCamelCase__					     = table_cast(A__		,     A__	)
           return pa_table




     def        __snake_case      (			self     :      int	) ->				List[Any]:
           lowerCamelCase__					     = self.config.chunksize
           lowerCamelCase__					     = pd.read_sql(
               self.config.sql		,     self.config.con		,     chunksize=A__		,     **self.config.pd_read_sql_kwargs	)
           lowerCamelCase__					     = [sql_reader] if chunksize is None else sql_reader
           for chunk_idx, df in enumerate(A__	):
                 lowerCamelCase__					     = pa.Table.from_pandas(A__	)
                 yield chunk_idx, self._cast_table(A__	)