'''simple docstring'''




import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


snake_case	=      logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''')







def       A_ (			_lowerCamelCase      :				int	,	_lowerCamelCase      :				Any	,	_lowerCamelCase      :				Tuple = 16_000     ):
      _lowerCAmelCase		 = int(round(sample_rate * max_length     )     )
      if len(_lowerCamelCase     ) <= sample_length:
            return wav
      _lowerCAmelCase		 = randint(0	,	len(_lowerCamelCase     ) - sample_length - 1     )
      return wav[random_offset : random_offset + sample_length]





@dataclass
class 							SCREAMING_SNAKE_CASE :
  """simple docstring"""







  __A  =		field(default=lowercase_						,    metadata={"help": "Name of a dataset from the datasets package"}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "A file containing the training audio paths and labels."}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "A file containing the validation audio paths and labels."}			)
  __A  =		field(
      default="train"						,    metadata={
          "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
      }						,    )
  __A  =		field(
      default="validation"						,    metadata={
          "help": (
              "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
          )
      }						,    )
  __A  =		field(
      default="audio"						,    metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}						,    )
  __A  =		field(
      default="label"						,    metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}			)
  __A  =		field(
      default=lowercase_						,    metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of training examples to this "
              "value if set."
          )
      }						,    )
  __A  =		field(
      default=lowercase_						,    metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
              "value if set."
          )
      }						,    )
  __A  =		field(
      default=20						,    metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}						,    )





@dataclass
class 							SCREAMING_SNAKE_CASE :
  """simple docstring"""







  __A  =		field(
      default="facebook/wav2vec2-base"						,    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}						,    )
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}			)
  __A  =		field(
      default="main"						,    metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}						,    )
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Name or path of preprocessor config."}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Whether to freeze the feature encoder layers of the model."}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Whether to generate an attention mask in the feature extractor."}			)
  __A  =		field(
      default=lowercase_						,    metadata={
          "help": (
              "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
              "with private models)."
          )
      }						,    )
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Whether to freeze the feature extractor layers of the model."}			)
  __A  =		field(
      default=lowercase_						,    metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}						,    )



  def 	a (	self :       int       ):


        """simple docstring"""



        if not self.freeze_feature_extractor and self.freeze_feature_encoder:
              warnings.warn(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'will be removed in a future version. Use `--freeze_feature_encoder`'
                  'instead. Setting `freeze_feature_encoder==True`.'       ,       __lowerCAmelCase       ,       )
        if self.freeze_feature_extractor and not self.freeze_feature_encoder:
              raise ValueError(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'should not be used in combination with `--freeze_feature_encoder`.'
                  'Only make use of `--freeze_feature_encoder`.'       )







def       A_ (			):
      _lowerCAmelCase		 = 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.
            _lowerCAmelCase ,	_lowerCAmelCase ,	_lowerCAmelCase		 = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
      else:
            _lowerCAmelCase ,	_lowerCAmelCase ,	_lowerCAmelCase		 = parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry('run_audio_classification'	,	_lowerCamelCase	,	_lowerCamelCase     )

      # 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     )]	,	)

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      _lowerCAmelCase		 = training_args.get_process_log_level()
      logger.setLevel(_lowerCamelCase     )
      transformers.utils.logging.set_verbosity(_lowerCamelCase     )
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # 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}"     )
      logger.info(F"Training/evaluation parameters {training_args}"     )

      # Set seed before initializing model.
      set_seed(training_args.seed     )

      # Detecting last checkpoint.
      _lowerCAmelCase		 = None
      if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
            _lowerCAmelCase		 = 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 train from scratch.'     )
            elif last_checkpoint is not None and training_args.resume_from_checkpoint is 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.'     )

    # Initialize our dataset and prepare it for the audio classification task.
      _lowerCAmelCase		 = DatasetDict()
      _lowerCAmelCase		 = load_dataset(
          data_args.dataset_name	,	data_args.dataset_config_name	,	split=data_args.train_split_name	,	use_auth_token=True if model_args.use_auth_token else None	,	)
      _lowerCAmelCase		 = load_dataset(
          data_args.dataset_name	,	data_args.dataset_config_name	,	split=data_args.eval_split_name	,	use_auth_token=True if model_args.use_auth_token else None	,	)

      if data_args.audio_column_name not in raw_datasets["train"].column_names:
            raise ValueError(
                F"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
                'Make sure to set `--audio_column_name` to the correct audio column - one of '
                F"{', '.join(raw_datasets['train'].column_names     )}."     )

      if data_args.label_column_name not in raw_datasets["train"].column_names:
            raise ValueError(
                F"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
                'Make sure to set `--label_column_name` to the correct text column - one of '
                F"{', '.join(raw_datasets['train'].column_names     )}."     )

      # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
      # transformer outputs in the classifier, but it doesn't always lead to better accuracy
      _lowerCAmelCase		 = AutoFeatureExtractor.from_pretrained(
          model_args.feature_extractor_name or model_args.model_name_or_path	,	return_attention_mask=model_args.attention_mask	,	cache_dir=model_args.cache_dir	,	revision=model_args.model_revision	,	use_auth_token=True if model_args.use_auth_token else None	,	)

      # `datasets` takes care of automatically loading and resampling the audio,
      # so we just need to set the correct target sampling rate.
      _lowerCAmelCase		 = raw_datasets.cast_column(
          data_args.audio_column_name	,	datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate     )     )

      _lowerCAmelCase		 = feature_extractor.model_input_names[0]

      def train_transforms(_lowerCamelCase      :				Any     ):
            _lowerCAmelCase		 = []
            for audio in batch[data_args.audio_column_name]:
                  _lowerCAmelCase		 = random_subsample(
                      audio['array']	,	max_length=data_args.max_length_seconds	,	sample_rate=feature_extractor.sampling_rate     )
                  subsampled_wavs.append(_lowerCamelCase     )
            _lowerCAmelCase		 = feature_extractor(_lowerCamelCase	,	sampling_rate=feature_extractor.sampling_rate     )
            _lowerCAmelCase		 = {model_input_name: inputs.get(_lowerCamelCase     )}
            _lowerCAmelCase		 = list(batch[data_args.label_column_name]     )

            return output_batch

      def val_transforms(_lowerCamelCase      :				int     ):
            _lowerCAmelCase		 = [audio['array'] for audio in batch[data_args.audio_column_name]]
            _lowerCAmelCase		 = feature_extractor(_lowerCamelCase	,	sampling_rate=feature_extractor.sampling_rate     )
            _lowerCAmelCase		 = {model_input_name: inputs.get(_lowerCamelCase     )}
            _lowerCAmelCase		 = list(batch[data_args.label_column_name]     )

            return output_batch

      # Prepare label mappings.
      # We'll include these in the model's config to get human readable labels in the Inference API.
      _lowerCAmelCase		 = raw_datasets['train'].features[data_args.label_column_name].names
      _lowerCAmelCase ,	_lowerCAmelCase		 = {}, {}
      for i, label in enumerate(_lowerCamelCase     ):
            _lowerCAmelCase		 = str(_lowerCamelCase     )
            _lowerCAmelCase		 = label

      # Load the accuracy metric from the datasets package
      _lowerCAmelCase		 = evaluate.load('accuracy'     )

      # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
      # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
      def compute_metrics(_lowerCamelCase      :				List[Any]     ):
            _lowerCAmelCase		 = np.argmax(eval_pred.predictions	,	axis=1     )
            return metric.compute(predictions=_lowerCamelCase	,	references=eval_pred.label_ids     )

      _lowerCAmelCase		 = AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path	,	num_labels=len(_lowerCamelCase     )	,	labelaid=_lowerCamelCase	,	idalabel=_lowerCamelCase	,	finetuning_task='audio-classification'	,	cache_dir=model_args.cache_dir	,	revision=model_args.model_revision	,	use_auth_token=True if model_args.use_auth_token else None	,	)
      _lowerCAmelCase		 = AutoModelForAudioClassification.from_pretrained(
          model_args.model_name_or_path	,	from_tf=bool('.ckpt' in model_args.model_name_or_path     )	,	config=_lowerCamelCase	,	cache_dir=model_args.cache_dir	,	revision=model_args.model_revision	,	use_auth_token=True if model_args.use_auth_token else None	,	ignore_mismatched_sizes=model_args.ignore_mismatched_sizes	,	)

      # freeze the convolutional waveform encoder
      if model_args.freeze_feature_encoder:
            model.freeze_feature_encoder()

      if training_args.do_train:
            if data_args.max_train_samples is not None:
                  _lowerCAmelCase		 = (
                      raw_datasets['train'].shuffle(seed=training_args.seed     ).select(range(data_args.max_train_samples     )     )
                  )
            # Set the training transforms
            raw_datasets["train"].set_transform(_lowerCamelCase	,	output_all_columns=_lowerCamelCase     )

      if training_args.do_eval:
            if data_args.max_eval_samples is not None:
                  _lowerCAmelCase		 = (
                      raw_datasets['eval'].shuffle(seed=training_args.seed     ).select(range(data_args.max_eval_samples     )     )
                  )
            # Set the validation transforms
            raw_datasets["eval"].set_transform(_lowerCamelCase	,	output_all_columns=_lowerCamelCase     )

      # Initialize our trainer
      _lowerCAmelCase		 = Trainer(
          model=_lowerCamelCase	,	args=_lowerCamelCase	,	train_dataset=raw_datasets['train'] if training_args.do_train else None	,	eval_dataset=raw_datasets['eval'] if training_args.do_eval else None	,	compute_metrics=_lowerCamelCase	,	tokenizer=_lowerCamelCase	,	)

      # Training
      if training_args.do_train:
            _lowerCAmelCase		 = None
            if training_args.resume_from_checkpoint is not None:
                  _lowerCAmelCase		 = training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  _lowerCAmelCase		 = last_checkpoint
            _lowerCAmelCase		 = trainer.train(resume_from_checkpoint=_lowerCamelCase     )
            trainer.save_model()
            trainer.log_metrics('train'	,	train_result.metrics     )
            trainer.save_metrics('train'	,	train_result.metrics     )
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            _lowerCAmelCase		 = trainer.evaluate()
            trainer.log_metrics('eval'	,	_lowerCamelCase     )
            trainer.save_metrics('eval'	,	_lowerCamelCase     )

      # Write model card and (optionally) push to hub
      _lowerCAmelCase		 = {
          'finetuned_from': model_args.model_name_or_path,
          'tasks': 'audio-classification',
          'dataset': data_args.dataset_name,
          'tags': ['audio-classification'],
      }
      if training_args.push_to_hub:
            trainer.push_to_hub(**_lowerCamelCase     )
      else:
            trainer.create_model_card(**_lowerCamelCase     )


if __name__ == "__main__":
 main()









'''simple docstring'''

import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
 lowerCamelCase				:  int    		=      argparse.ArgumentParser()

 parser.add_argument(
     '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
 )
 # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
 parser.add_argument(
     '--original_config_file',
     default=None,
     type=str,
     help='The YAML config file corresponding to the original architecture.',
 )
 parser.add_argument(
     '--num_in_channels',
     default=None,
     type=int,
     help='The number of input channels. If `None` number of input channels will be automatically inferred.',
 )
 parser.add_argument(
     '--scheduler_type',
     default='pndm',
     type=str,
     help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']',
 )
 parser.add_argument(
     '--pipeline_type',
     default=None,
     type=str,
     help=(
         'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\''
         '. If `None` pipeline will be automatically inferred.'
     ),
 )
 parser.add_argument(
     '--image_size',
     default=None,
     type=int,
     help=(
         'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
         ' Base. Use 768 for Stable Diffusion v2.'
     ),
 )
 parser.add_argument(
     '--prediction_type',
     default=None,
     type=str,
     help=(
         'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable'
         ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.'
     ),
 )
 parser.add_argument(
     '--extract_ema',
     action='store_true',
     help=(
         'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
         ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
         ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
     ),
 )
 parser.add_argument(
     '--upcast_attention',
     action='store_true',
     help=(
         'Whether the attention computation should always be upcasted. This is necessary when running stable'
         ' diffusion 2.1.'
     ),
 )
 parser.add_argument(
     '--from_safetensors',
     action='store_true',
     help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
 )
 parser.add_argument(
     '--to_safetensors',
     action='store_true',
     help='Whether to store pipeline in safetensors format or not.',
 )
 parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
 parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
 parser.add_argument(
     '--stable_unclip',
     type=str,
     default=None,
     required=False,
     help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.',
 )
 parser.add_argument(
     '--stable_unclip_prior',
     type=str,
     default=None,
     required=False,
     help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.',
 )
 parser.add_argument(
     '--clip_stats_path',
     type=str,
     help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.',
     required=False,
 )
 parser.add_argument(
     '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.'
 )
 parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
 parser.add_argument(
     '--vae_path',
     type=str,
     default=None,
     required=False,
     help='Set to a path, hub id to an already converted vae to not convert it again.',
 )
 lowerCamelCase				:  str    		=      parser.parse_args()

 lowerCamelCase				:  Tuple    		=      download_from_original_stable_diffusion_ckpt(
     checkpoint_path=args.checkpoint_path,
     original_config_file=args.original_config_file,
     image_size=args.image_size,
     prediction_type=args.prediction_type,
     model_type=args.pipeline_type,
     extract_ema=args.extract_ema,
     scheduler_type=args.scheduler_type,
     num_in_channels=args.num_in_channels,
     upcast_attention=args.upcast_attention,
     from_safetensors=args.from_safetensors,
     device=args.device,
     stable_unclip=args.stable_unclip,
     stable_unclip_prior=args.stable_unclip_prior,
     clip_stats_path=args.clip_stats_path,
     controlnet=args.controlnet,
     vae_path=args.vae_path,
 )

 if args.half:
  pipe.to(torch_dtype=torch.floataa)

 if args.controlnet:
  # only save the controlnet model
  pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
 else:
  pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)




