


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

__UpperCAmelCase			    =       logging.getLogger(__name__)




def      _a     (						_lowercase :     Any=None      , _lowercase :     int=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					:		str							,			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     :			Tuple  							=      [{'''input_values''': feature['''input_values''']} for feature in features]
          __UpperCAmelCase     :			Tuple  							=      [{'''input_ids''': feature['''labels''']} for feature in features]

          __UpperCAmelCase     :			Optional[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     :			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     :			Union[str, Any]  							=      labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1      )							,			-100      )

          __UpperCAmelCase     :			int  							=      labels

          return batch



class      a    (		_a	):


     """simple docstring"""






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

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

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

     # Detecting last checkpoint.
     __UpperCAmelCase     :			str  							=      None
     if os.path.isdir(training_args.output_dir  ) and training_args.do_train and not training_args.overwrite_output_dir:
          __UpperCAmelCase     :			List[str]  							=      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     :			List[Any]  							=      datasets.load_dataset(
         '''common_voice'''      , data_args.dataset_config_name      , split=data_args.train_split_name  )
     __UpperCAmelCase     :			Optional[Any]  							=      datasets.load_dataset('''common_voice'''      , data_args.dataset_config_name      , split='''test'''  )

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

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

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

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

     __UpperCAmelCase     :			Optional[int]  							=      train_dataset.map(
         _lowercase      , batched=_lowercase      , batch_size=-1      , keep_in_memory=_lowercase      , remove_columns=train_dataset.column_names      , )
     __UpperCAmelCase     :			Union[str, Any]  							=      train_dataset.map(
         _lowercase      , batched=_lowercase      , batch_size=-1      , keep_in_memory=_lowercase      , remove_columns=eval_dataset.column_names      , )

     __UpperCAmelCase     :			List[str]  							=      list(set(vocab_train['''vocab'''][0]  ) | set(vocab_test['''vocab'''][0]  )  )
     __UpperCAmelCase     :			List[Any]  							=      {v: k for k, v in enumerate(_lowercase  )}
     __UpperCAmelCase     :			Optional[int]  							=      vocab_dict[''' ''']
     del vocab_dict[" "]
     __UpperCAmelCase     :			Union[str, Any]  							=      len(_lowercase  )
     __UpperCAmelCase     :			List[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     :			Any  							=      WavaVecaCTCTokenizer(
         '''vocab.json'''      , unk_token='''[UNK]'''      , pad_token='''[PAD]'''      , word_delimiter_token='''|'''      , )
     __UpperCAmelCase     :			Tuple  							=      WavaVecaFeatureExtractor(
         feature_size=1      , sampling_rate=16000      , padding_value=0.0      , do_normalize=_lowercase      , return_attention_mask=_lowercase  )
     __UpperCAmelCase     :			Optional[Any]  							=      WavaVecaProcessor(feature_extractor=_lowercase      , tokenizer=_lowercase  )
     __UpperCAmelCase     :			Dict  							=      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     :			int  							=      min(len(_lowercase  )      , data_args.max_train_samples  )
          __UpperCAmelCase     :			Optional[int]  							=      train_dataset.select(range(_lowercase  )  )

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

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

     __UpperCAmelCase     :			List[str]  							=      train_dataset.map(
         _lowercase      , remove_columns=train_dataset.column_names      , num_proc=data_args.preprocessing_num_workers      , )
     __UpperCAmelCase     :			Optional[Any]  							=      eval_dataset.map(
         _lowercase      , remove_columns=eval_dataset.column_names      , num_proc=data_args.preprocessing_num_workers      , )

     def prepare_dataset(_lowercase :     Union[str, 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}.'

          __UpperCAmelCase     :			Dict  							=      processor(
              audio=batch['''speech''']      , text=batch['''target_text''']      , sampling_rate=batch['''sampling_rate'''][0]  )
          batch.update(_lowercase  )
          return batch

     __UpperCAmelCase     :			Optional[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     :			Union[str, Any]  							=      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     :			Dict  							=      datasets.load_metric('''wer'''  )

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

          __UpperCAmelCase     :			Any  							=      processor.tokenizer.pad_token_id

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

          __UpperCAmelCase     :			List[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[Any]  							=      DataCollatorCTCWithPadding(processor=_lowercase      , padding=_lowercase  )

     # Initialize our Trainer
     __UpperCAmelCase     :			List[Any]  							=      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     :			int  							=      last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path  ):
               __UpperCAmelCase     :			List[Any]  							=      model_args.model_name_or_path
          else:
               __UpperCAmelCase     :			Tuple  							=      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     :			List[Any]  							=      train_result.metrics
          __UpperCAmelCase     :			List[str]  							=      (
              data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase  )
          )
          __UpperCAmelCase     :			List[str]  							=      min(_lowercase      , len(_lowercase  )  )

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

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

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

     return results


if __name__ == "__main__":
      main()



'''simple docstring'''



from __future__ import annotations

__UpperCAmelCase      :Tuple			    =       "Muhammad Umer Farooq"
__UpperCAmelCase      :Tuple			    =       "MIT"
__UpperCAmelCase      :Union[str, Any]			    =       "1.0.0"
__UpperCAmelCase      :Optional[int]			    =       "Muhammad Umer Farooq"
__UpperCAmelCase      :Optional[Any]			    =       "contact@muhammadumerfarooq.me"
__UpperCAmelCase      :Any			    =       "Alpha"

import re
from html.parser import HTMLParser
from urllib import parse

import requests



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Tuple							,			snake_case					:		str      )						->							None:
          super().__init__()
          __UpperCAmelCase     :			list[str]  							=      []
          __UpperCAmelCase     :			Optional[int]  							=      domain






     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		str							,			snake_case					:		list[tuple[str, str | None]]      )						->							None:
          # Only parse the 'anchor' tag.
          if tag == "a":
               # Check the list of defined attributes.
               for name, value in attrs:
                    # If href is defined, and not empty nor # print it.
                    if name == "href" and value != "#" and value != "":
                         # If not already in urls.
                         if value not in self.urls:
                              __UpperCAmelCase     :			Optional[Any]  							=      parse.urljoin(self.domain							,			snake_case      )
                              self.urls.append(snake_case      )




