



"""simple docstring"""







import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


A    =			logging.get_logger(__name__)  # pylint: disable=invalid-name






class      UpperCAmelCase__		(      lowercase__     ):



		def __init__( self  :    Tuple      ,							snake_case  :    WhisperForConditionalGeneration      ,							snake_case  :    WhisperProcessor      ,							snake_case  :    AutoencoderKL      ,							snake_case  :    CLIPTextModel      ,							snake_case  :    CLIPTokenizer      ,							snake_case  :    UNetaDConditionModel      ,							snake_case  :    Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,							snake_case  :    StableDiffusionSafetyChecker      ,							snake_case  :    CLIPImageProcessor      ,							)			->						Union[str, Any]:






									'''simple docstring'''

									super().__init__()

									if safety_checker is None:
																logger.warning(
																    f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
																    ' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'
																    ' results in services or applications open to the public. Both the diffusers team and Hugging Face'
																    ' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'
																    ' it only for use-cases that involve analyzing network behavior or auditing its results. For more'
																    ' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .'				)

									self.register_modules(
									    speech_model=snake_case      ,							speech_processor=snake_case      ,							vae=snake_case      ,							text_encoder=snake_case      ,							tokenizer=snake_case      ,							unet=snake_case      ,							scheduler=snake_case      ,							feature_extractor=snake_case      ,							)



		def 					A_		( self  :    List[Any]      ,							snake_case  :    Optional[Union[str, int]] = "auto"				)			->						int:






									'''simple docstring'''

									if slice_size == "auto":
																A         =					self.unet.config.attention_head_dim // 2
									self.unet.set_attention_slice(snake_case				)



		def 					A_		( self  :    List[Any]				)			->						str:






									'''simple docstring'''

									self.enable_attention_slicing(snake_case				)



		@torch.no_grad()
		def __call__( self  :    str      ,							snake_case  :    str      ,							snake_case  :    Tuple=16_000      ,							snake_case  :    int = 512      ,							snake_case  :    int = 512      ,							snake_case  :    int = 50      ,							snake_case  :    float = 7.5      ,							snake_case  :    Optional[Union[str, List[str]]] = None      ,							snake_case  :    Optional[int] = 1      ,							snake_case  :    float = 0.0      ,							snake_case  :    Optional[torch.Generator] = None      ,							snake_case  :    Optional[torch.FloatTensor] = None      ,							snake_case  :    Optional[str] = "pil"      ,							snake_case  :    bool = True      ,							snake_case  :    Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,							snake_case  :    int = 1      ,							**snake_case  :    List[Any]      ,							)			->						Any:






									'''simple docstring'''

									A         =					self.speech_processor.feature_extractor(
									    snake_case      ,							return_tensors='pt'      ,							sampling_rate=snake_case				).input_features.to(self.device				)
									A         =					self.speech_model.generate(snake_case      ,							max_length=480_000				)

									A         =					self.speech_processor.tokenizer.batch_decode(snake_case      ,							skip_special_tokens=snake_case      ,							normalize=snake_case				)[
									    0
									]

									if isinstance(snake_case      ,							snake_case				):
																A         =					1
									elif isinstance(snake_case      ,							snake_case				):
																A         =					len(snake_case				)
									else:
																raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(snake_case				)}"""				)

									if height % 8 != 0 or width % 8 != 0:
																raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""				)

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(snake_case      ,							snake_case				) or callback_steps <= 0)
									):
																raise ValueError(
																    f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
																    f""" {type(snake_case				)}."""				)

									# get prompt text embeddings
									A         =					self.tokenizer(
									    snake_case      ,							padding='max_length'      ,							max_length=self.tokenizer.model_max_length      ,							return_tensors='pt'      ,							)
									A         =					text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
																A         =					self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]				)
																logger.warning(
																    'The following part of your input was truncated because CLIP can only handle sequences up to'
																    f""" {self.tokenizer.model_max_length} tokens: {removed_text}"""				)
																A         =					text_input_ids[:, : self.tokenizer.model_max_length]
									A         =					self.text_encoder(text_input_ids.to(self.device				)				)[0]

									# duplicate text embeddings for each generation per prompt, using mps friendly method
									A         =					text_embeddings.shape
									A         =					text_embeddings.repeat(1      ,							snake_case      ,							1				)
									A         =					text_embeddings.view(bs_embed * num_images_per_prompt      ,							snake_case      ,							-1				)

									# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
									# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
									# corresponds to doing no classifier free guidance.
									A         =					guidance_scale > 1.0
									# get unconditional embeddings for classifier free guidance
									if do_classifier_free_guidance:
																A         =					42
																if negative_prompt is None:
																							A         =					[""] * batch_size
																elif type(snake_case				) is not type(snake_case				):
																							raise TypeError(
																							    f"""`negative_prompt` should be the same type to `prompt`, but got {type(snake_case				)} !="""
																							    f""" {type(snake_case				)}."""				)
																elif isinstance(snake_case      ,							snake_case				):
																							A         =					[negative_prompt]
																elif batch_size != len(snake_case				):
																							raise ValueError(
																							    f"""`negative_prompt`: {negative_prompt} has batch size {len(snake_case				)}, but `prompt`:"""
																							    f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
																							    ' the batch size of `prompt`.'				)
																else:
																							A         =					negative_prompt

																A         =					text_input_ids.shape[-1]
																A         =					self.tokenizer(
																    snake_case      ,							padding='max_length'      ,							max_length=snake_case      ,							truncation=snake_case      ,							return_tensors='pt'      ,							)
																A         =					self.text_encoder(uncond_input.input_ids.to(self.device				)				)[0]

																# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
																A         =					uncond_embeddings.shape[1]
																A         =					uncond_embeddings.repeat(1      ,							snake_case      ,							1				)
																A         =					uncond_embeddings.view(batch_size * num_images_per_prompt      ,							snake_case      ,							-1				)

																# For classifier free guidance, we need to do two forward passes.
																# Here we concatenate the unconditional and text embeddings into a single batch
																# to avoid doing two forward passes
																A         =					torch.cat([uncond_embeddings, text_embeddings]				)

									# get the initial random noise unless the user supplied it

									# Unlike in other pipelines, latents need to be generated in the target device
									# for 1-to-1 results reproducibility with the CompVis implementation.
									# However this currently doesn't work in `mps`.
									A         =					(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
									A         =					text_embeddings.dtype
									if latents is None:
																if self.device.type == "mps":
																							# randn does not exist on mps
																							A         =					torch.randn(snake_case      ,							generator=snake_case      ,							device='cpu'      ,							dtype=snake_case				).to(
																							    self.device				)
																else:
																							A         =					torch.randn(snake_case      ,							generator=snake_case      ,							device=self.device      ,							dtype=snake_case				)
									else:
																if latents.shape != latents_shape:
																							raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""				)
																A         =					latents.to(self.device				)

									# set timesteps
									self.scheduler.set_timesteps(snake_case				)

									# Some schedulers like PNDM have timesteps as arrays
									# It's more optimized to move all timesteps to correct device beforehand
									A         =					self.scheduler.timesteps.to(self.device				)

									# scale the initial noise by the standard deviation required by the scheduler
									A         =					latents * self.scheduler.init_noise_sigma

									# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
									# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
									# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
									# and should be between [0, 1]
									A         =					"eta" in set(inspect.signature(self.scheduler.step				).parameters.keys()				)
									A         =					{}
									if accepts_eta:
																A         =					eta

									for i, t in enumerate(self.progress_bar(snake_case				)				):
																# expand the latents if we are doing classifier free guidance
																A         =					torch.cat([latents] * 2				) if do_classifier_free_guidance else latents
																A         =					self.scheduler.scale_model_input(snake_case      ,							snake_case				)

																# predict the noise residual
																A         =					self.unet(snake_case      ,							snake_case      ,							encoder_hidden_states=snake_case				).sample

																# perform guidance
																if do_classifier_free_guidance:
																							A         =					noise_pred.chunk(2				)
																							A         =					noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

																# compute the previous noisy sample x_t -> x_t-1
																A         =					self.scheduler.step(snake_case      ,							snake_case      ,							snake_case      ,							**snake_case				).prev_sample

																# call the callback, if provided
																if callback is not None and i % callback_steps == 0:
																							callback(snake_case      ,							snake_case      ,							snake_case				)

									A         =					1 / 0.18215 * latents
									A         =					self.vae.decode(snake_case				).sample

									A         =					(image / 2 + 0.5).clamp(0      ,							1				)

									# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
									A         =					image.cpu().permute(0      ,							2      ,							3      ,							1				).float().numpy()

									if output_type == "pil":
																A         =					self.numpy_to_pil(snake_case				)

									if not return_dict:
																return image

									return StableDiffusionPipelineOutput(images=snake_case      ,							nsfw_content_detected=snake_case				)








"""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


