
"""simple docstring"""





import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
    from comet_ml import OfflineExperiment

if is_tensorboard_available():
    import struct

    import tensorboard.compat.proto.event_pba as event_pba

_a									=				logging.getLogger(__name__)


@require_tensorboard
class A_      (unittest.TestCase ):




  '''simple docstring'''







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     UpperCAmelCase_   :   List[Any]     	=       "test_project_with_config"
     with tempfile.TemporaryDirectory() as dirpath:
        UpperCAmelCase_   :   int     	=       Accelerator(log_with="tensorboard"							,  project_dir=lowercase_    )
        UpperCAmelCase_   :   Optional[int]     	=       {"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
        accelerator.init_trackers(lowercase_							,  lowercase_    )
        accelerator.end_training()
        for child in Path(F"""{dirpath}/{project_name}"""    ).glob("*/**"    ):
           UpperCAmelCase_   :   Union[str, Any]     	=       list(filter(lambda lowercase_    : x.is_file()							,  child.iterdir()    )    )[0]
        self.assertNotEqual(str(lowercase_    )							,  ""    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     UpperCAmelCase_   :   List[str]     	=       "test_project_with_log"
     with tempfile.TemporaryDirectory() as dirpath:
        UpperCAmelCase_   :   Union[str, Any]     	=       Accelerator(log_with="tensorboard"							,  project_dir=lowercase_    )
        accelerator.init_trackers(lowercase_    )
        UpperCAmelCase_   :   int     	=       {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
        accelerator.log(lowercase_							,  step=0    )
        accelerator.end_training()
        # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
        # Names are randomly generated each time
        UpperCAmelCase_   :   int     	=       list(filter(lambda lowercase_    : x.is_file()							,  Path(F"""{dirpath}/{project_name}"""    ).iterdir()    )    )[0]
        self.assertNotEqual(str(lowercase_    )							,  ""    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     UpperCAmelCase_   :   Tuple     	=       "test_project_with_log"
     with tempfile.TemporaryDirectory() as dirpath:
        UpperCAmelCase_   :   str     	=       Accelerator(log_with="tensorboard"							,  project_dir=lowercase_    )
        accelerator.init_trackers(lowercase_    )
        UpperCAmelCase_   :   Any     	=       {"tensor": torch.tensor(1    )}
        accelerator.log(lowercase_							,  step=0    )
        accelerator.end_training()
        # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
        # Names are randomly generated each time
        UpperCAmelCase_   :   Optional[Any]     	=       list(filter(lambda lowercase_    : x.is_file()							,  Path(F"""{dirpath}/{project_name}"""    ).iterdir()    )    )[0]
        # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
        with open(lowercase_							,  "rb"    ) as f:
           UpperCAmelCase_   :   Any     	=       f.read()
        UpperCAmelCase_   :   List[Any]     	=       False
        while data:
           UpperCAmelCase_   :   Dict     	=       struct.unpack("Q"							,  data[:8]    )

           UpperCAmelCase_   :   Optional[Any]     	=       data[12 : 12 + int(header[0]    )]  # 8+4
           UpperCAmelCase_   :   int     	=       data[12 + int(header[0]    ) + 4 :]
           UpperCAmelCase_   :   Optional[Any]     	=       event_pba.Event()

           event.ParseFromString(lowercase_    )
           if event.HasField("summary"    ):
              for value in event.summary.value:
                 if value.simple_value == 1.0 and value.tag == "tensor":
                    UpperCAmelCase_   :   Optional[Any]     	=       True
        self.assertTrue(lowercase_							,  "Converted tensor was not found in the log file!"    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     with self.assertRaisesRegex(lowercase_							,  "Logging with `tensorboard` requires a `logging_dir`"    ):
        UpperCAmelCase_   :   Optional[Any]     	=       Accelerator(log_with="tensorboard"    )
     with tempfile.TemporaryDirectory() as dirpath:
        UpperCAmelCase_   :   Union[str, Any]     	=       Accelerator(log_with="tensorboard"							,  project_dir=lowercase_    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     UpperCAmelCase_   :   str     	=       ProjectConfiguration(total_limit=30    )
     with tempfile.TemporaryDirectory() as dirpath:
        UpperCAmelCase_   :   Optional[int]     	=       Accelerator(log_with="tensorboard"							,  project_dir=lowercase_							,  project_config=lowercase_    )




@require_wandb
@mock.patch.dict(os.environ							,{"""WANDB_MODE""": """offline"""} )
class A_      (lowercase__							,lowercase__ ):




  '''simple docstring'''







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     super().setUp()
     # wandb let's us override where logs are stored to via the WANDB_DIR env var
     self.add_mocks(mock.patch.dict(os.environ							,  {"WANDB_DIR": self.tmpdir}    )    )







  @staticmethod
  def 			UpperCamelCase__   (						lowercase_							,  lowercase_							,  lowercase_ = True    ):

     """simple docstring"""
     UpperCAmelCase_   :   Any     	=       RF"""{section} ([\S\s]*?)\n\n"""
     if record:
        UpperCAmelCase_   :   Dict     	=       RF"""Record: {pattern}"""
     UpperCAmelCase_   :   Optional[int]     	=       re.findall(lowercase_							,  lowercase_    )[0]
     # A config
     if section == "config" or section == "history":
        UpperCAmelCase_   :   Any     	=       re.findall(R"\"([a-zA-Z0-9_.,]+)"							,  lowercase_    )
        return {key: val for key, val in zip(cleaned_record[0::2]							,  cleaned_record[1::2]    )}
     # Everything else
     else:
        return dict(re.findall(R"(\w+): \"([^\s]+)\""							,  lowercase_    )    )







  @skip
  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     UpperCAmelCase_   :   List[str]     	=       "test_project_with_config"
     UpperCAmelCase_   :   List[Any]     	=       Accelerator(log_with="wandb"    )
     UpperCAmelCase_   :   Optional[Any]     	=       {"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
     UpperCAmelCase_   :   List[str]     	=       {"wandb": {"tags": ["my_tag"]}}
     accelerator.init_trackers(lowercase_							,  lowercase_							,  lowercase_    )
     UpperCAmelCase_   :   Optional[Any]     	=       {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
     accelerator.log(lowercase_							,  step=0    )
     accelerator.end_training()
     # The latest offline log is stored at wandb/latest-run/*.wandb
     for child in Path(F"""{self.tmpdir}/wandb/latest-run"""    ).glob("*"    ):
        if child.is_file() and child.suffix == ".wandb":
           UpperCAmelCase_   :   Optional[int]     	=       subprocess.check_output(
               ["wandb", "sync", "--view", "--verbose", str(lowercase_    )]							,  env=os.environ.copy()    ).decode("utf8"							,  "ignore"    )
           break

        # Check HPS through careful parsing and cleaning
     UpperCAmelCase_   :   List[str]     	=       self.parse_log(lowercase_							,  "config"    )
     self.assertEqual(logged_items["num_iterations"]							,  "12"    )
     self.assertEqual(logged_items["learning_rate"]							,  "0.01"    )
     self.assertEqual(logged_items["some_boolean"]							,  "false"    )
     self.assertEqual(logged_items["some_string"]							,  "some_value"    )
     self.assertEqual(logged_items["some_string"]							,  "some_value"    )

     # Run tags
     UpperCAmelCase_   :   Optional[int]     	=       self.parse_log(lowercase_							,  "run"							,  lowercase_    )
     self.assertEqual(logged_items["tags"]							,  "my_tag"    )

     # Actual logging
     UpperCAmelCase_   :   Union[str, Any]     	=       self.parse_log(lowercase_							,  "history"    )
     self.assertEqual(logged_items["total_loss"]							,  "0.1"    )
     self.assertEqual(logged_items["iteration"]							,  "1"    )
     self.assertEqual(logged_items["my_text"]							,  "some_value"    )
     self.assertEqual(logged_items["_step"]							,  "0"    )







def       __a	(						self,						__lowerCamelCase,						__lowerCamelCase    ):
   UpperCAmelCase_   :   Optional[Any]     	=       run_name
   UpperCAmelCase_   :   str     	=       OfflineExperiment(project_name=__lowerCamelCase,						offline_directory=__lowerCamelCase    )
   logger.info(f"""Initialized offline CometML project {self.run_name}"""    )
   logger.info("Make sure to log any initial configurations with `self.store_init_configuration` before training!"    )


@require_comet_ml
@mock.patch.object(lowercase__							,"""__init__"""							,lowercase__ )
class A_      (unittest.TestCase ):




  '''simple docstring'''







  @staticmethod
  def 			UpperCamelCase__   (						lowercase_							,  lowercase_							,  lowercase_ = False    ):

     """simple docstring"""
     for log in log_list:
        UpperCAmelCase_   :   str     	=       json.loads(lowercase_    )["payload"]
        if is_param and "param" in j.keys():
           if j["param"]["paramName"] == key:
              return j["param"]["paramValue"]
        if "log_other" in j.keys():
           if j["log_other"]["key"] == key:
              return j["log_other"]["val"]
        if "metric" in j.keys():
           if j["metric"]["metricName"] == key:
              return j["metric"]["metricValue"]







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     with tempfile.TemporaryDirectory() as d:
        UpperCAmelCase_   :   str     	=       CometMLTracker("test_project_with_config"							,  lowercase_    )
        UpperCAmelCase_   :   Dict     	=       Accelerator(log_with=lowercase_    )
        UpperCAmelCase_   :   List[Any]     	=       {"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
        accelerator.init_trackers(lowercase_							,  lowercase_    )
        accelerator.end_training()
        UpperCAmelCase_   :   Any     	=       os.listdir(lowercase_    )[0]  # Comet is nice, it's just a zip file here
        # We parse the raw logs
        UpperCAmelCase_   :   List[Any]     	=       os.path.join(lowercase_							,  lowercase_    )
        UpperCAmelCase_   :   Optional[int]     	=       zipfile.ZipFile(lowercase_							,  "r"    )
        UpperCAmelCase_   :   List[Any]     	=       archive.open("messages.json"    ).read().decode("utf-8"    )
     UpperCAmelCase_   :   List[str]     	=       log.split("\n"    )[:-1]
     self.assertEqual(self.get_value_from_key(lowercase_							,  "num_iterations"							,  lowercase_    )							,  12    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "learning_rate"							,  lowercase_    )							,  0.01    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "some_boolean"							,  lowercase_    )							,  lowercase_    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "some_string"							,  lowercase_    )							,  "some_value"    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     with tempfile.TemporaryDirectory() as d:
        UpperCAmelCase_   :   List[Any]     	=       CometMLTracker("test_project_with_config"							,  lowercase_    )
        UpperCAmelCase_   :   Union[str, Any]     	=       Accelerator(log_with=lowercase_    )
        accelerator.init_trackers(lowercase_    )
        UpperCAmelCase_   :   Optional[int]     	=       {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
        accelerator.log(lowercase_							,  step=0    )
        accelerator.end_training()
        UpperCAmelCase_   :   Tuple     	=       os.listdir(lowercase_    )[0]  # Comet is nice, it's just a zip file here
        # We parse the raw logs
        UpperCAmelCase_   :   Dict     	=       os.path.join(lowercase_							,  lowercase_    )
        UpperCAmelCase_   :   str     	=       zipfile.ZipFile(lowercase_							,  "r"    )
        UpperCAmelCase_   :   Optional[Any]     	=       archive.open("messages.json"    ).read().decode("utf-8"    )
     UpperCAmelCase_   :   Optional[int]     	=       log.split("\n"    )[:-1]
     self.assertEqual(self.get_value_from_key(lowercase_							,  "curr_step"							,  lowercase_    )							,  0    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "total_loss"    )							,  0.1    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "iteration"    )							,  1    )
     self.assertEqual(self.get_value_from_key(lowercase_							,  "my_text"    )							,  "some_value"    )




class A_      (lowercase__ ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__     :		Dict    	=						[
      """total_loss""",
      """iteration""",
      """my_text""",
      """learning_rate""",
      """num_iterations""",
      """some_boolean""",
      """some_string""",
  ]

  SCREAMING_SNAKE_CASE__     :		Dict    	=						"""my_custom_tracker"""
  SCREAMING_SNAKE_CASE__     :		List[str]    	=						False







  def __init__(						self							,  lowercase_    ):

     """simple docstring"""
     UpperCAmelCase_   :   Any     	=       open(F"""{dir}/log.csv"""							,  "w+"    )
     UpperCAmelCase_   :   Optional[int]     	=       csv.DictWriter(self.f							,  fieldnames=self._col_names    )
     self.writer.writeheader()







  @property
  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     return self.writer







  def 			UpperCamelCase__   (						self							,  lowercase_    ):

     """simple docstring"""
     logger.info("Call init"    )
     self.writer.writerow(lowercase_    )







  def 			UpperCamelCase__   (						self							,  lowercase_							,  lowercase_    ):

     """simple docstring"""
     logger.info("Call log"    )
     self.writer.writerow(lowercase_    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     self.f.close()




class A_      (unittest.TestCase ):




  '''simple docstring'''







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     with tempfile.TemporaryDirectory() as d:
        UpperCAmelCase_   :   Any     	=       MyCustomTracker(lowercase_    )
        UpperCAmelCase_   :   Optional[int]     	=       Accelerator(log_with=lowercase_    )
        UpperCAmelCase_   :   Any     	=       {"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
        accelerator.init_trackers("Some name"							,  lowercase_    )
        accelerator.end_training()
        with open(F"""{d}/log.csv"""							,  "r"    ) as f:
           UpperCAmelCase_   :   Dict     	=       csv.DictReader(lowercase_    )
           UpperCAmelCase_   :   List[Any]     	=       next(lowercase_    )
           UpperCAmelCase_   :   int     	=       {
               "total_loss": "",
               "iteration": "",
               "my_text": "",
               "learning_rate": "0.01",
               "num_iterations": "12",
               "some_boolean": "False",
               "some_string": "some_value",
           }
           self.assertDictEqual(lowercase_							,  lowercase_    )







  def 			UpperCamelCase__   (						self    ):

     """simple docstring"""
     with tempfile.TemporaryDirectory() as d:
        UpperCAmelCase_   :   Any     	=       MyCustomTracker(lowercase_    )
        UpperCAmelCase_   :   Dict     	=       Accelerator(log_with=lowercase_    )
        accelerator.init_trackers("Some name"    )
        UpperCAmelCase_   :   Any     	=       {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
        accelerator.log(lowercase_							,  step=0    )
        accelerator.end_training()
        with open(F"""{d}/log.csv"""							,  "r"    ) as f:
           UpperCAmelCase_   :   Optional[int]     	=       csv.DictReader(lowercase_    )
           UpperCAmelCase_   :   Any     	=       next(lowercase_    )
           UpperCAmelCase_   :   Tuple     	=       {
               "total_loss": "0.1",
               "iteration": "1",
               "my_text": "some_value",
               "learning_rate": "",
               "num_iterations": "",
               "some_boolean": "",
               "some_string": "",
           }
           self.assertDictEqual(lowercase_							,  lowercase_    )







import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
      from apex import amp

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


UpperCamelCase_									=   logging.getLogger(__name__)







@dataclass
class       _snake_case				:






   '''simple docstring'''






   A__      : str       =						field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
   A__      : Optional[str]       =						field(
       default=__snake_case ,							metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,							)
   A__      : Optional[bool]       =						field(
       default=__snake_case ,							metadata={"help": "Whether to freeze the feature extractor layers of the model."} )
   A__      : Optional[bool]       =						field(
       default=__snake_case ,							metadata={"help": "Whether to log verbose messages or not."} ,							)







def       lowerCamelCase_  (    _a       :						ModelArguments   ,		_a       :						TrainingArguments    ):



    '''simple docstring'''




    logging.basicConfig(
        format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""   ,		datefmt="""%m/%d/%Y %H:%M:%S"""   ,		handlers=[logging.StreamHandler(sys.stdout    )]   ,		)
    UpperCAmelCase_     :       List[Any]  		=					logging.WARNING
    if model_args.verbose_logging:
        UpperCAmelCase_     :       int  		=					logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank    ):
        UpperCAmelCase_     :       Union[str, Any]  		=					logging.INFO
    logger.setLevel(_a    )







@dataclass
class       _snake_case				:






   '''simple docstring'''






   A__      : str       =						field(
       default=__snake_case ,							metadata={"help": "The name of the dataset to use (via the datasets library)."} )
   A__      : Optional[str]       =						field(
       default=__snake_case ,							metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} )
   A__      : Optional[str]       =						field(
       default="train" ,							metadata={
           "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
       } ,							)
   A__      : Optional[str]       =						field(
       default="validation" ,							metadata={
           "help": (
               "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
           )
       } ,							)
   A__      : Optional[str]       =						field(
       default="text" ,							metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"} ,							)
   A__      : Optional[str]       =						field(
       default="file" ,							metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} ,							)
   A__      : Optional[bool]       =						field(
       default=__snake_case ,							metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."} ,							)
   A__      : Optional[float]       =						field(
       default=__snake_case ,							metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."} ,							)
   A__      : Optional[str]       =						field(
       default="librispeech" ,							metadata={
           "help": (
               "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
               " 'buckwalter'."
           )
       } ,							)
   A__      : bool       =						field(
       default=__snake_case ,							metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
   A__      : Optional[int]       =						field(
       default=__snake_case ,							metadata={"help": "The number of processes to use for the preprocessing."} ,							)







@dataclass
class       _snake_case				:






   '''simple docstring'''






   A__      : bool       =						False
   A__      : Optional[str]       =						None
   A__      : Optional[str]       =						"|"
   A__      : Optional[Dict[str, str]]       =						field(default_factory=__snake_case )
   A__      : Optional[Set[str]]       =						field(default_factory=__snake_case )
   A__      : Optional[Callable[[str], str]]       =						None


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


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






   def       A__    (    self:     List[Any]  ,lowerCamelCase_:     ModelArguments							)	->      WavaVecaProcessor:
       UpperCAmelCase_     :       List[Any]  		=					WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path  ,cache_dir=model_args.cache_dir							)
       if self.vocab_file:
           UpperCAmelCase_     :       Tuple  		=					WavaVecaCTCTokenizer(
               self.vocab_file  ,cache_dir=model_args.cache_dir  ,do_lower_case=self.do_lower_case  ,word_delimiter_token=self.word_delimiter_token  ,)
       else:
           UpperCAmelCase_     :       Tuple  		=					WavaVecaCTCTokenizer.from_pretrained(
               model_args.model_name_or_path  ,cache_dir=model_args.cache_dir  ,do_lower_case=self.do_lower_case  ,word_delimiter_token=self.word_delimiter_token  ,)
       return WavaVecaProcessor(lowerCamelCase_  ,lowerCamelCase_							)







@dataclass
class       _snake_case				:






   '''simple docstring'''






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


   def __call__(    self:     Tuple  ,lowerCamelCase_:     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_     :       Union[str, Any]  		=					[{"""input_values""": feature["""input_values"""]} for feature in features]
       UpperCAmelCase_     :       List[Any]  		=					[{"""input_ids""": feature["""labels"""]} for feature in features]

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

       UpperCAmelCase_     :       List[str]  		=					labels

       return batch







class       _snake_case				(     __snake_case ):






   '''simple docstring'''






   def       A__    (    self:     Any  ,lowerCamelCase_:     nn.Module  ,lowerCamelCase_:     Dict[str, Union[torch.Tensor, Any]]							)	->      torch.Tensor:
       model.train()
       UpperCAmelCase_     :       Optional[int]  		=					self._prepare_inputs(lowerCamelCase_							)

       if self.use_amp:
           with autocast():
               UpperCAmelCase_     :       int  		=					self.compute_loss(lowerCamelCase_  ,lowerCamelCase_							)
       else:
           UpperCAmelCase_     :       Tuple  		=					self.compute_loss(lowerCamelCase_  ,lowerCamelCase_							)

       if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
               UpperCAmelCase_     :       List[str]  		=					loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
               UpperCAmelCase_     :       List[str]  		=					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_     :       Union[str, Any]  		=					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       lowerCamelCase_  (    ):



    '''simple docstring'''




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

    UpperCAmelCase_		, UpperCAmelCase_		, UpperCAmelCase_     :       Any  		=					parser.parse_args_into_dataclasses()
    configure_logger(_a   ,		_a    )

    UpperCAmelCase_     :       Tuple  		=					Orthography.from_name(data_args.orthography.lower()    )
    UpperCAmelCase_     :       int  		=					orthography.create_processor(_a    )
    UpperCAmelCase_     :       Dict  		=					WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path   ,		cache_dir=model_args.cache_dir   ,		gradient_checkpointing=training_args.gradient_checkpointing   ,		vocab_size=len(processor.tokenizer    )   ,		)

    UpperCAmelCase_     :       Dict  		=					datasets.load_dataset(
        data_args.dataset_name   ,		data_args.dataset_config_name   ,		split=data_args.train_split_name    )
    UpperCAmelCase_     :       int  		=					datasets.load_dataset(
        data_args.dataset_name   ,		data_args.dataset_config_name   ,		split=data_args.validation_split_name    )

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

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

    UpperCAmelCase_     :       Any  		=					train_dataset.map(_a   ,		remove_columns=[data_args.speech_file_column]    )
    UpperCAmelCase_     :       Optional[Any]  		=					val_dataset.map(_a   ,		remove_columns=[data_args.speech_file_column]    )

    if data_args.max_duration_in_seconds is not None:

        def filter_by_max_duration(_a       :						List[Any]    ):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

        UpperCAmelCase_     :       Union[str, Any]  		=					len(_a    )
        UpperCAmelCase_     :       int  		=					len(_a    )
        UpperCAmelCase_     :       Optional[Any]  		=					train_dataset.filter(_a   ,		remove_columns=["""duration_in_seconds"""]    )
        UpperCAmelCase_     :       Tuple  		=					val_dataset.filter(_a   ,		remove_columns=["""duration_in_seconds"""]    )
        if len(_a    ) > old_train_size:
            logger.warning(
                F'''Filtered out {len(_a    ) - old_train_size} train example(s) longer than'''
                F''' {data_args.max_duration_in_seconds} second(s).'''    )
        if len(_a    ) > old_val_size:
            logger.warning(
                F'''Filtered out {len(_a    ) - old_val_size} validation example(s) longer than'''
                F''' {data_args.max_duration_in_seconds} second(s).'''    )
    logger.info(F'''Split sizes: {len(_a    )} train and {len(_a    )} validation.'''    )

    logger.warning(F'''Updated {len(_a    )} transcript(s) using \'{data_args.orthography}\' orthography rules.'''    )
    if logger.isEnabledFor(logging.DEBUG    ):
        for original_text, updated_text in text_updates:
            logger.debug(F'''Updated text: "{original_text}" -> "{updated_text}"'''    )
    UpperCAmelCase_     :       Dict  		=					None

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

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

    UpperCAmelCase_     :       Optional[int]  		=					DataCollatorCTCWithPadding(processor=_a   ,		padding=_a    )

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

        UpperCAmelCase_     :       List[str]  		=					processor.tokenizer.pad_token_id

        UpperCAmelCase_     :       str  		=					processor.batch_decode(_a    )
        # we do not want to group tokens when computing the metrics
        UpperCAmelCase_     :       List[Any]  		=					processor.batch_decode(pred.label_ids   ,		group_tokens=_a    )
        if logger.isEnabledFor(logging.DEBUG    ):
            for reference, predicted in zip(_a   ,		_a    ):
                logger.debug(F'''reference: "{reference}"'''    )
                logger.debug(F'''predicted: "{predicted}"'''    )
                if orthography.untransliterator is not None:
                    logger.debug(F'''reference (untransliterated): "{orthography.untransliterator(_a    )}"'''    )
                    logger.debug(F'''predicted (untransliterated): "{orthography.untransliterator(_a    )}"'''    )

        UpperCAmelCase_     :       Dict  		=					wer_metric.compute(predictions=_a   ,		references=_a    )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    UpperCAmelCase_     :       Union[str, Any]  		=					CTCTrainer(
        model=_a   ,		data_collator=_a   ,		args=_a   ,		compute_metrics=_a   ,		train_dataset=_a   ,		eval_dataset=_a   ,		tokenizer=processor.feature_extractor   ,		)

    trainer.train()


if __name__ == "__main__":
      main()
