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


UpperCamelCase       :     Optional[int]			=    logging.getLogger(__name__)



@dataclass
class   UpperCamelCase					:







    """simple docstring"""





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






def SCREAMING_SNAKE_CASE__  (				snake_case       :				ModelArguments				,	snake_case       :				TrainingArguments  )   ->				Optional[Any]:







     """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  )]				,	)
     a					:							List[Any]							= logging.WARNING
     if model_args.verbose_logging:
          a					:							Optional[int]							= logging.DEBUG
     elif trainer_utils.is_main_process(training_args.local_rank  ):
          a					:							str							= logging.INFO
     logger.setLevel(snake_case  )



@dataclass
class   UpperCamelCase					:







    """simple docstring"""





    A     :    str				=			field(
        default=a_    ,     metadata={"help": "The name of the dataset to use (via the datasets library)."}       )
    A     :    Optional[str]				=			field(
        default=a_    ,     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=a_    ,     metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}    ,     )
    A     :    Optional[float]				=			field(
        default=a_    ,     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=a_    ,     metadata={"help": "Overwrite the cached preprocessed datasets or not."}       )
    A     :    Optional[int]				=			field(
        default=a_    ,     metadata={"help": "The number of processes to use for the preprocessing."}    ,     )






@dataclass
class   UpperCamelCase					:







    """simple docstring"""





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





    @classmethod
    def    SCREAMING_SNAKE_CASE_     (					cls     :						Any							,							UpperCAmelCase_     :						str):


         """simple docstring"""







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





    def    SCREAMING_SNAKE_CASE_     (					self     :						Union[str, Any]							,							UpperCAmelCase_     :						str):


         """simple docstring"""







         if len(self.translation_table) > 0:
              a					:							Any							= text.translate(self.translation_table)
         if len(self.words_to_remove) == 0:
              a					:							List[Any]							= ' '.join(text.split())  # clean up whitespaces
         else:
              a					:							Tuple							= ' '.join(w for w in text.split() if w not in self.words_to_remove)  # and clean up whilespaces
         return text







    def    SCREAMING_SNAKE_CASE_     (					self     :						int							,							UpperCAmelCase_     :						ModelArguments):


         """simple docstring"""







         a					:							int							= WavaVecaFeatureExtractor.from_pretrained(
             model_args.model_name_or_path							,							cache_dir=model_args.cache_dir)
         if self.vocab_file:
              a					:							List[Any]							= 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:
              a					:							Optional[Any]							= 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(UpperCAmelCase_							,							UpperCAmelCase_)






@dataclass
class   UpperCamelCase					:







    """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     :						Any							,							UpperCAmelCase_     :						List[Dict[str, Union[List[int], torch.Tensor]]]):


         """simple docstring"""







         a					:							Optional[int]							= [{'input_values': feature['input_values']} for feature in features]
         a					:							List[Any]							= [{'input_ids': feature['labels']} for feature in features]

         a					:							Any							= self.processor.pad(
             UpperCAmelCase_							,							padding=self.padding							,							max_length=self.max_length							,							pad_to_multiple_of=self.pad_to_multiple_of							,							return_tensors='pt'							,							)
         a					:							Any							= self.processor.pad(
             labels=UpperCAmelCase_							,							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
         a					:							Union[str, Any]							= labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1)							,							-1_0_0)

         a					:							List[str]							= labels

         return batch






