





'''simple docstring'''





import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


SCREAMING_SNAKE_CASE_		     = re.compile(r"""\b(a|an|the)\b""", re.UNICODE)

SCREAMING_SNAKE_CASE_		     = None



def      __lowercase     (   )				->     Any:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0."""			)
      parser.add_argument("""data_file"""				,		metavar="""data.json"""				,		help="""Input data JSON file."""			)
      parser.add_argument("""pred_file"""				,		metavar="""pred.json"""				,		help="""Model predictions."""			)
      parser.add_argument(
          """--out-file"""				,		"""-o"""				,		metavar="""eval.json"""				,		help="""Write accuracy metrics to file (default is stdout)."""			)
      parser.add_argument(
          """--na-prob-file"""				,		"""-n"""				,		metavar="""na_prob.json"""				,		help="""Model estimates of probability of no answer."""			)
      parser.add_argument(
          """--na-prob-thresh"""				,		"""-t"""				,		type=lowerCAmelCase_				,		default=1.0				,		help="""Predict \"\" if no-answer probability exceeds this (default = 1.0)."""				,		)
      parser.add_argument(
          """--out-image-dir"""				,		"""-p"""				,		metavar="""out_images"""				,		default=lowerCAmelCase_				,		help="""Save precision-recall curves to directory."""			)
      parser.add_argument("""--verbose"""				,		"""-v"""				,		action="""store_true"""			)
      if len(sys.argv			) == 1:
            parser.print_help()
            sys.exit(1			)
      return parser.parse_args()



def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     List[Any]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		{}
      for article in dataset:
            for p in article["paragraphs"]:
                  for qa in p["qas"]:
                        SCREAMING_SNAKE_CASE	=		bool(qa["""answers"""]["""text"""]			)
      return qid_to_has_ans



def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     Optional[int]:


      '''simple docstring'''


      def remove_articles(_SCREAMING_SNAKE_CASE			):
            return ARTICLES_REGEX.sub(""" """				,		lowerCAmelCase_			)

      def white_space_fix(_SCREAMING_SNAKE_CASE			):
            return " ".join(text.split()			)

      def remove_punc(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		set(string.punctuation			)
            return "".join(ch for ch in text if ch not in exclude			)

      def lower(_SCREAMING_SNAKE_CASE			):
            return text.lower()

      return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_			)			)			)			)



