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

lowercase__					       =	logging.getLogger(__name__)







def 						__a   (	_SCREAMING_SNAKE_CASE=None		,     _SCREAMING_SNAKE_CASE=None   )	->Tuple:
  return field(default_factory=lambda: default		,     metadata=_lowerCAmelCase   )




@dataclass
class    __snake_case       :
      a__        =		field(
          metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}				)
      a__        =		field(
          default=SCREAMING_SNAKE_CASE__       ,      metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}       ,      )
      a__        =		field(
          default=SCREAMING_SNAKE_CASE__       ,      metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}				)
      a__        =		field(
          default=0.1       ,      metadata={"""help""": """The dropout ratio for the attention probabilities."""}				)
      a__        =		field(
          default=0.1       ,      metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""}				)
      a__        =		field(
          default=0.1       ,      metadata={
              """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
          }       ,      )
      a__        =		field(
          default=0.1       ,      metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""}       ,      )
      a__        =		field(
          default=0.05       ,      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``."""
              )
          }       ,      )
      a__        =		field(default=0.0       ,      metadata={"""help""": """The LayerDrop probability."""}				)







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







@dataclass
class    __snake_case       :
      a__        =		42
      a__        =		True
      a__        =		None
      a__        =		None
      a__        =		None
      a__        =		None



      def __call__(						self    ,			lowercase)	->			Union[str, Any]:





        '''simple docstring'''





        a__:     Optional[int]										=	[{"""input_values""": feature["""input_values"""]} for feature in features]
        a__:     Union[str, Any]										=	[{"""input_ids""": feature["""labels"""]} for feature in features]

        a__:     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'    ,			)
        a__:     str										=	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
        a__:     str										=	labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1)    ,			-1_00)

        a__:     Any										=	labels

        return batch







