


import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


__UpperCAmelCase    :int				       =     "bart"
__UpperCAmelCase    :Tuple				       =     True




@st.cache(allow_output_mutation=_lowercase						)
def 			_a			(		):





     '''simple docstring'''






     if LOAD_DENSE_INDEX:
          __UpperCAmelCase			:				Optional[int]													=    AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased'''						)
          __UpperCAmelCase			:				Dict													=    AutoModel.from_pretrained('''yjernite/retribert-base-uncased'''						).to('''cuda:0'''						)
          __UpperCAmelCase			:				List[Any]													=    qar_model.eval()
     else:
          __UpperCAmelCase			:				Any													=    (None, None)
     if MODEL_TYPE == "bart":
          __UpperCAmelCase			:				Optional[int]													=    AutoTokenizer.from_pretrained('''yjernite/bart_eli5'''						)
          __UpperCAmelCase			:				int													=    AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5'''						).to('''cuda:0'''						)
          __UpperCAmelCase			:				int													=    torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth'''						)
          sas_model.load_state_dict(save_dict['''model''']						)
          __UpperCAmelCase			:				str													=    sas_model.eval()
     else:
          __UpperCAmelCase			:				int													=    make_qa_sas_model(
              model_name='''t5-small'''    ,      from_file='''seq2seq_models/eli5_t5_model_1024_4.pth'''    ,      device='''cuda:0'''						)
     return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)




@st.cache(allow_output_mutation=_lowercase						)
def 			_a			(		):





     '''simple docstring'''






     if LOAD_DENSE_INDEX:
          __UpperCAmelCase			:				Optional[Any]													=    faiss.StandardGpuResources()
          __UpperCAmelCase			:				Union[str, Any]													=    datasets.load_dataset(path='''wiki_snippets'''    ,      name='''wiki40b_en_100_0'''						)['''train''']
          __UpperCAmelCase			:				int													=    np.memmap(
              '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat'''    ,      dtype='''float32'''    ,      mode='''r'''    ,      shape=(wikiaab_passages.num_rows, 128)    ,      )
          __UpperCAmelCase			:				int													=    faiss.IndexFlatIP(128						)
          __UpperCAmelCase			:				str													=    faiss.index_cpu_to_gpu(_lowercase    ,      1    ,      _lowercase						)
          wikiaab_gpu_index_flat.add(_lowercase						)  # TODO fix for larger GPU
     else:
          __UpperCAmelCase			:				Dict													=    (None, None)
     __UpperCAmelCase			:				Tuple													=    Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}]						)
     return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)




@st.cache(allow_output_mutation=_lowercase						)
def 			_a			(		):





     '''simple docstring'''






     __UpperCAmelCase			:				Union[str, Any]													=    datasets.load_dataset('''eli5'''    ,      name='''LFQA_reddit'''						)
     __UpperCAmelCase			:				Optional[int]													=    elia['''train_eli5''']
     __UpperCAmelCase			:				Optional[int]													=    np.memmap(
         '''eli5_questions_reps.dat'''    ,      dtype='''float32'''    ,      mode='''r'''    ,      shape=(elia_train.num_rows, 128)						)
     __UpperCAmelCase			:				Tuple													=    faiss.IndexFlatIP(128						)
     eli5_train_q_index.add(_lowercase						)
     return (elia_train, eli5_train_q_index)


__UpperCAmelCase    :Any				       =     load_indexes()
__UpperCAmelCase    :int				       =     load_models()
__UpperCAmelCase    :Dict				       =     load_train_data()




def 			_a			(		_lowercase      :			Union[str, Any]    ,      _lowercase      :			Union[str, Any]=10						):





     '''simple docstring'''






     __UpperCAmelCase			:				Union[str, Any]													=    embed_questions_for_retrieval([question]    ,      _lowercase    ,      _lowercase						)
     __UpperCAmelCase			:				Optional[Any]													=    eli5_train_q_index.search(_lowercase    ,      _lowercase						)
     __UpperCAmelCase			:				Tuple													=    [elia_train[int(_lowercase						)] for i in I[0]]
     return nn_examples