def      _a     (						_lowercase :     str  ):





     '''simple docstring'''






     return ".".join(get_sub_domain_name(_lowercase  ).split('''.'''  )[-2:]  )




def      _a     (						_lowercase :     str  ):





     '''simple docstring'''






     return parse.urlparse(_lowercase  ).netloc




def      _a     (						_lowercase :     str = "https://github.com"  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Union[str, Any]  							=      get_domain_name(_lowercase  )

     # Initialize the parser
     __UpperCAmelCase     :			Dict  							=      Parser(_lowercase  )

     try:
          # Open URL
          __UpperCAmelCase     :			Dict  							=      requests.get(_lowercase  )

          # pass the raw HTML to the parser to get links
          parser.feed(r.text  )

          # Get links and loop through
          __UpperCAmelCase     :			str  							=      set()
          for link in parser.urls:
               # open URL.
               # read = requests.get(link)
               try:
                    __UpperCAmelCase     :			Tuple  							=      requests.get(_lowercase  )
                    # Get the valid email.
                    __UpperCAmelCase     :			Dict  							=      re.findall('''[a-zA-Z0-9]+@''' + domain      , read.text  )
                    # If not in list then append it.
                    for email in emails:
                         valid_emails.add(_lowercase  )
               except ValueError:
                    pass
     except ValueError:
          raise SystemExit(1  )

     # Finally return a sorted list of email addresses with no duplicates.
     return sorted(_lowercase  )


if __name__ == "__main__":
      __UpperCAmelCase      :List[str]			    =       emails_from_url("https://github.com")
      print(f"""{len(emails)} emails found:""")
      print("\n".join(sorted(emails)))