class   UpperCamelCase					(       a_       ):







    """simple docstring"""





    def    SCREAMING_SNAKE_CASE_     (					self     :						Any							,							UpperCAmelCase_     :						nn.Module							,							UpperCAmelCase_     :						Dict[str, Union[torch.Tensor, Any]]):


         """simple docstring"""







         model.train()
         a					:							Optional[Any]							= self._prepare_inputs(UpperCAmelCase_)

         if self.use_amp:
              with autocast():
                   a					:							List[Any]							= self.compute_loss(UpperCAmelCase_							,							UpperCAmelCase_)
         else:
              a					:							Optional[Any]							= self.compute_loss(UpperCAmelCase_							,							UpperCAmelCase_)

         if self.args.n_gpu > 1:
              if model.module.config.ctc_loss_reduction == "mean":
                   a					:							List[str]							= loss.mean()
              elif model.module.config.ctc_loss_reduction == "sum":
                   a					:							Optional[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:
              a					:							Tuple							= loss / self.args.gradient_accumulation_steps

         if self.use_amp:
              self.scaler.scale(UpperCAmelCase_).backward()
         elif self.use_apex:
              with amp.scale_loss(UpperCAmelCase_							,							self.optimizer) as scaled_loss:
                   scaled_loss.backward()
         elif self.deepspeed:
              self.deepspeed.backward(UpperCAmelCase_)
         else:
              loss.backward()

         return loss.detach()






def SCREAMING_SNAKE_CASE__  (				)   ->				Any:







     """simple docstring"""
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.

     a					:							Dict							= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

     a							,			a							,			a					:							Union[str, Any]							= parser.parse_args_into_dataclasses()
     configure_logger(snake_case				,	snake_case  )

     a					:							Any							= Orthography.from_name(data_args.orthography.lower()  )
     a					:							List[Any]							= orthography.create_processor(snake_case  )
     a					:							Union[str, Any]							= 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  )				,	)

     a					:							List[str]							= datasets.load_dataset(
         data_args.dataset_name				,	data_args.dataset_config_name				,	split=data_args.train_split_name  )
     a					:							Any							= datasets.load_dataset(
         data_args.dataset_name				,	data_args.dataset_config_name				,	split=data_args.validation_split_name  )

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

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

     a					:							Union[str, Any]							= train_dataset.map(snake_case				,	remove_columns=[data_args.speech_file_column]  )
     a					:							Tuple							= val_dataset.map(snake_case				,	remove_columns=[data_args.speech_file_column]  )

     if data_args.max_duration_in_seconds is not None:

          def filter_by_max_duration(snake_case       :				Tuple  ):
               return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

     logger.warning(F"""Updated {len(snake_case  )} 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}\""""  )
     a					:							Union[str, Any]							= None

     def prepare_dataset(snake_case       :				List[str]  ):
          # 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}."""

          a					:							str							= processor(
              audio=batch['speech']				,	text=batch[data_args.target_text_column]				,	sampling_rate=batch['sampling_rate'][0]  )
          batch.update(snake_case  )
          return batch

     a					:							Optional[Any]							= train_dataset.map(
         snake_case				,	batch_size=training_args.per_device_train_batch_size				,	batched=snake_case				,	num_proc=data_args.preprocessing_num_workers				,	)
     a					:							Tuple							= val_dataset.map(
         snake_case				,	batch_size=training_args.per_device_train_batch_size				,	batched=snake_case				,	num_proc=data_args.preprocessing_num_workers				,	)

     a					:							Optional[int]							= DataCollatorCTCWithPadding(processor=snake_case				,	padding=snake_case  )

     def compute_metrics(snake_case       :				List[str]  ):
          a					:							List[Any]							= pred.predictions
          a					:							Any							= np.argmax(snake_case				,	axis=-1  )

          a					:							Dict							= processor.tokenizer.pad_token_id

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

          a					:							Tuple							= wer_metric.compute(predictions=snake_case				,	references=snake_case  )

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     a					:							int							= CTCTrainer(
         model=snake_case				,	data_collator=snake_case				,	args=snake_case				,	compute_metrics=snake_case				,	train_dataset=snake_case				,	eval_dataset=snake_case				,	tokenizer=processor.feature_extractor				,	)

     trainer.train()


if __name__ == "__main__":
      main()


'''simple docstring'''





from itertools import count
from math import asin, pi, sqrt






def SCREAMING_SNAKE_CASE__  (				snake_case       :				float  )   ->				float:







     """simple docstring"""
     return (
         (1 - 2 * point) * sqrt(point - point**2  ) + 2 * point + asin(sqrt(1 - point  )  )
     ) / 4






def SCREAMING_SNAKE_CASE__  (				snake_case       :				int  )   ->				float:







     """simple docstring"""
     a					:							List[str]							= (circles_number + 1 - sqrt(2 * circles_number  )) / (
         2 * (circles_number**2 + 1)
     )
     a					:							int							= circles_number * intersection_y

     a					:							List[Any]							= intersection_x * intersection_y / 2
     a					:							List[str]							= circle_bottom_arc_integral(
         1 / 2  ) - circle_bottom_arc_integral(snake_case  )

     return triangle_area + concave_region_area






def SCREAMING_SNAKE_CASE__  (				snake_case       :				float = 1 / 1_000  )   ->				int:







     """simple docstring"""
     a					:							str							= (1 - pi / 4) / 4

     for n in count(1  ):
          if concave_triangle_area(snake_case  ) / l_section_area < fraction:
               return n

     return -1


if __name__ == "__main__":
      print(f'''{solution() = }''')

