






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


_A      :	Tuple       		=	logging.getLogger(__name__)

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


def   __magic_name__     (				__snake_case    :	Any					,			__snake_case    :	Optional[Any]  )			->    Union[str, Any]:
       logging.basicConfig(
           format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"					,			datefmt="%m/%d/%Y %H:%M:%S"					,			handlers=[logging.StreamHandler(sys.stdout  )]					,			)
       lowercase   :    Any			=							logging.WARNING
       if model_args.verbose_logging:
              lowercase   :    Optional[Any]			=							logging.DEBUG
       elif trainer_utils.is_main_process(training_args.local_rank  ):
              lowercase   :    Dict			=							logging.INFO
       logger.setLevel(_A  )

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


@dataclass
class 		a__						:
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    """|"""
   __lowerCAmelCase						=    field(default_factory=UpperCAmelCase__						)
   __lowerCAmelCase						=    field(default_factory=UpperCAmelCase__						)
   __lowerCAmelCase						=    None
   @classmethod
   def       __magic_name__      (      cls     ,   _a    ):






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






          if len(self.translation_table    ) > 0:
                 lowercase   :    Union[str, Any]			=							text.translate(self.translation_table    )
          if len(self.words_to_remove    ) == 0:
                 lowercase   :    Any			=							" ".join(text.split()    )  # clean up whitespaces
          else:
                 lowercase   :    Optional[int]			=							" ".join(w for w in text.split() if w not in self.words_to_remove    )  # and clean up whilespaces
          return text

   def       __magic_name__      (      self     ,   _a    ):
          lowercase   :    Dict			=							WavaVecaFeatureExtractor.from_pretrained(
              model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir    )
          if self.vocab_file:
                 lowercase   :    int			=							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   :    str			=							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(__lowercase     ,   __lowercase    )


@dataclass
class 		a__						:
   __lowerCAmelCase						=    42
   __lowerCAmelCase						=    True
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   def __call__(      self     ,   _a    ):
          lowercase   :    int			=							[{"input_values": feature["input_values"]} for feature in features]
          lowercase   :    Optional[Any]			=							[{"input_ids": feature["labels"]} for feature in features]

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

          lowercase   :    Tuple			=							labels

          return batch


class 		a__						(				UpperCAmelCase__						):
   def       __magic_name__      (      self     ,   _a     ,   _a    ):
          model.train()
          lowercase   :    int			=							self._prepare_inputs(__lowercase    )

          if self.use_amp:
                 with autocast():
                        lowercase   :    Any			=							self.compute_loss(__lowercase     ,   __lowercase    )
          else:
                 lowercase   :    int			=							self.compute_loss(__lowercase     ,   __lowercase    )

          if self.args.n_gpu > 1:
                 if model.module.config.ctc_loss_reduction == "mean":
                        lowercase   :    Dict			=							loss.mean()
                 elif model.module.config.ctc_loss_reduction == "sum":
                        lowercase   :    Tuple			=							loss.sum() / (inputs["labels"] >= 0).sum()
                 else:
                        raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']"""    )

          if self.args.gradient_accumulation_steps > 1:
                 lowercase   :    List[str]			=							loss / self.args.gradient_accumulation_steps

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

          return loss.detach()


def   __magic_name__     (				)			->    Tuple:
       lowercase   :    str			=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

       lowercase		,   lowercase		,   lowercase   :    Dict			=							parser.parse_args_into_dataclasses()
       configure_logger(_A					,			_A  )

       lowercase   :    Tuple			=							Orthography.from_name(data_args.orthography.lower()  )
       lowercase   :    Tuple			=							orthography.create_processor(_A  )
       lowercase   :    List[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  )					,			)

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

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

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

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

              lowercase   :    int			=							len(_A  )
              lowercase   :    int			=							len(_A  )
              lowercase   :    Optional[int]			=							train_dataset.filter(_A					,			remove_columns=["duration_in_seconds"]  )
              lowercase   :    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}\""""  )
       lowercase   :    Dict			=							None

       def prepare_dataset(__snake_case    :	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}."""

              lowercase   :    int			=							processor(
                  audio=batch["speech"]					,			text=batch[data_args.target_text_column]					,			sampling_rate=batch["sampling_rate"][0]  )
              batch.update(_A  )
              return batch

       lowercase   :    int			=							train_dataset.map(
           _A					,			batch_size=training_args.per_device_train_batch_size					,			batched=_A					,			num_proc=data_args.preprocessing_num_workers					,			)
       lowercase   :    int			=							val_dataset.map(
           _A					,			batch_size=training_args.per_device_train_batch_size					,			batched=_A					,			num_proc=data_args.preprocessing_num_workers					,			)

       lowercase   :    str			=							DataCollatorCTCWithPadding(processor=_A					,			padding=_A  )

       def compute_metrics(__snake_case    :	Union[str, Any]  ):
              lowercase   :    Tuple			=							pred.predictions
              lowercase   :    Any			=							np.argmax(_A					,			axis=-1  )

              lowercase   :    Union[str, Any]			=							processor.tokenizer.pad_token_id

              lowercase   :    Tuple			=							processor.batch_decode(_A  )
              # we do not want to group tokens when computing the metrics
              lowercase   :    Union[str, 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  )}\""""  )

              lowercase   :    Optional[Any]			=							wer_metric.compute(predictions=_A					,			references=_A  )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       lowercase   :    str			=							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()




"""simple docstring"""




import unittest

import numpy as np
import torch

from diffusers import DDPMPipeline, DDPMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device


enable_full_determinism()

class 		a__						(				unittest.TestCase						):
   @property
   def       __magic_name__      (      self    ):
          torch.manual_seed(0    )
          lowercase   :    int			=							UNetaDModel(
              block_out_channels=(32, 64)     ,   layers_per_block=2     ,   sample_size=32     ,   in_channels=3     ,   out_channels=3     ,   down_block_types=("DownBlock2D", "AttnDownBlock2D")     ,   up_block_types=("AttnUpBlock2D", "UpBlock2D")     ,   )
          return model
   def       __magic_name__      (      self    ):
          lowercase   :    int			=							"cpu"
          lowercase   :    Dict			=							self.dummy_uncond_unet
          lowercase   :    List[str]			=							DDPMScheduler()

          lowercase   :    Tuple			=							DDPMPipeline(unet=_a     ,   scheduler=_a    )
          ddpm.to(_a    )
          ddpm.set_progress_bar_config(disable=_a    )

          lowercase   :    Optional[int]			=							torch.Generator(device=_a    ).manual_seed(0    )
          lowercase   :    Optional[int]			=							ddpm(generator=_a     ,   num_inference_steps=2     ,   output_type="numpy"    ).images

          lowercase   :    List[str]			=							torch.Generator(device=_a    ).manual_seed(0    )
          lowercase   :    List[str]			=							ddpm(generator=_a     ,   num_inference_steps=2     ,   output_type="numpy"     ,   return_dict=_a    )[0]

          lowercase   :    List[str]			=							image[0, -3:, -3:, -1]
          lowercase   :    Any			=							image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          lowercase   :    List[str]			=							np.array(
              [9.956E-01, 5.785E-01, 4.675E-01, 9.930E-01, 0.0, 1.0_0_0, 1.199E-03, 2.648E-04, 5.101E-04]    )

          assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2
          assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1E-2

   def       __magic_name__      (      self    ):
          lowercase   :    Any			=							self.dummy_uncond_unet
          lowercase   :    Dict			=							DDPMScheduler(prediction_type="sample"    )

          lowercase   :    List[Any]			=							DDPMPipeline(unet=_a     ,   scheduler=_a    )
          ddpm.to(_a    )
          ddpm.set_progress_bar_config(disable=_a    )

          lowercase   :    Any			=							torch.manual_seed(0    )
          lowercase   :    int			=							ddpm(generator=_a     ,   num_inference_steps=2     ,   output_type="numpy"    ).images

          lowercase   :    List[str]			=							torch.manual_seed(0    )
          lowercase   :    Optional[Any]			=							ddpm(generator=_a     ,   num_inference_steps=2     ,   output_type="numpy"    )[0]

          lowercase   :    Any			=							image[0, -3:, -3:, -1]
          lowercase   :    Dict			=							image_eps[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          lowercase   :    Tuple			=							1E-2 if torch_device != "mps" else 3E-2
          assert np.abs(image_slice.flatten() - image_eps_slice.flatten()    ).max() < tolerance


@slow
@require_torch_gpu
class 		a__						(				unittest.TestCase						):
   def       __magic_name__      (      self    ):
          lowercase   :    Optional[Any]			=							"google/ddpm-cifar10-32"

          lowercase   :    Dict			=							UNetaDModel.from_pretrained(_a    )
          lowercase   :    str			=							DDPMScheduler.from_pretrained(_a    )

          lowercase   :    int			=							DDPMPipeline(unet=_a     ,   scheduler=_a    )
          ddpm.to(_a    )
          ddpm.set_progress_bar_config(disable=_a    )

          lowercase   :    Dict			=							torch.manual_seed(0    )
          lowercase   :    List[str]			=							ddpm(generator=_a     ,   output_type="numpy"    ).images

          lowercase   :    int			=							image[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          lowercase   :    Optional[Any]			=							np.array([0.4_2_0_0, 0.3_5_8_8, 0.1_9_3_9, 0.3_8_4_7, 0.3_3_8_2, 0.2_6_4_7, 0.4_1_5_5, 0.3_5_8_2, 0.3_3_8_5]    )
          assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2