def 			_a			(		_lowercase      :			Optional[Any]    ,      _lowercase      :			Any="wiki40b"    ,      _lowercase      :			Tuple="dense"    ,      _lowercase      :			str=10						):





     '''simple docstring'''






     if source == "none":
          __UpperCAmelCase			:				Union[str, Any]													=    (''' <P> '''.join(['''''' for _ in range(11						)]						).strip(), [])
     else:
          if method == "dense":
               __UpperCAmelCase			:				Union[str, Any]													=    query_qa_dense_index(
                   _lowercase    ,      _lowercase    ,      _lowercase    ,      _lowercase    ,      _lowercase    ,      _lowercase						)
          else:
               __UpperCAmelCase			:				Tuple													=    query_es_index(
                   _lowercase    ,      _lowercase    ,      index_name='''english_wiki40b_snippets_100w'''    ,      n_results=_lowercase    ,      )
     __UpperCAmelCase			:				Optional[Any]													=    [
         (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
     ]
     __UpperCAmelCase			:				int													=    '''question: {} context: {}'''.format(_lowercase    ,      _lowercase						)
     return question_doc, support_list




@st.cache(
    hash_funcs={
        torch.Tensor: (lambda _lowercase						: None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowercase						: None),
    }						)
def 			_a			(		_lowercase      :			List[str]    ,      _lowercase      :			Any    ,      _lowercase      :			Tuple    ,      _lowercase      :			List[Any]=64    ,      _lowercase      :			Optional[int]=256    ,      _lowercase      :			Dict=False    ,      _lowercase      :			List[str]=2    ,      _lowercase      :			Union[str, Any]=0.95    ,      _lowercase      :			Tuple=0.8						):





     '''simple docstring'''






     with torch.no_grad():
          __UpperCAmelCase			:				Optional[int]													=    qa_sas_generate(
              _lowercase    ,      _lowercase    ,      _lowercase    ,      num_answers=1    ,      num_beams=_lowercase    ,      min_len=_lowercase    ,      max_len=_lowercase    ,      do_sample=_lowercase    ,      temp=_lowercase    ,      top_p=_lowercase    ,      top_k=_lowercase    ,      max_input_length=1024    ,      device='''cuda:0'''    ,      )[0]
     return (answer, support_list)


st.title("Long Form Question Answering with ELI5")

# Start sidebar
__UpperCAmelCase    :Tuple				       =     "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"
__UpperCAmelCase    :Optional[Any]				       =     "\n<html>\n  <head>\n    <style>\n      .img-container {\n        padding-left: 90px;\n        padding-right: 90px;\n        padding-top: 50px;\n        padding-bottom: 50px;\n        background-color: #f0f3f9;\n      }\n    </style>\n  </head>\n  <body>\n    <span class=\"img-container\"> <!-- Inline parent element -->\n      %s\n    </span>\n  </body>\n</html>\n" % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
__UpperCAmelCase    :Optional[int]				       =     "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n"
st.sidebar.markdown(description, unsafe_allow_html=True)

__UpperCAmelCase    :Any				       =     [
    "Answer the question",
    "View the retrieved document only",
    "View the most similar ELI5 question and answer",
    "Show me everything, please!",
]
__UpperCAmelCase    :str				       =     st.sidebar.checkbox("Demo options")
if demo_options:
      __UpperCAmelCase    :Optional[Any]				       =     st.sidebar.selectbox(
          "",
          action_list,
          index=3,
      )
      __UpperCAmelCase    :Optional[Any]				       =     action_list.index(action_st)
      __UpperCAmelCase    :Union[str, Any]				       =     st.sidebar.selectbox(
          "",
          ["Show full text of passages", "Show passage section titles"],
          index=0,
      )
      __UpperCAmelCase    :List[Any]				       =     show_type == "Show full text of passages"
else:
      __UpperCAmelCase    :List[str]				       =     3
      __UpperCAmelCase    :Union[str, Any]				       =     True

__UpperCAmelCase    :List[Any]				       =     st.sidebar.checkbox("Retrieval options")
if retrieval_options:
      __UpperCAmelCase    :Any				       =     "\n    ### Information retriever options\n\n    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n    "
      st.sidebar.markdown(retriever_info)
      __UpperCAmelCase    :Union[str, Any]				       =     st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"])
      __UpperCAmelCase    :Dict				       =     st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"])
else:
      __UpperCAmelCase    :int				       =     "wiki40b"
      __UpperCAmelCase    :Optional[int]				       =     "dense"

__UpperCAmelCase    :Optional[Any]				       =     "beam"
__UpperCAmelCase    :int				       =     2
__UpperCAmelCase    :Optional[int]				       =     6_4
__UpperCAmelCase    :Dict				       =     2_5_6
__UpperCAmelCase    :Optional[int]				       =     None
__UpperCAmelCase    :int				       =     None
__UpperCAmelCase    :Any				       =     st.sidebar.checkbox("Generation options")
if generate_options:
      __UpperCAmelCase    :List[str]				       =     "\n    ### Answer generation options\n\n    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n    **beam** search, or **sample** from the decoder's output probabilities.\n    "
      st.sidebar.markdown(generate_info)
      __UpperCAmelCase    :List[str]				       =     st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"])
      __UpperCAmelCase    :Union[str, Any]				       =     st.sidebar.slider(
          "Minimum generation length", min_value=8, max_value=2_5_6, value=6_4, step=8, format=None, key=None
      )
      __UpperCAmelCase    :Dict				       =     st.sidebar.slider(
          "Maximum generation length", min_value=6_4, max_value=5_1_2, value=2_5_6, step=1_6, format=None, key=None
      )
      if sampled == "beam":
            __UpperCAmelCase    :str				       =     st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
      else:
            __UpperCAmelCase    :List[str]				       =     st.sidebar.slider(
                "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
            )
            __UpperCAmelCase    :List[Any]				       =     st.sidebar.slider(
                "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
            )
            __UpperCAmelCase    :str				       =     None

# start main text
__UpperCAmelCase    :List[Any]				       =     [
    "<MY QUESTION>",
    "How do people make chocolate?",
    "Why do we get a fever when we are sick?",
    "How can different animals perceive different colors?",
    "What is natural language processing?",
    "What's the best way to treat a sunburn?",
    "What exactly are vitamins ?",
    "How does nuclear energy provide electricity?",
    "What's the difference between viruses and bacteria?",
    "Why are flutes classified as woodwinds when most of them are made out of metal ?",
    "Why do people like drinking coffee even though it tastes so bad?",
    "What happens when wine ages? How does it make the wine taste better?",
    "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?",
    "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?",
    "How does New Zealand have so many large bird predators?",
]
__UpperCAmelCase    :Optional[Any]				       =     st.selectbox(
    "What would you like to ask? ---- select <MY QUESTION> to enter a new query",
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
      __UpperCAmelCase    :str				       =     st.text_input("Enter your question here:", "")
else:
      __UpperCAmelCase    :Any				       =     question_s

if st.button("Show me!"):
      if action in [0, 1, 3]:
            if index_type == "mixed":
                  __UpperCAmelCase    :int				       =     make_support(question, source=wiki_source, method="dense", n_results=1_0)
                  __UpperCAmelCase    :List[str]				       =     make_support(question, source=wiki_source, method="sparse", n_results=1_0)
                  __UpperCAmelCase    :Optional[int]				       =     []
                  for res_d, res_s in zip(support_list_dense, support_list_sparse):
                        if tuple(res_d) not in support_list:
                              support_list += [tuple(res_d)]
                        if tuple(res_s) not in support_list:
                              support_list += [tuple(res_s)]
                  __UpperCAmelCase    :List[Any]				       =     support_list[:1_0]
                  __UpperCAmelCase    :Optional[Any]				       =     "<P> " + " <P> ".join([res[-1] for res in support_list])
            else:
                  __UpperCAmelCase    :Optional[int]				       =     make_support(question, source=wiki_source, method=index_type, n_results=1_0)
      if action in [0, 3]:
            __UpperCAmelCase    :List[str]				       =     answer_question(
                question_doc,
                sas_model,
                sas_tokenizer,
                min_len=min_len,
                max_len=int(max_len),
                sampling=(sampled == "sampled"),
                n_beams=n_beams,
                top_p=top_p,
                temp=temp,
            )
            st.markdown("### The model generated answer is:")
            st.write(answer)
      if action in [0, 1, 3] and wiki_source != "none":
            st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:")
            for i, res in enumerate(support_list):
                  __UpperCAmelCase    :int				       =     "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_"))
                  __UpperCAmelCase    :Any				       =     res[1].strip()
                  if sec_titles == "":
                        __UpperCAmelCase    :Tuple				       =     "[{}]({})".format(res[0], wiki_url)
                  else:
                        __UpperCAmelCase    :Dict				       =     sec_titles.split(" & ")
                        __UpperCAmelCase    :Dict				       =     " & ".join(
                            ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list]
                        )
                  st.markdown(
                      "{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}".format(i + 1, res[0], sections),
                      unsafe_allow_html=True,
                  )
                  if show_passages:
                        st.write(
                            "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True
                        )
      if action in [2, 3]:
            __UpperCAmelCase    :Any				       =     find_nearest_training(question)
            __UpperCAmelCase    :Dict				       =     nn_train_list[0]
            st.markdown(
                "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"])
            )
            __UpperCAmelCase    :str				       =     [
                "{}. {}".format(i + 1, "  \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""]))
                for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"]))
                if i == 0 or sc > 2
            ]
            st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st)))


