






"""simple docstring"""




import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
 from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
 _snake_case          =   True
 from torch.cuda.amp import autocast

_snake_case          =   logging.getLogger(__name__)

def 			lowerCAmelCase__     (     UpperCamelCase__=None     ,   UpperCamelCase__=None				):



  '''simple docstring'''
  return field(default_factory=lambda: default     ,   metadata=UpperCamelCase__				)






@dataclass
class        UpperCamelCase			:
 UpperCamelCase					:       str			=					field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}      )
 UpperCamelCase					:       Optional[str]			=					field(
     default=snake_case_		,     metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}		,     )
 UpperCamelCase					:       Optional[bool]			=					field(
     default=snake_case_		,     metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}      )
 UpperCamelCase					:       Optional[float]			=					field(
     default=0.1		,     metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}      )
 UpperCamelCase					:       Optional[float]			=					field(
     default=0.1		,     metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}      )
 UpperCamelCase					:       Optional[float]			=					field(
     default=0.1		,     metadata={
         '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
     }		,     )
 UpperCamelCase					:       Optional[float]			=					field(
     default=0.1		,     metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}		,     )
 UpperCamelCase					:       Optional[float]			=					field(
     default=0.0_5		,     metadata={
         '''help''': (
             '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
             '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
             '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
         )
     }		,     )
 UpperCamelCase					:       Optional[float]			=					field(default=0.0		,     metadata={'''help''': '''The LayerDrop probability.'''}      )







