




'''simple docstring'''





import json
import os
import subprocess
import sys
import warnings
from argparse import ArgumentParser
from contextlib import AbstractContextManager
from typing import Dict, List, Optional

import requests

from ..utils import logging
from . import BaseTransformersCLICommand


a		:	Optional[Any]       =      logging.get_logger(__name__)  # pylint: disable=invalid-name


a		:	List[Any]       =      """lfs-multipart-upload"""




class      UpperCamelCase       (	__A       ):



  @staticmethod
  def     a_							(			__lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Tuple							       =      parser.add_parser(
          """lfs-enable-largefiles"""		,     help=(
              """Deprecated: use `huggingface-cli` instead. Configure your repository to enable upload of files > 5GB."""
          )		,     )
      enable_parser.add_argument("""path"""		,     type=lowerCamelCase__		,     help="""Local path to repository you want to configure.""" )
      enable_parser.set_defaults(func=lambda __lowerCAmelCase : LfsEnableCommand(lowerCamelCase__ ) )

      _a				:							int							       =      parser.add_parser(
          lowerCamelCase__		,     help=(
              """Deprecated: use `huggingface-cli` instead. """
              """Command will get called by git-lfs, do not call it directly."""
          )		,     )
      upload_parser.set_defaults(func=lambda __lowerCAmelCase : LfsUploadCommand(lowerCamelCase__ ) )






class      UpperCamelCase       :



  def __init__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							int							       =      args



  def     a_							(			self ):







      '''simple docstring'''


      warnings.warn(
          """Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead.""" )
      _a				:							Union[str, Any]							       =      os.path.abspath(self.args.path )
      if not os.path.isdir(lowerCamelCase__ ):
          print("""This does not look like a valid git repo.""" )
          exit(1 )
      subprocess.run(
          """git config lfs.customtransfer.multipart.path transformers-cli""".split()		,     check=lowerCamelCase__		,     cwd=lowerCamelCase__ )
      subprocess.run(
          f'''git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}'''.split()		,     check=lowerCamelCase__		,     cwd=lowerCamelCase__		,     )
      print("""Local repo set up for largefiles""" )






def UpperCAmelCase    (       UpperCAmelCase_						):
    _a				:							Dict							       =      json.dumps(a__						) + """\n"""
    sys.stdout.write(a__						)
    sys.stdout.flush()





def UpperCAmelCase    (       ):
    _a				:							List[str]							       =      json.loads(sys.stdin.readline().strip()						)

    if "terminate" in (msg.get("""type"""						), msg.get("""event"""						)):
        # terminate message received
        return None

    if msg.get("""event"""						) not in ("download", "upload"):
        logger.critical("""Received unexpected message"""						)
        sys.exit(1						)

    return msg




class      UpperCamelCase       (	__A       ):



  def __init__(			self		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							str							       =      filepath
      _a				:							List[str]							       =      seek_from
      _a				:							Optional[int]							       =      read_limit
      _a				:							Optional[int]							       =      0



  def __enter__(			self ):







      '''simple docstring'''


      _a				:							Tuple							       =      open(self.filepath		,     """rb""" )
      self.f.seek(self.seek_from )
      return self



  def __len__(			self ):







      '''simple docstring'''


      _a				:							Optional[Any]							       =      os.fstat(self.f.fileno() ).st_size
      return min(self.read_limit		,     total_length - self.seek_from )



  def     a_							(			self		,     __lowerCAmelCase=-1 ):







      '''simple docstring'''


      if self.n_seen >= self.read_limit:
          return b""
      _a				:							Any							       =      self.read_limit - self.n_seen
      _a				:							Any							       =      self.f.read(remaining_amount if n < 0 else min(lowerCamelCase__		,     lowerCamelCase__ ) )
      self.n_seen += len(lowerCamelCase__ )
      return data



  def __iter__(			self ):







      '''simple docstring'''


      yield self.read(n=4 * 1024 * 1024 )



  def __exit__(			self		,     *__lowerCAmelCase ):







      '''simple docstring'''


      self.f.close()






class      UpperCamelCase       :



  def __init__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Optional[int]							       =      args



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							List[Any]							       =      json.loads(sys.stdin.readline().strip() )
      if not (init_msg.get("""event""" ) == "init" and init_msg.get("""operation""" ) == "upload"):
          write_msg({"""error""": {"""code""": 32, """message""": """Wrong lfs init operation"""}} )
          sys.exit(1 )

      # The transfer process should use the information it needs from the
      # initiation structure, and also perform any one-off setup tasks it
      # needs to do. It should then respond on stdout with a simple empty
      # confirmation structure, as follows:
      write_msg({} )

      # After the initiation exchange, git-lfs will send any number of
      # transfer requests to the stdin of the transfer process, in a serial sequence.
      while True:
          _a				:							Optional[int]							       =      read_msg()
          if msg is None:
              # When all transfers have been processed, git-lfs will send
              # a terminate event to the stdin of the transfer process.
              # On receiving this message the transfer process should
              # clean up and terminate. No response is expected.
              sys.exit(0 )

          _a				:							List[Any]							       =      msg["""oid"""]
          _a				:							Any							       =      msg["""path"""]
          _a				:							List[Any]							       =      msg["""action"""]["""href"""]
          _a				:							Union[str, Any]							       =      msg["""action"""]["""header"""]
          _a				:							Any							       =      int(header.pop("""chunk_size""" ) )
          _a				:							Optional[int]							       =      list(header.values() )

          _a				:							Optional[int]							       =      []
          for i, presigned_url in enumerate(lowerCamelCase__ ):
              with FileSlice(lowerCamelCase__		,     seek_from=i * chunk_size		,     read_limit=lowerCamelCase__ ) as data:
                  _a				:							List[Any]							       =      requests.put(lowerCamelCase__		,     data=lowerCamelCase__ )
                  r.raise_for_status()
                  parts.append(
                      {
                          """etag""": r.headers.get("""etag""" ),
                          """partNumber""": i + 1,
                      } )
                  # In order to support progress reporting while data is uploading / downloading,
                  # the transfer process should post messages to stdout
                  write_msg(
                      {
                          """event""": """progress""",
                          """oid""": oid,
                          """bytesSoFar""": (i + 1) * chunk_size,
                          """bytesSinceLast""": chunk_size,
                      } )
                  # Not precise but that's ok.

          _a				:							Optional[int]							       =      requests.post(
              lowerCamelCase__		,     json={
                  """oid""": oid,
                  """parts""": parts,
              }		,     )
          r.raise_for_status()

          write_msg({"""event""": """complete""", """oid""": oid} )








'''simple docstring'''
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"""):
  A				: Union[str, Any]					      =			True
  from torch.cuda.amp import autocast


A				: Union[str, Any]					      =			logging.getLogger(__name__)






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

def 							snake_case_    (  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     )]       ,)
    __lowercase     							=		logging.WARNING
    if model_args.verbose_logging:
        __lowercase     							=		logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank     ):
        __lowercase     							=		logging.INFO
    logger.setLevel(a__     )






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






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	bool       =   False
       snake_case_					:	Optional[str]       =   None
       snake_case_					:	Optional[str]       =   "|"
       snake_case_					:	Optional[Dict[str, str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Set[str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Callable[[str], str]]       =   None

       @classmethod
       def        snake_case__     (       cls   ,						lowerCamelCase__	)       ->   Any:

           """simple docstring"""



           if name == "librispeech":
               return cls()
           if name == "timit":
               return cls(
                   do_lower_case=lowerCamelCase__   ,						translation_table=str.maketrans({"""-""": """ """}	)   ,						)
           if name == "buckwalter":
               __lowercase     							=		{
                   """-""": """ """,  # 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        snake_case__     (       self   ,						lowerCamelCase__	)       ->   str:

           """simple docstring"""



           if len(self.translation_table	) > 0:
               __lowercase     							=		text.translate(self.translation_table	)
           if len(self.words_to_remove	) == 0:
               __lowercase     							=		""" """.join(text.split()	)  # clean up whitespaces
           else:
               __lowercase     							=		""" """.join(w for w in text.split() if w not in self.words_to_remove	)  # and clean up whilespaces
           return text




       def        snake_case__     (       self   ,						lowerCamelCase__	)       ->   WavaVecaProcessor:

           """simple docstring"""



           __lowercase     							=		WavaVecaFeatureExtractor.from_pretrained(
               model_args.model_name_or_path   ,						cache_dir=model_args.cache_dir	)
           if self.vocab_file:
               __lowercase     							=		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:
               __lowercase     							=		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 			SCREAMING_SNAKE_CASE:
       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   ,						lowerCamelCase__	)       ->   Dict[str, torch.Tensor]:

           """simple docstring"""



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

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

           __lowercase     							=		labels

           return batch






class 			SCREAMING_SNAKE_CASE(							__A	):

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   torch.Tensor:

           """simple docstring"""



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

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

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



    """simple docstring"""




    __lowercase     							=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

    __lowercase							,__lowercase							,__lowercase     							=		parser.parse_args_into_dataclasses()
    configure_logger(a__       ,a__     )

    __lowercase     							=		Orthography.from_name(data_args.orthography.lower()     )
    __lowercase     							=		orthography.create_processor(a__     )
    __lowercase     							=		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     )       ,)

    __lowercase     							=		datasets.load_dataset(
        data_args.dataset_name       ,data_args.dataset_config_name       ,split=data_args.train_split_name     )
    __lowercase     							=		datasets.load_dataset(
        data_args.dataset_name       ,data_args.dataset_config_name       ,split=data_args.validation_split_name     )

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

    def prepare_example(a__						:      Tuple     ):  # TODO(elgeish) make use of multiprocessing?
        __lowercase							,__lowercase     							=		librosa.load(example[data_args.speech_file_column]       ,sr=a__     )
        if data_args.max_duration_in_seconds is not None:
            __lowercase     							=		len(example["""speech"""]     ) / example["""sampling_rate"""]
        # Normalize and clean up text; order matters!
        __lowercase     							=		orthography.preprocess_for_training(example[data_args.target_text_column]     )
        __lowercase     							=		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)     )
            __lowercase     							=		updated_text
        return example

    __lowercase     							=		train_dataset.map(a__       ,remove_columns=[data_args.speech_file_column]     )
    __lowercase     							=		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__						:      Union[str, Any]     ):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

        __lowercase     							=		len(a__     )
        __lowercase     							=		len(a__     )
        __lowercase     							=		train_dataset.filter(a__       ,remove_columns=["""duration_in_seconds"""]     )
        __lowercase     							=		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}"'     )
    __lowercase     							=		None

    def prepare_dataset(a__						:      Optional[Any]     ):
        # 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}.'

        __lowercase     							=		processor(
            audio=batch["""speech"""]       ,text=batch[data_args.target_text_column]       ,sampling_rate=batch["""sampling_rate"""][0]     )
        batch.update(a__     )
        return batch

    __lowercase     							=		train_dataset.map(
        a__       ,batch_size=training_args.per_device_train_batch_size       ,batched=a__       ,num_proc=data_args.preprocessing_num_workers       ,)
    __lowercase     							=		val_dataset.map(
        a__       ,batch_size=training_args.per_device_train_batch_size       ,batched=a__       ,num_proc=data_args.preprocessing_num_workers       ,)

    __lowercase     							=		DataCollatorCTCWithPadding(processor=a__       ,padding=a__     )

    def compute_metrics(a__						:      Union[str, Any]     ):
        __lowercase     							=		pred.predictions
        __lowercase     							=		np.argmax(a__       ,axis=-1     )

        __lowercase     							=		processor.tokenizer.pad_token_id

        __lowercase     							=		processor.batch_decode(a__     )
        # we do not want to group tokens when computing the metrics
        __lowercase     							=		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__     )}"'     )

        __lowercase     							=		wer_metric.compute(predictions=a__       ,references=a__     )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    __lowercase     							=		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()