class    __snake_case       (     SCREAMING_SNAKE_CASE__				):



      def   lowerCamelCase_   (						self    ,			lowercase    ,			lowercase)	->			List[Any]:





        '''simple docstring'''





        model.train()
        a__:     Union[str, Any]										=	self._prepare_inputs(lowerCamelCase__)

        if self.use_amp:
          with autocast():
            a__:     Union[str, Any]										=	self.compute_loss(lowerCamelCase__    ,			lowerCamelCase__)
        else:
          a__:     Optional[int]										=	self.compute_loss(lowerCamelCase__    ,			lowerCamelCase__)

        if self.args.n_gpu > 1:
          if model.module.config.ctc_loss_reduction == "mean":
            a__:     str										=	loss.mean()
          elif model.module.config.ctc_loss_reduction == "sum":
            a__:     Tuple										=	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__:     Tuple										=	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 						__a   (	)	->List[str]:
  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__:     int										=	parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
  else:
    a__:     Union[str, Any]										=	parser.parse_args_into_dataclasses()

  # Detecting last checkpoint.
  a__:     str										=	None
  if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
    a__:     int										=	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'		,     _lowerCAmelCase   )

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

  # Get the datasets:
  a__:     Union[str, Any]										=	datasets.load_dataset(
      'common_voice'		,     data_args.dataset_config_name		,     split=data_args.train_split_name   )
  a__:     Any										=	datasets.load_dataset('common_voice'		,     data_args.dataset_config_name		,     split='test'   )

  # Create and save tokenizer
  a__:     List[Any]										=	F'[{"".join(data_args.chars_to_ignore   )}]'

  def remove_special_characters(_SCREAMING_SNAKE_CASE   ):
    a__:     List[Any]										=	re.sub(_lowerCAmelCase		,     ''		,     batch['sentence']   ).lower() + """ """
    return batch

  a__:     Dict										=	train_dataset.map(_lowerCAmelCase		,     remove_columns=['sentence']   )
  a__:     Optional[Any]										=	eval_dataset.map(_lowerCAmelCase		,     remove_columns=['sentence']   )

  def extract_all_chars(_SCREAMING_SNAKE_CASE   ):
    a__:     Dict										=	""" """.join(batch['text']   )
    a__:     List[str]										=	list(set(_lowerCAmelCase   )   )
    return {"vocab": [vocab], "all_text": [all_text]}

  a__:     str										=	train_dataset.map(
      _lowerCAmelCase		,     batched=_lowerCAmelCase		,     batch_size=-1		,     keep_in_memory=_lowerCAmelCase		,     remove_columns=train_dataset.column_names		,     )
  a__:     Tuple										=	train_dataset.map(
      _lowerCAmelCase		,     batched=_lowerCAmelCase		,     batch_size=-1		,     keep_in_memory=_lowerCAmelCase		,     remove_columns=eval_dataset.column_names		,     )

  a__:     List[Any]										=	list(set(vocab_train['vocab'][0]   ) | set(vocab_test['vocab'][0]   )   )
  a__:     Optional[Any]										=	{v: k for k, v in enumerate(_lowerCAmelCase   )}
  a__:     Dict										=	vocab_dict[""" """]
  del vocab_dict[" "]
  a__:     Union[str, Any]										=	len(_lowerCAmelCase   )
  a__:     Optional[int]										=	len(_lowerCAmelCase   )

  with open('vocab.json'		,     'w'   ) as vocab_file:
    json.dump(_lowerCAmelCase		,     _lowerCAmelCase   )

  # Load pretrained model and tokenizer
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.
  a__:     Tuple										=	WavaVecaCTCTokenizer(
      'vocab.json'		,     unk_token='[UNK]'		,     pad_token='[PAD]'		,     word_delimiter_token='|'		,     )
  a__:     Optional[int]										=	WavaVecaFeatureExtractor(
      feature_size=1		,     sampling_rate=16000		,     padding_value=0.0		,     do_normalize=_lowerCAmelCase		,     return_attention_mask=_lowerCAmelCase   )
  a__:     Any										=	WavaVecaProcessor(feature_extractor=_lowerCAmelCase		,     tokenizer=_lowerCAmelCase   )
  a__:     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__:     List[Any]										=	min(len(_lowerCAmelCase   )		,     data_args.max_train_samples   )
    a__:     Dict										=	train_dataset.select(range(_lowerCAmelCase   )   )

  if data_args.max_val_samples is not None:
    a__:     Dict										=	eval_dataset.select(range(data_args.max_val_samples   )   )

  a__:     Any										=	torchaudio.transforms.Resample(48000		,     16000   )

  # Preprocessing the datasets.
  # We need to read the aduio files as arrays and tokenize the targets.
  def speech_file_to_array_fn(_SCREAMING_SNAKE_CASE   ):
    a__:     Optional[Any]										=	torchaudio.load(batch['path']   )
    a__:     Optional[int]										=	resampler(_lowerCAmelCase   ).squeeze().numpy()
    a__:     Optional[Any]										=	16000
    a__:     Optional[Any]										=	batch["""text"""]
    return batch

  a__:     Tuple										=	train_dataset.map(
      _lowerCAmelCase		,     remove_columns=train_dataset.column_names		,     num_proc=data_args.preprocessing_num_workers		,     )
  a__:     List[str]										=	eval_dataset.map(
      _lowerCAmelCase		,     remove_columns=eval_dataset.column_names		,     num_proc=data_args.preprocessing_num_workers		,     )

  def prepare_dataset(_SCREAMING_SNAKE_CASE   ):
    # 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__:     int										=	processor(
        audio=batch['speech']		,     text=batch['target_text']		,     sampling_rate=batch['sampling_rate'][0]   )
    batch.update(_lowerCAmelCase   )
    return batch

  a__:     str										=	train_dataset.map(
      _lowerCAmelCase		,     remove_columns=train_dataset.column_names		,     batch_size=training_args.per_device_train_batch_size		,     batched=_lowerCAmelCase		,     num_proc=data_args.preprocessing_num_workers		,     )
  a__:     Union[str, Any]										=	eval_dataset.map(
      _lowerCAmelCase		,     remove_columns=eval_dataset.column_names		,     batch_size=training_args.per_device_train_batch_size		,     batched=_lowerCAmelCase		,     num_proc=data_args.preprocessing_num_workers		,     )

  # Metric
  a__:     List[str]										=	datasets.load_metric('wer'   )

  def compute_metrics(_SCREAMING_SNAKE_CASE   ):
    a__:     int										=	pred.predictions
    a__:     Tuple										=	np.argmax(_lowerCAmelCase		,     axis=-1   )

    a__:     List[Any]										=	processor.tokenizer.pad_token_id

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

    a__:     Optional[int]										=	wer_metric.compute(predictions=_lowerCAmelCase		,     references=_lowerCAmelCase   )

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  # Data collator
  a__:     int										=	DataCollatorCTCWithPadding(processor=_lowerCAmelCase		,     padding=_lowerCAmelCase   )

  # Initialize our Trainer
  a__:     int										=	CTCTrainer(
      model=_lowerCAmelCase		,     data_collator=_lowerCAmelCase		,     args=_lowerCAmelCase		,     compute_metrics=_lowerCAmelCase		,     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__:     Dict										=	last_checkpoint
    elif os.path.isdir(model_args.model_name_or_path   ):
      a__:     Optional[Any]										=	model_args.model_name_or_path
    else:
      a__:     Tuple										=	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=_lowerCAmelCase   )
    trainer.save_model()

    a__:     str										=	train_result.metrics
    a__:     Tuple										=	(
        data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCAmelCase   )
    )
    a__:     List[str]										=	min(_lowerCAmelCase		,     len(_lowerCAmelCase   )   )

    trainer.log_metrics('train'		,     _lowerCAmelCase   )
    trainer.save_metrics('train'		,     _lowerCAmelCase   )
    trainer.save_state()

  # Evaluation
  a__:     Optional[int]										=	{}
  if training_args.do_eval:
    logger.info('*** Evaluate ***'   )
    a__:     List[str]										=	trainer.evaluate()
    a__:     int										=	data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowerCAmelCase   )
    a__:     str										=	min(_lowerCAmelCase		,     len(_lowerCAmelCase   )   )

    trainer.log_metrics('eval'		,     _lowerCAmelCase   )
    trainer.save_metrics('eval'		,     _lowerCAmelCase   )

  return results