@dataclass
class        UpperCamelCase			:
 UpperCamelCase					:       Optional[str]			=					field(
     default=snake_case_		,     metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}      )
 UpperCamelCase					:       Optional[str]			=					field(
     default='''train+validation'''		,     metadata={
         '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
     }		,     )
 UpperCamelCase					:       bool			=					field(
     default=snake_case_		,     metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}      )
 UpperCamelCase					:       Optional[int]			=					field(
     default=snake_case_		,     metadata={'''help''': '''The number of processes to use for the preprocessing.'''}		,     )
 UpperCamelCase					:       Optional[int]			=					field(
     default=snake_case_		,     metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of training examples to this '''
             '''value if set.'''
         )
     }		,     )
 UpperCamelCase					:       Optional[int]			=					field(
     default=snake_case_		,     metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
             '''value if set.'''
         )
     }		,     )
 UpperCamelCase					:       List[str]			=					list_field(
     default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']		,     metadata={'''help''': '''A list of characters to remove from the transcripts.'''}		,     )







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


 def __call__(     self		:						Optional[int]							,						UpperCAmelCase__		:						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
   _a  :       str             =	[{"""input_values""": feature["""input_values"""]} for feature in features]
   _a  :       Dict             =	[{"""input_ids""": feature["""labels"""]} for feature in features]

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

   _a  :       List[Any]             =	labels

   return batch







class        UpperCamelCase			(	snake_case_      ):


 def _lowercase	(     self		:						Tuple							,						UpperCAmelCase__		:						nn.Module							,						UpperCAmelCase__		:						Dict[str, Union[torch.Tensor, Any]]							)					->       torch.Tensor:
   model.train()
   _a  :       Dict             =	self._prepare_inputs(UpperCAmelCase__							)

   if self.use_amp:
     with autocast():
       _a  :       Tuple             =	self.compute_loss(UpperCAmelCase__							,						UpperCAmelCase__							)
   else:
     _a  :       List[str]             =	self.compute_loss(UpperCAmelCase__							,						UpperCAmelCase__							)

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

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

   return loss.detach()







def 			lowerCAmelCase__     (     ):



  '''simple docstring'''
  # 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.

  _a  :       Optional[int]             =	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
  if len(sys.argv				) == 2 and sys.argv[1].endswith(""".json"""				):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    _a      ,  _a      ,  _a  :       Optional[int]             =	parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
  else:
    _a      ,  _a      ,  _a  :       Optional[int]             =	parser.parse_args_into_dataclasses()

  # Detecting last checkpoint.
  _a  :       Optional[int]             =	None
  if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
    _a  :       Dict             =	get_last_checkpoint(training_args.output_dir				)
    if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
      raise ValueError(
          F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
          """Use --overwrite_output_dir to overcome."""				)
    elif last_checkpoint is not None:
      logger.info(
          F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
          """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""				)

    # Setup logging
  logging.basicConfig(
      format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""     ,   datefmt="""%m/%d/%Y %H:%M:%S"""     ,   handlers=[logging.StreamHandler(sys.stdout				)]     ,   )
  logger.setLevel(logging.INFO if is_main_process(training_args.local_rank				) else logging.WARN				)

  # Log on each process the small summary:
  logger.warning(
      F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
      + F"""distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}"""				)
  # Set the verbosity to info of the Transformers logger (on main process only):
  if is_main_process(training_args.local_rank				):
    transformers.utils.logging.set_verbosity_info()
  logger.info("""Training/evaluation parameters %s"""     ,   UpperCamelCase__				)

  # Set seed before initializing model.
  set_seed(training_args.seed				)

  # Get the datasets:
  _a  :       str             =	datasets.load_dataset(
      """common_voice"""     ,   data_args.dataset_config_name     ,   split=data_args.train_split_name				)
  _a  :       Optional[int]             =	datasets.load_dataset("""common_voice"""     ,   data_args.dataset_config_name     ,   split="""test"""				)

  # Create and save tokenizer
  _a  :       Union[str, Any]             =	F"""[{''.join(data_args.chars_to_ignore				)}]"""

  def remove_special_characters(UpperCamelCase__				):
    _a  :       Optional[int]             =	re.sub(UpperCamelCase__     ,   """"""     ,   batch["""sentence"""]				).lower() + """ """
    return batch

  _a  :       Optional[Any]             =	train_dataset.map(UpperCamelCase__     ,   remove_columns=["""sentence"""]				)
  _a  :       Optional[Any]             =	eval_dataset.map(UpperCamelCase__     ,   remove_columns=["""sentence"""]				)

  def extract_all_chars(UpperCamelCase__				):
    _a  :       Dict             =	""" """.join(batch["""text"""]				)
    _a  :       int             =	list(set(UpperCamelCase__				)				)
    return {"vocab": [vocab], "all_text": [all_text]}

  _a  :       Tuple             =	train_dataset.map(
      UpperCamelCase__     ,   batched=UpperCamelCase__     ,   batch_size=-1     ,   keep_in_memory=UpperCamelCase__     ,   remove_columns=train_dataset.column_names     ,   )
  _a  :       int             =	train_dataset.map(
      UpperCamelCase__     ,   batched=UpperCamelCase__     ,   batch_size=-1     ,   keep_in_memory=UpperCamelCase__     ,   remove_columns=eval_dataset.column_names     ,   )

  _a  :       Dict             =	list(set(vocab_train["""vocab"""][0]				) | set(vocab_test["""vocab"""][0]				)				)
  _a  :       str             =	{v: k for k, v in enumerate(UpperCamelCase__				)}
  _a  :       Optional[Any]             =	vocab_dict[""" """]
  del vocab_dict[" "]
  _a  :       Tuple             =	len(UpperCamelCase__				)
  _a  :       Dict             =	len(UpperCamelCase__				)

  with open("""vocab.json"""     ,   """w"""				) as vocab_file:
    json.dump(UpperCamelCase__     ,   UpperCamelCase__				)

  # Load pretrained model and tokenizer
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.
  _a  :       Optional[Any]             =	WavaVecaCTCTokenizer(
      """vocab.json"""     ,   unk_token="""[UNK]"""     ,   pad_token="""[PAD]"""     ,   word_delimiter_token="""|"""     ,   )
  _a  :       int             =	WavaVecaFeatureExtractor(
      feature_size=1     ,   sampling_rate=1_6_0_0_0     ,   padding_value=0.0     ,   do_normalize=UpperCamelCase__     ,   return_attention_mask=UpperCamelCase__				)
  _a  :       Tuple             =	WavaVecaProcessor(feature_extractor=UpperCamelCase__     ,   tokenizer=UpperCamelCase__				)
  _a  :       Union[str, Any]             =	WavaVecaForCTC.from_pretrained(
      model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir     ,   activation_dropout=model_args.activation_dropout     ,   attention_dropout=model_args.attention_dropout     ,   hidden_dropout=model_args.hidden_dropout     ,   feat_proj_dropout=model_args.feat_proj_dropout     ,   mask_time_prob=model_args.mask_time_prob     ,   gradient_checkpointing=training_args.gradient_checkpointing     ,   layerdrop=model_args.layerdrop     ,   ctc_loss_reduction="""mean"""     ,   pad_token_id=processor.tokenizer.pad_token_id     ,   vocab_size=len(processor.tokenizer				)     ,   )

  if data_args.max_train_samples is not None:
    _a  :       Any             =	min(len(UpperCamelCase__				)     ,   data_args.max_train_samples				)
    _a  :       Any             =	train_dataset.select(range(UpperCamelCase__				)				)

  if data_args.max_val_samples is not None:
    _a  :       int             =	eval_dataset.select(range(data_args.max_val_samples				)				)

  _a  :       Tuple             =	torchaudio.transforms.Resample(4_8_0_0_0     ,   1_6_0_0_0				)

  # Preprocessing the datasets.
  # We need to read the aduio files as arrays and tokenize the targets.
  def speech_file_to_array_fn(UpperCamelCase__				):
    _a      ,  _a  :       List[Any]             =	torchaudio.load(batch["""path"""]				)
    _a  :       int             =	resampler(UpperCamelCase__				).squeeze().numpy()
    _a  :       List[Any]             =	1_6_0_0_0
    _a  :       Union[str, Any]             =	batch["""text"""]
    return batch

  _a  :       int             =	train_dataset.map(
      UpperCamelCase__     ,   remove_columns=train_dataset.column_names     ,   num_proc=data_args.preprocessing_num_workers     ,   )
  _a  :       Any             =	eval_dataset.map(
      UpperCamelCase__     ,   remove_columns=eval_dataset.column_names     ,   num_proc=data_args.preprocessing_num_workers     ,   )

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

    _a  :       Union[str, Any]             =	processor(
        audio=batch["""speech"""]     ,   text=batch["""target_text"""]     ,   sampling_rate=batch["""sampling_rate"""][0]				)
    batch.update(UpperCamelCase__				)
    return batch

  _a  :       Optional[Any]             =	train_dataset.map(
      UpperCamelCase__     ,   remove_columns=train_dataset.column_names     ,   batch_size=training_args.per_device_train_batch_size     ,   batched=UpperCamelCase__     ,   num_proc=data_args.preprocessing_num_workers     ,   )
  _a  :       Tuple             =	eval_dataset.map(
      UpperCamelCase__     ,   remove_columns=eval_dataset.column_names     ,   batch_size=training_args.per_device_train_batch_size     ,   batched=UpperCamelCase__     ,   num_proc=data_args.preprocessing_num_workers     ,   )

  # Metric
  _a  :       Optional[int]             =	datasets.load_metric("""wer"""				)

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

    _a  :       Union[str, Any]             =	processor.tokenizer.pad_token_id

    _a  :       Optional[int]             =	processor.batch_decode(UpperCamelCase__				)
    # we do not want to group tokens when computing the metrics
    _a  :       Optional[int]             =	processor.batch_decode(pred.label_ids     ,   group_tokens=UpperCamelCase__				)

    _a  :       int             =	wer_metric.compute(predictions=UpperCamelCase__     ,   references=UpperCamelCase__				)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  # Data collator
  _a  :       str             =	DataCollatorCTCWithPadding(processor=UpperCamelCase__     ,   padding=UpperCamelCase__				)

  # Initialize our Trainer
  _a  :       str             =	CTCTrainer(
      model=UpperCamelCase__     ,   data_collator=UpperCamelCase__     ,   args=UpperCamelCase__     ,   compute_metrics=UpperCamelCase__     ,   train_dataset=train_dataset if training_args.do_train else None     ,   eval_dataset=eval_dataset if training_args.do_eval else None     ,   tokenizer=processor.feature_extractor     ,   )

  # Training
  if training_args.do_train:
    if last_checkpoint is not None:
      _a  :       Optional[Any]             =	last_checkpoint
    elif os.path.isdir(model_args.model_name_or_path				):
      _a  :       Optional[int]             =	model_args.model_name_or_path
    else:
      _a  :       List[Any]             =	None

    # Save the feature_extractor and the tokenizer
    if is_main_process(training_args.local_rank				):
      processor.save_pretrained(training_args.output_dir				)

    _a  :       Dict             =	trainer.train(resume_from_checkpoint=UpperCamelCase__				)
    trainer.save_model()

    _a  :       int             =	train_result.metrics
    _a  :       int             =	(
        data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCamelCase__				)
    )
    _a  :       str             =	min(UpperCamelCase__     ,   len(UpperCamelCase__				)				)

    trainer.log_metrics("""train"""     ,   UpperCamelCase__				)
    trainer.save_metrics("""train"""     ,   UpperCamelCase__				)
    trainer.save_state()

  # Evaluation
  _a  :       str             =	{}
  if training_args.do_eval:
    logger.info("""*** Evaluate ***"""				)
    _a  :       Any             =	trainer.evaluate()
    _a  :       Union[str, Any]             =	data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCamelCase__				)
    _a  :       List[Any]             =	min(UpperCamelCase__     ,   len(UpperCamelCase__				)				)

    trainer.log_metrics("""eval"""     ,   UpperCamelCase__				)
    trainer.save_metrics("""eval"""     ,   UpperCamelCase__				)

  return results


if __name__ == "__main__":
 main()









"""simple docstring"""




import warnings

from ...utils import logging
from .image_processing_clip import CLIPImageProcessor


_snake_case          =   logging.get_logger(__name__)






class        UpperCamelCase			(	snake_case_      ):


 def __init__(     self		:						Any							,						*UpperCAmelCase__		:						Optional[Any]							,						**UpperCAmelCase__		:						Tuple							)					->       None:
   warnings.warn(
       """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
       """ use CLIPImageProcessor instead."""							,						UpperCAmelCase__							,						)
   super().__init__(*UpperCAmelCase__							,						**UpperCAmelCase__							)