__UpperCAmelCase    :Optional[Any]				       =     "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n"

st.sidebar.markdown(disclaimer, unsafe_allow_html=True)



'''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"):
      __UpperCAmelCase    :Optional[Any]				       =     True
      from torch.cuda.amp import autocast

__UpperCAmelCase    :Any				       =     logging.getLogger(__name__)




def 			_a			(		_lowercase      :			List[str]=None    ,      _lowercase      :			Union[str, Any]=None						):





     '''simple docstring'''






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



@dataclass
class 			a       :


     """simple docstring"""






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



@dataclass
class 			a       :


     """simple docstring"""






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



@dataclass
class 			a       :


     """simple docstring"""






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

     def __call__(       self  :	Any							,				snake_case  :	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
          __UpperCAmelCase			:				List[Any]													=    [{'''input_values''': feature['''input_values''']} for feature in features]
          __UpperCAmelCase			:				List[str]													=    [{'''input_ids''': feature['''labels''']} for feature in features]

          __UpperCAmelCase			:				List[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			:				Union[str, Any]													=    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    )							,				-100    )

          __UpperCAmelCase			:				str													=    labels

          return batch



class 			a       (	_a ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Optional[Any]							,				snake_case  :	nn.Module							,				snake_case  :	Dict[str, Union[torch.Tensor, Any]]    )		->							torch.Tensor:
          model.train()
          __UpperCAmelCase			:				Any													=    self._prepare_inputs(snake_case    )

          if self.use_amp:
               with autocast():
                    __UpperCAmelCase			:				Optional[Any]													=    self.compute_loss(snake_case							,				snake_case    )
          else:
               __UpperCAmelCase			:				int													=    self.compute_loss(snake_case							,				snake_case    )

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





     '''simple docstring'''






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

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

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

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

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

     def remove_special_characters(_lowercase      :			Any						):
          __UpperCAmelCase			:				str													=    re.sub(_lowercase    ,      ''''''    ,      batch['''sentence''']						).lower() + ''' '''
          return batch

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

     def extract_all_chars(_lowercase      :			List[Any]						):
          __UpperCAmelCase			:				Tuple													=    ''' '''.join(batch['''text''']						)
          __UpperCAmelCase			:				List[Any]													=    list(set(_lowercase						)						)
          return {"vocab": [vocab], "all_text": [all_text]}

     __UpperCAmelCase			:				Dict													=    train_dataset.map(
         _lowercase    ,      batched=_lowercase    ,      batch_size=-1    ,      keep_in_memory=_lowercase    ,      remove_columns=train_dataset.column_names    ,      )
     __UpperCAmelCase			:				Tuple													=    train_dataset.map(
         _lowercase    ,      batched=_lowercase    ,      batch_size=-1    ,      keep_in_memory=_lowercase    ,      remove_columns=eval_dataset.column_names    ,      )

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

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

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

     if data_args.max_val_samples is not None:
          __UpperCAmelCase			:				Optional[int]													=    eval_dataset.select(range(data_args.max_val_samples						)						)

     __UpperCAmelCase			:				List[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(_lowercase      :			List[Any]						):
          __UpperCAmelCase							,     __UpperCAmelCase			:				int													=    torchaudio.load(batch['''path''']						)
          __UpperCAmelCase			:				Optional[int]													=    resampler(_lowercase						).squeeze().numpy()
          __UpperCAmelCase			:				Optional[int]													=    16000
          __UpperCAmelCase			:				Union[str, Any]													=    batch['''text''']
          return batch

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

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

     __UpperCAmelCase			:				int													=    train_dataset.map(
         _lowercase    ,      remove_columns=train_dataset.column_names    ,      batch_size=training_args.per_device_train_batch_size    ,      batched=_lowercase    ,      num_proc=data_args.preprocessing_num_workers    ,      )
     __UpperCAmelCase			:				Tuple													=    eval_dataset.map(
         _lowercase    ,      remove_columns=eval_dataset.column_names    ,      batch_size=training_args.per_device_train_batch_size    ,      batched=_lowercase    ,      num_proc=data_args.preprocessing_num_workers    ,      )

     # Metric
     __UpperCAmelCase			:				List[Any]													=    datasets.load_metric('''wer'''						)

     def compute_metrics(_lowercase      :			Tuple						):
          __UpperCAmelCase			:				Optional[int]													=    pred.predictions
          __UpperCAmelCase			:				int													=    np.argmax(_lowercase    ,      axis=-1						)

          __UpperCAmelCase			:				str													=    processor.tokenizer.pad_token_id

          __UpperCAmelCase			:				Union[str, Any]													=    processor.batch_decode(_lowercase						)
          # we do not want to group tokens when computing the metrics
          __UpperCAmelCase			:				Tuple													=    processor.batch_decode(pred.label_ids    ,      group_tokens=_lowercase						)

          __UpperCAmelCase			:				Optional[Any]													=    wer_metric.compute(predictions=_lowercase    ,      references=_lowercase						)

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     # Data collator
     __UpperCAmelCase			:				List[str]													=    DataCollatorCTCWithPadding(processor=_lowercase    ,      padding=_lowercase						)

     # Initialize our Trainer
     __UpperCAmelCase			:				List[str]													=    CTCTrainer(
         model=_lowercase    ,      data_collator=_lowercase    ,      args=_lowercase    ,      compute_metrics=_lowercase    ,      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:
               __UpperCAmelCase			:				Optional[int]													=    last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path						):
               __UpperCAmelCase			:				List[Any]													=    model_args.model_name_or_path
          else:
               __UpperCAmelCase			:				Optional[int]													=    None

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

          __UpperCAmelCase			:				List[Any]													=    trainer.train(resume_from_checkpoint=_lowercase						)
          trainer.save_model()

          __UpperCAmelCase			:				Tuple													=    train_result.metrics
          __UpperCAmelCase			:				Tuple													=    (
              data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase						)
          )
          __UpperCAmelCase			:				Tuple													=    min(_lowercase    ,      len(_lowercase						)						)

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

     # Evaluation
     __UpperCAmelCase			:				Dict													=    {}
     if training_args.do_eval:
          logger.info('''*** Evaluate ***'''						)
          __UpperCAmelCase			:				Tuple													=    trainer.evaluate()
          __UpperCAmelCase			:				List[Any]													=    data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowercase						)
          __UpperCAmelCase			:				List[str]													=    min(_lowercase    ,      len(_lowercase						)						)

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

     return results


if __name__ == "__main__":
      main()