if __name__ == "__main__":
 main()







from collections import defaultdict
from pathlib import Path

import pandas as pd
from rouge_cli import calculate_rouge_path

from utils import calculate_rouge


SCREAMING_SNAKE_CASE_:Any             =						[
    """Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the"""
    """ final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe"""
    """ depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.""",
    """The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal"""
    """ accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's"""
    """ founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the"""
    """ body.""",
    """Amnesty International releases its annual report on the death penalty. The report catalogs the use of"""
    """ state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the"""
    """ world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital"""
    """ punishment.""",
]

SCREAMING_SNAKE_CASE_:Optional[int]             =						[
    """Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ."""
    """ Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz"""
    """ had informed his Lufthansa training school of an episode of severe depression, airline says .""",
    """Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ."""
    """ Israel and the United States opposed the move, which could open the door to war crimes investigations against"""
    """ Israelis .""",
    """Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to"""
    """ death . Organization claims that governments around the world are using the threat of terrorism to advance"""
    """ executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death"""
    """ sentences up by 28% .""",
]




def 	__UpperCamelCase	(  )       ->  Optional[Any]:



    """simple docstring"""






    A :       Tuple          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     bootstrap_aggregation=_lowerCAmelCase      ,     rouge_keys=["""rouge2""", """rougeL"""]		)
    assert isinstance(_lowerCAmelCase      ,     _lowerCAmelCase		)
    A :       Tuple          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     bootstrap_aggregation=_lowerCAmelCase      ,     rouge_keys=["""rouge2"""]		)
    assert (
        pd.DataFrame(no_aggregation["""rouge2"""]		).fmeasure.mean()
        == pd.DataFrame(no_aggregation_just_ra["""rouge2"""]		).fmeasure.mean()
    )




def 	__UpperCamelCase	(  )       ->  List[Any]:



    """simple docstring"""






    A :       Dict          =   """rougeLsum"""
    A :       str          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase      ,     rouge_keys=[k]		)[k]
    A :       Tuple          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase      ,     rouge_keys=[k]		)[k]
    assert score > score_no_sep




def 	__UpperCamelCase	(  )       ->  Tuple:



    """simple docstring"""






    A :       Union[str, Any]          =   ["""rouge1""", """rouge2""", """rougeL"""]
    A :       Dict          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase      ,     rouge_keys=_lowerCAmelCase		)
    A :       List[str]          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase      ,     rouge_keys=_lowerCAmelCase		)
    assert score_sep == score_no_sep




def 	__UpperCamelCase	(  )       ->  Optional[Any]:



    """simple docstring"""






    A :       Optional[Any]          =   [
        """Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.""",
        """Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .""",
    ]
    A :       Optional[Any]          =   [
        """Margot Frank, died in 1945, a month earlier than previously thought.""",
        """Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of"""
        """ the final seconds on board Flight 9525.""",
    ]
    assert calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase		) == calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     newline_sep=_lowerCAmelCase		)




def 	__UpperCamelCase	(  )       ->  List[Any]:



    """simple docstring"""






    A :       Tuple          =   [
        """\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" """
    ]
    A :       Union[str, Any]          =   [
        """ Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ."""
    ]

    A :       int          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     rouge_keys=["""rougeLsum"""]      ,     newline_sep=_lowerCAmelCase		)["""rougeLsum"""]
    A :       Optional[Any]          =   calculate_rouge(_lowerCAmelCase      ,     _lowerCAmelCase      ,     rouge_keys=["""rougeLsum"""]		)["""rougeLsum"""]
    assert new_score > prev_score




def 	__UpperCamelCase	(  )       ->  Any:



    """simple docstring"""






    A :       Tuple          =   Path("""examples/seq2seq/test_data/wmt_en_ro"""		)
    A :       Optional[Any]          =   calculate_rouge_path(data_dir.joinpath("""test.source"""		)      ,     data_dir.joinpath("""test.target"""		)		)
    assert isinstance(_lowerCAmelCase      ,     _lowerCAmelCase		)
    A :       List[Any]          =   calculate_rouge_path(
        data_dir.joinpath("""test.source"""		)      ,     data_dir.joinpath("""test.target"""		)      ,     bootstrap_aggregation=_lowerCAmelCase		)
    assert isinstance(_lowerCAmelCase      ,     _lowerCAmelCase		)