def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     Optional[Any]:


      '''simple docstring'''


      if not s:
            return []
      return normalize_answer(lowerCAmelCase_			).split()



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     str:


      '''simple docstring'''


      return int(normalize_answer(lowerCAmelCase_			) == normalize_answer(lowerCAmelCase_			)			)



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     List[str]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		get_tokens(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		get_tokens(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		collections.Counter(lowerCAmelCase_			) & collections.Counter(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		sum(common.values()			)
      if len(lowerCAmelCase_			) == 0 or len(lowerCAmelCase_			) == 0:
            # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
            return int(gold_toks == pred_toks			)
      if num_same == 0:
            return 0
      SCREAMING_SNAKE_CASE	=		1.0 * num_same / len(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		1.0 * num_same / len(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		(2 * precision * recall) / (precision + recall)
      return fa



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     int:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		{}
      SCREAMING_SNAKE_CASE	=		{}
      for article in dataset:
            for p in article["paragraphs"]:
                  for qa in p["qas"]:
                        SCREAMING_SNAKE_CASE	=		qa['''id''']
                        SCREAMING_SNAKE_CASE	=		[t for t in qa['''answers''']['''text'''] if normalize_answer(lowerCAmelCase_			)]
                        if not gold_answers:
                              # For unanswerable questions, only correct answer is empty string
                              SCREAMING_SNAKE_CASE	=		['''''']
                        if qid not in preds:
                              print(F"""Missing prediction for {qid}"""			)
                              continue
                        SCREAMING_SNAKE_CASE	=		preds[qid]
                        # Take max over all gold answers
                        SCREAMING_SNAKE_CASE	=		max(compute_exact(lowerCAmelCase_				,		lowerCAmelCase_			) for a in gold_answers			)
                        SCREAMING_SNAKE_CASE	=		max(compute_fa(lowerCAmelCase_				,		lowerCAmelCase_			) for a in gold_answers			)
      return exact_scores, fa_scores



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Optional[int]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		{}
      for qid, s in scores.items():
            SCREAMING_SNAKE_CASE	=		na_probs[qid] > na_prob_thresh
            if pred_na:
                  SCREAMING_SNAKE_CASE	=		float(not qid_to_has_ans[qid]			)
            else:
                  SCREAMING_SNAKE_CASE	=		s
      return new_scores



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE=None			)				->     List[Any]:


      '''simple docstring'''


      if not qid_list:
            SCREAMING_SNAKE_CASE	=		len(lowerCAmelCase_			)
            return collections.OrderedDict(
                [
                    ("""exact""", 100.0 * sum(exact_scores.values()			) / total),
                    ("""f1""", 100.0 * sum(fa_scores.values()			) / total),
                    ("""total""", total),
                ]			)
      else:
            SCREAMING_SNAKE_CASE	=		len(lowerCAmelCase_			)
            return collections.OrderedDict(
                [
                    ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list			) / total),
                    ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list			) / total),
                    ("""total""", total),
                ]			)



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


      '''simple docstring'''


      for k in new_eval:
            SCREAMING_SNAKE_CASE	=		new_eval[k]



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     List[str]:


      '''simple docstring'''


      plt.step(lowerCAmelCase_				,		lowerCAmelCase_				,		color="""b"""				,		alpha=0.2				,		where="""post"""			)
      plt.fill_between(lowerCAmelCase_				,		lowerCAmelCase_				,		step="""post"""				,		alpha=0.2				,		color="""b"""			)
      plt.xlabel("""Recall"""			)
      plt.ylabel("""Precision"""			)
      plt.xlim([0.0, 1.05]			)
      plt.ylim([0.0, 1.05]			)
      plt.title(lowerCAmelCase_			)
      plt.savefig(lowerCAmelCase_			)
      plt.clf()



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE=None				,		_SCREAMING_SNAKE_CASE=None			)				->     List[str]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		sorted(lowerCAmelCase_				,		key=lambda _SCREAMING_SNAKE_CASE			: na_probs[k]			)
      SCREAMING_SNAKE_CASE	=		0.0
      SCREAMING_SNAKE_CASE	=		1.0
      SCREAMING_SNAKE_CASE	=		0.0
      SCREAMING_SNAKE_CASE	=		[1.0]
      SCREAMING_SNAKE_CASE	=		[0.0]
      SCREAMING_SNAKE_CASE	=		0.0
      for i, qid in enumerate(lowerCAmelCase_			):
            if qid_to_has_ans[qid]:
                  true_pos += scores[qid]
            SCREAMING_SNAKE_CASE	=		true_pos / float(i + 1			)
            SCREAMING_SNAKE_CASE	=		true_pos / float(lowerCAmelCase_			)
            if i == len(lowerCAmelCase_			) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
                  # i.e., if we can put a threshold after this point
                  avg_prec += cur_p * (cur_r - recalls[-1])
                  precisions.append(lowerCAmelCase_			)
                  recalls.append(lowerCAmelCase_			)
      if out_image:
            plot_pr_curve(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_			)
      return {"ap": 100.0 * avg_prec}



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     str:


      '''simple docstring'''


      if out_image_dir and not os.path.exists(lowerCAmelCase_			):
            os.makedirs(lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		sum(1 for v in qid_to_has_ans.values() if v			)
      if num_true_pos == 0:
            return
      SCREAMING_SNAKE_CASE	=		make_precision_recall_eval(
          lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		out_image=os.path.join(lowerCAmelCase_				,		"""pr_exact.png"""			)				,		title="""Precision-Recall curve for Exact Match score"""				,		)
      SCREAMING_SNAKE_CASE	=		make_precision_recall_eval(
          lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		out_image=os.path.join(lowerCAmelCase_				,		"""pr_f1.png"""			)				,		title="""Precision-Recall curve for F1 score"""				,		)
      SCREAMING_SNAKE_CASE	=		{k: float(lowerCAmelCase_			) for k, v in qid_to_has_ans.items()}
      SCREAMING_SNAKE_CASE	=		make_precision_recall_eval(
          lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		out_image=os.path.join(lowerCAmelCase_				,		"""pr_oracle.png"""			)				,		title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"""				,		)
      merge_eval(lowerCAmelCase_				,		lowerCAmelCase_				,		"""pr_exact"""			)
      merge_eval(lowerCAmelCase_				,		lowerCAmelCase_				,		"""pr_f1"""			)
      merge_eval(lowerCAmelCase_				,		lowerCAmelCase_				,		"""pr_oracle"""			)



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Optional[Any]:


      '''simple docstring'''


      if not qid_list:
            return
      SCREAMING_SNAKE_CASE	=		[na_probs[k] for k in qid_list]
      SCREAMING_SNAKE_CASE	=		np.ones_like(lowerCAmelCase_			) / float(len(lowerCAmelCase_			)			)
      plt.hist(lowerCAmelCase_				,		weights=lowerCAmelCase_				,		bins=20				,		range=(0.0, 1.0)			)
      plt.xlabel("""Model probability of no-answer"""			)
      plt.ylabel("""Proportion of dataset"""			)
      plt.title(F"""Histogram of no-answer probability: {name}"""			)
      plt.savefig(os.path.join(lowerCAmelCase_				,		F"""na_prob_hist_{name}.png"""			)			)
      plt.clf()



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Dict:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]			)
      SCREAMING_SNAKE_CASE	=		num_no_ans
      SCREAMING_SNAKE_CASE	=		cur_score
      SCREAMING_SNAKE_CASE	=		0.0
      SCREAMING_SNAKE_CASE	=		sorted(lowerCAmelCase_				,		key=lambda _SCREAMING_SNAKE_CASE			: na_probs[k]			)
      for i, qid in enumerate(lowerCAmelCase_			):
            if qid not in scores:
                  continue
            if qid_to_has_ans[qid]:
                  SCREAMING_SNAKE_CASE	=		scores[qid]
            else:
                  if preds[qid]:
                        SCREAMING_SNAKE_CASE	=		-1
                  else:
                        SCREAMING_SNAKE_CASE	=		0
            cur_score += diff
            if cur_score > best_score:
                  SCREAMING_SNAKE_CASE	=		cur_score
                  SCREAMING_SNAKE_CASE	=		na_probs[qid]
      return 100.0 * best_score / len(lowerCAmelCase_			), best_thresh



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Dict:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		find_best_thresh(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		find_best_thresh(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		best_exact
      SCREAMING_SNAKE_CASE	=		exact_thresh
      SCREAMING_SNAKE_CASE	=		best_fa
      SCREAMING_SNAKE_CASE	=		fa_thresh



def      __lowercase     (   )				->     Tuple:


      '''simple docstring'''


      with open(OPTS.data_file			) as f:
            SCREAMING_SNAKE_CASE	=		json.load(lowerCAmelCase_			)
            SCREAMING_SNAKE_CASE	=		dataset_json['''data''']
      with open(OPTS.pred_file			) as f:
            SCREAMING_SNAKE_CASE	=		json.load(lowerCAmelCase_			)
      if OPTS.na_prob_file:
            with open(OPTS.na_prob_file			) as f:
                  SCREAMING_SNAKE_CASE	=		json.load(lowerCAmelCase_			)
      else:
            SCREAMING_SNAKE_CASE	=		{k: 0.0 for k in preds}
      SCREAMING_SNAKE_CASE	=		make_qid_to_has_ans(lowerCAmelCase_			)  # maps qid to True/False
      SCREAMING_SNAKE_CASE	=		[k for k, v in qid_to_has_ans.items() if v]
      SCREAMING_SNAKE_CASE	=		[k for k, v in qid_to_has_ans.items() if not v]
      SCREAMING_SNAKE_CASE	=		get_raw_scores(lowerCAmelCase_				,		lowerCAmelCase_			)
      SCREAMING_SNAKE_CASE	=		apply_no_ans_threshold(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		OPTS.na_prob_thresh			)
      SCREAMING_SNAKE_CASE	=		apply_no_ans_threshold(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		OPTS.na_prob_thresh			)
      SCREAMING_SNAKE_CASE	=		make_eval_dict(lowerCAmelCase_				,		lowerCAmelCase_			)
      if has_ans_qids:
            SCREAMING_SNAKE_CASE	=		make_eval_dict(lowerCAmelCase_				,		lowerCAmelCase_				,		qid_list=lowerCAmelCase_			)
            merge_eval(lowerCAmelCase_				,		lowerCAmelCase_				,		"""HasAns"""			)
      if no_ans_qids:
            SCREAMING_SNAKE_CASE	=		make_eval_dict(lowerCAmelCase_				,		lowerCAmelCase_				,		qid_list=lowerCAmelCase_			)
            merge_eval(lowerCAmelCase_				,		lowerCAmelCase_				,		"""NoAns"""			)
      if OPTS.na_prob_file:
            find_all_best_thresh(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_			)
      if OPTS.na_prob_file and OPTS.out_image_dir:
            run_precision_recall_analysis(lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		lowerCAmelCase_				,		OPTS.out_image_dir			)
            histogram_na_prob(lowerCAmelCase_				,		lowerCAmelCase_				,		OPTS.out_image_dir				,		"""hasAns"""			)
            histogram_na_prob(lowerCAmelCase_				,		lowerCAmelCase_				,		OPTS.out_image_dir				,		"""noAns"""			)
      if OPTS.out_file:
            with open(OPTS.out_file				,		"""w"""			) as f:
                  json.dump(lowerCAmelCase_				,		lowerCAmelCase_			)
      else:
            print(json.dumps(lowerCAmelCase_				,		indent=2			)			)


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE_		     = parse_args()
      if OPTS.out_image_dir:
            import matplotlib

            matplotlib.use("""Agg""")
            import matplotlib.pyplot as plt
      main()









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

SCREAMING_SNAKE_CASE_		     = logging.getLogger(__name__)



def      __lowercase     (   _SCREAMING_SNAKE_CASE=None				,		_SCREAMING_SNAKE_CASE=None			)				->     int:


      '''simple docstring'''


      return field(default_factory=lambda: default				,		metadata=_SCREAMING_SNAKE_CASE			)

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

     __snake_case					:			Optional[str]				=    field(
         default=lowerCAmelCase_							,   metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}     )
     __snake_case					:			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'"
         }							,   )
     __snake_case					:			bool				=    field(
         default=lowerCAmelCase_							,   metadata={"help": "Overwrite the cached preprocessed datasets or not."}     )
     __snake_case					:			Optional[int]				=    field(
         default=lowerCAmelCase_							,   metadata={"help": "The number of processes to use for the preprocessing."}							,   )
     __snake_case					:			Optional[int]				=    field(
         default=lowerCAmelCase_							,   metadata={
             "help": (
                 "For debugging purposes or quicker training, truncate the number of training examples to this "
                 "value if set."
             )
         }							,   )
     __snake_case					:			Optional[int]				=    field(
         default=lowerCAmelCase_							,   metadata={
             "help": (
                 "For debugging purposes or quicker training, truncate the number of validation examples to this "
                 "value if set."
             )
         }							,   )
     __snake_case					:			List[str]				=    list_field(
         default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"]							,   metadata={"help": "A list of characters to remove from the transcripts."}							,   )

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

     __snake_case					:			WavaVecaProcessor
     __snake_case					:			Union[bool, str]				=    True
     __snake_case					:			Optional[int]				=    None
     __snake_case					:			Optional[int]				=    None
     __snake_case					:			Optional[int]				=    None
     __snake_case					:			Optional[int]				=    None






     def __call__(							self		:					Any		,lowerCamelCase__		:					List[Dict[str, Union[List[int], torch.Tensor]]] )  ->	Dict[str, torch.Tensor]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		[{"""input_values""": feature["""input_values"""]} for feature in features]
           SCREAMING_SNAKE_CASE	=		[{"""input_ids""": feature["""labels"""]} for feature in features]

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

           SCREAMING_SNAKE_CASE	=		labels

           return batch

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					nn.Module		,lowerCamelCase__		:					Dict[str, Union[torch.Tensor, Any]] )  ->	torch.Tensor:




           '''simple docstring'''


           model.train()
           SCREAMING_SNAKE_CASE	=		self._prepare_inputs(lowerCamelCase__ )

           if self.use_amp:
                 with autocast():
                       SCREAMING_SNAKE_CASE	=		self.compute_loss(lowerCamelCase__		,lowerCamelCase__ )
           else:
                 SCREAMING_SNAKE_CASE	=		self.compute_loss(lowerCamelCase__		,lowerCamelCase__ )

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


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		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.
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
      else:
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      SCREAMING_SNAKE_CASE	=		None
      if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
            SCREAMING_SNAKE_CASE	=		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"""				,		_SCREAMING_SNAKE_CASE			)

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

      # Get the datasets:
      SCREAMING_SNAKE_CASE	=		datasets.load_dataset(
          """common_voice"""				,		data_args.dataset_config_name				,		split=data_args.train_split_name			)
      SCREAMING_SNAKE_CASE	=		datasets.load_dataset("""common_voice"""				,		data_args.dataset_config_name				,		split="""test"""			)

      # Create and save tokenizer
      SCREAMING_SNAKE_CASE	=		F"""[{''.join(data_args.chars_to_ignore			)}]"""

      def remove_special_characters(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		re.sub(_SCREAMING_SNAKE_CASE				,		""""""				,		batch["""sentence"""]			).lower() + """ """
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)

      def extract_all_chars(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		""" """.join(batch["""text"""]			)
            SCREAMING_SNAKE_CASE	=		list(set(_SCREAMING_SNAKE_CASE			)			)
            return {"vocab": [vocab], "all_text": [all_text]}

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		batched=_SCREAMING_SNAKE_CASE				,		batch_size=-1				,		keep_in_memory=_SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		)
      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		batched=_SCREAMING_SNAKE_CASE				,		batch_size=-1				,		keep_in_memory=_SCREAMING_SNAKE_CASE				,		remove_columns=eval_dataset.column_names				,		)

      SCREAMING_SNAKE_CASE	=		list(set(vocab_train["""vocab"""][0]			) | set(vocab_test["""vocab"""][0]			)			)
      SCREAMING_SNAKE_CASE	=		{v: k for k, v in enumerate(_SCREAMING_SNAKE_CASE			)}
      SCREAMING_SNAKE_CASE	=		vocab_dict[""" """]
      del vocab_dict[" "]
      SCREAMING_SNAKE_CASE	=		len(_SCREAMING_SNAKE_CASE			)
      SCREAMING_SNAKE_CASE	=		len(_SCREAMING_SNAKE_CASE			)

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

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

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

      SCREAMING_SNAKE_CASE	=		torchaudio.transforms.Resample(4_80_00				,		1_60_00			)

      # 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			):
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		torchaudio.load(batch["""path"""]			)
            SCREAMING_SNAKE_CASE	=		resampler(_SCREAMING_SNAKE_CASE			).squeeze().numpy()
            SCREAMING_SNAKE_CASE	=		1_60_00
            SCREAMING_SNAKE_CASE	=		batch["""text"""]
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		num_proc=data_args.preprocessing_num_workers				,		)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(
          _SCREAMING_SNAKE_CASE				,		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}."""

            SCREAMING_SNAKE_CASE	=		processor(
                audio=batch["""speech"""]				,		text=batch["""target_text"""]				,		sampling_rate=batch["""sampling_rate"""][0]			)
            batch.update(_SCREAMING_SNAKE_CASE			)
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		batch_size=training_args.per_device_train_batch_size				,		batched=_SCREAMING_SNAKE_CASE				,		num_proc=data_args.preprocessing_num_workers				,		)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=eval_dataset.column_names				,		batch_size=training_args.per_device_train_batch_size				,		batched=_SCREAMING_SNAKE_CASE				,		num_proc=data_args.preprocessing_num_workers				,		)

      # Metric
      SCREAMING_SNAKE_CASE	=		datasets.load_metric("""wer"""			)

      def compute_metrics(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		pred.predictions
            SCREAMING_SNAKE_CASE	=		np.argmax(_SCREAMING_SNAKE_CASE				,		axis=-1			)

            SCREAMING_SNAKE_CASE	=		processor.tokenizer.pad_token_id

            SCREAMING_SNAKE_CASE	=		processor.batch_decode(_SCREAMING_SNAKE_CASE			)
            # we do not want to group tokens when computing the metrics
            SCREAMING_SNAKE_CASE	=		processor.batch_decode(pred.label_ids				,		group_tokens=_SCREAMING_SNAKE_CASE			)

            SCREAMING_SNAKE_CASE	=		wer_metric.compute(predictions=_SCREAMING_SNAKE_CASE				,		references=_SCREAMING_SNAKE_CASE			)

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      SCREAMING_SNAKE_CASE	=		DataCollatorCTCWithPadding(processor=_SCREAMING_SNAKE_CASE				,		padding=_SCREAMING_SNAKE_CASE			)

      # Initialize our Trainer
      SCREAMING_SNAKE_CASE	=		CTCTrainer(
          model=_SCREAMING_SNAKE_CASE				,		data_collator=_SCREAMING_SNAKE_CASE				,		args=_SCREAMING_SNAKE_CASE				,		compute_metrics=_SCREAMING_SNAKE_CASE				,		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:
                  SCREAMING_SNAKE_CASE	=		last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path			):
                  SCREAMING_SNAKE_CASE	=		model_args.model_name_or_path
            else:
                  SCREAMING_SNAKE_CASE	=		None

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

            SCREAMING_SNAKE_CASE	=		trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE			)
            trainer.save_model()

            SCREAMING_SNAKE_CASE	=		train_result.metrics
            SCREAMING_SNAKE_CASE	=		(
                data_args.max_train_samples if data_args.max_train_samples is not None else len(_SCREAMING_SNAKE_CASE			)
            )
            SCREAMING_SNAKE_CASE	=		min(_SCREAMING_SNAKE_CASE				,		len(_SCREAMING_SNAKE_CASE			)			)

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

      # Evaluation
      SCREAMING_SNAKE_CASE	=		{}
      if training_args.do_eval:
            logger.info("""*** Evaluate ***"""			)
            SCREAMING_SNAKE_CASE	=		trainer.evaluate()
            SCREAMING_SNAKE_CASE	=		data_args.max_val_samples if data_args.max_val_samples is not None else len(_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		min(_SCREAMING_SNAKE_CASE				,		len(_SCREAMING_SNAKE_CASE			)			)

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

      return results


if __name__ == "__main__":
      main()