A    =			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   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__ = 16000			) ->							Union[str, Any]:
							A         =					int(round(sample_rate * max_length			)			)
							if len(lowerCamelCase__			) <= sample_length:
														return wav
							A         =					randint(0				,      len(lowerCamelCase__			) - sample_length - 1			)
							return wav[random_offset : random_offset + sample_length]






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






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



		def 					A_		( self  :    List[str]				)			->						str:






									'''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`.'      ,							snake_case      ,							)
									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   lowerCAmelCase__			(     ) ->							str:
							# 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         =					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.
														A      ,  A      ,  A         =					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
							else:
														A      ,  A      ,  A         =					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()

							A         =					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.
							A         =					None
							if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
														A         =					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.
							A         =					DatasetDict()
							A         =					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				,      )
							A         =					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
							A         =					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.
							A         =					raw_datasets.cast_column(
							    data_args.audio_column_name				,      datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate			)			)

							A         =					feature_extractor.model_input_names[0]

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

														return output_batch

							def val_transforms(lowerCamelCase__			):
														A         =					[audio['array'] for audio in batch[data_args.audio_column_name]]
														A         =					feature_extractor(lowerCamelCase__				,      sampling_rate=feature_extractor.sampling_rate			)
														A         =					{model_input_name: inputs.get(lowerCamelCase__			)}
														A         =					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.
							A         =					raw_datasets['train'].features[data_args.label_column_name].names
							A      ,  A         =					{}, {}
							for i, label in enumerate(lowerCamelCase__			):
														A         =					str(lowerCamelCase__			)
														A         =					label

							# Load the accuracy metric from the datasets package
							A         =					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__			):
														A         =					np.argmax(eval_pred.predictions				,      axis=1			)
														return metric.compute(predictions=lowerCamelCase__				,      references=eval_pred.label_ids			)

							A         =					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				,      )
							A         =					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:
																					A         =					(
																					    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:
																					A         =					(
																					    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
							A         =					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:
														A         =					None
														if training_args.resume_from_checkpoint is not None:
																					A         =					training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					A         =					last_checkpoint
														A         =					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:
														A         =					trainer.evaluate()
														trainer.log_metrics('eval'				,      lowerCamelCase__			)
														trainer.save_metrics('eval'				,      lowerCamelCase__			)

							# Write model card and (optionally) push to hub
							A         =					{
							    '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()



