




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


UpperCAmelCase_		:				List[str]									=     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   ):
				__magic_name__	:	List[Any]								=int(round(sample_rate * max_length   )   )
				if len(lowerCamelCase   ) <= sample_length:
								return wav
				__magic_name__	:	Dict								=randint(0	,     len(lowerCamelCase   ) - sample_length - 1   )
				return wav[random_offset : random_offset + sample_length]




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




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

						def     A__						(		self   :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_   (	):
				# 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.

				__magic_name__	:	Union[str, Any]								=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
				if len(sys.argv   ) == 2 and sys.argv[1].endswith(""".json"""   ):
								# If we pass only one argument to the script and it's the path to a json file,
								# let's parse it to get our arguments.
								__magic_name__				, __magic_name__				, __magic_name__	:	Optional[int]								=parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
				else:
								__magic_name__				, __magic_name__				, __magic_name__	:	List[str]								=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()

				__magic_name__	:	str								=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.
				__magic_name__	:	Tuple								=None
				if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
								__magic_name__	:	List[str]								=get_last_checkpoint(training_args.output_dir   )
								if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
												raise ValueError(
												    F"Output directory ({training_args.output_dir}) already exists and is not empty. "
												    """Use --overwrite_output_dir to 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.
				__magic_name__	:	str								=DatasetDict()
				__magic_name__	:	Optional[int]								=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	,     )
				__magic_name__	:	List[Any]								=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
				__magic_name__	:	List[str]								=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.
				__magic_name__	:	str								=raw_datasets.cast_column(
				    data_args.audio_column_name	,     datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate   )   )

				__magic_name__	:	Any								=feature_extractor.model_input_names[0]

				def train_transforms(lowerCamelCase   ):
								__magic_name__	:	Optional[int]								=[]
								for audio in batch[data_args.audio_column_name]:
												__magic_name__	:	int								=random_subsample(
												    audio["""array"""]	,     max_length=data_args.max_length_seconds	,     sample_rate=feature_extractor.sampling_rate   )
												subsampled_wavs.append(lowerCamelCase   )
								__magic_name__	:	int								=feature_extractor(lowerCamelCase	,     sampling_rate=feature_extractor.sampling_rate   )
								__magic_name__	:	Optional[Any]								={model_input_name: inputs.get(lowerCamelCase   )}
								__magic_name__	:	Union[str, Any]								=list(batch[data_args.label_column_name]   )

								return output_batch

				def val_transforms(lowerCamelCase   ):
								__magic_name__	:	Union[str, Any]								=[audio["""array"""] for audio in batch[data_args.audio_column_name]]
								__magic_name__	:	Tuple								=feature_extractor(lowerCamelCase	,     sampling_rate=feature_extractor.sampling_rate   )
								__magic_name__	:	Tuple								={model_input_name: inputs.get(lowerCamelCase   )}
								__magic_name__	:	List[str]								=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.
				__magic_name__	:	Tuple								=raw_datasets["""train"""].features[data_args.label_column_name].names
				__magic_name__				, __magic_name__	:	Union[str, Any]								={}, {}
				for i, label in enumerate(lowerCamelCase   ):
								__magic_name__	:	Optional[int]								=str(lowerCamelCase   )
								__magic_name__	:	Dict								=label

				# Load the accuracy metric from the datasets package
				__magic_name__	:	Tuple								=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   ):
								__magic_name__	:	Optional[int]								=np.argmax(eval_pred.predictions	,     axis=1   )
								return metric.compute(predictions=lowerCamelCase	,     references=eval_pred.label_ids   )

				__magic_name__	:	str								=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	,     )
				__magic_name__	:	Optional[Any]								=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:
												__magic_name__	:	Dict								=(
												    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:
												__magic_name__	:	Dict								=(
												    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
				__magic_name__	:	str								=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:
								__magic_name__	:	Dict								=None
								if training_args.resume_from_checkpoint is not None:
												__magic_name__	:	Optional[Any]								=training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												__magic_name__	:	str								=last_checkpoint
								__magic_name__	:	str								=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:
								__magic_name__	:	Any								=trainer.evaluate()
								trainer.log_metrics("""eval"""	,     lowerCamelCase   )
								trainer.save_metrics("""eval"""	,     lowerCamelCase   )

				# Write model card and (optionally) push to hub
				__magic_name__	:	Optional[Any]								={
				    """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()










import argparse
import re

import torch
from CLAP import create_model

from transformers import AutoFeatureExtractor, ClapConfig, ClapModel


UpperCAmelCase_		:				Optional[int]									=     {
    "text_branch": "text_model",
    "audio_branch": "audio_model.audio_encoder",
    "attn": "attention.self",
    "self.proj": "output.dense",
    "attention.self_mask": "attn_mask",
    "mlp.fc1": "intermediate.dense",
    "mlp.fc2": "output.dense",
    "norm1": "layernorm_before",
    "norm2": "layernorm_after",
    "bn0": "batch_norm",
}

UpperCAmelCase_		:				Optional[int]									=     AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused", truncation="rand_trunc")




def 		lowerCAmelCase_   (	lowerCamelCase	,     lowerCamelCase=False   ):
				__magic_name__				, __magic_name__	:	Any								=create_model(
				    """HTSAT-tiny"""	,     """roberta"""	,     lowerCamelCase	,     precision="""fp32"""	,     device="""cuda:0""" if torch.cuda.is_available() else """cpu"""	,     enable_fusion=lowerCamelCase	,     fusion_type="""aff_2d""" if enable_fusion else None	,     )
				return model, model_cfg




def 		lowerCAmelCase_   (	lowerCamelCase   ):
				__magic_name__	:	Optional[int]								={}

				__magic_name__	:	Union[str, Any]								=R""".*sequential.(\d+).*"""
				__magic_name__	:	Union[str, Any]								=R""".*_projection.(\d+).*"""

				for key, value in state_dict.items():
								# check if any key needs to be modified
								for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
												if key_to_modify in key:
																__magic_name__	:	Union[str, Any]								=key.replace(lowerCamelCase	,     lowerCamelCase   )

								if re.match(lowerCamelCase	,     lowerCamelCase   ):
												# replace sequential layers with list
												__magic_name__	:	str								=re.match(lowerCamelCase	,     lowerCamelCase   ).group(1   )

												__magic_name__	:	Optional[Any]								=key.replace(F"sequential.{sequential_layer}."	,     F"layers.{int(lowerCamelCase   )//3}.linear."   )
								elif re.match(lowerCamelCase	,     lowerCamelCase   ):
												__magic_name__	:	Any								=int(re.match(lowerCamelCase	,     lowerCamelCase   ).group(1   )   )

												# Because in CLAP they use `nn.Sequential`...
												__magic_name__	:	int								=1 if projecton_layer == 0 else 2

												__magic_name__	:	List[Any]								=key.replace(F"_projection.{projecton_layer}."	,     F"_projection.linear{transformers_projection_layer}."   )

								if "audio" and "qkv" in key:
												# split qkv into query key and value
												__magic_name__	:	Dict								=value
												__magic_name__	:	List[str]								=mixed_qkv.size(0   ) // 3

												__magic_name__	:	Optional[Any]								=mixed_qkv[:qkv_dim]
												__magic_name__	:	Any								=mixed_qkv[qkv_dim : qkv_dim * 2]
												__magic_name__	:	Optional[Any]								=mixed_qkv[qkv_dim * 2 :]

												__magic_name__	:	str								=query_layer
												__magic_name__	:	int								=key_layer
												__magic_name__	:	str								=value_layer
								else:
												__magic_name__	:	int								=value

				return model_state_dict




def 		lowerCAmelCase_   (	lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase=False   ):
				__magic_name__				, __magic_name__	:	Tuple								=init_clap(lowerCamelCase	,     enable_fusion=lowerCamelCase   )

				clap_model.eval()
				__magic_name__	:	int								=clap_model.state_dict()
				__magic_name__	:	Optional[Any]								=rename_state_dict(lowerCamelCase   )

				__magic_name__	:	Any								=ClapConfig()
				__magic_name__	:	Optional[Any]								=enable_fusion
				__magic_name__	:	Tuple								=ClapModel(lowerCamelCase   )

				# ignore the spectrogram embedding layer
				model.load_state_dict(lowerCamelCase	,     strict=lowerCamelCase   )

				model.save_pretrained(lowerCamelCase   )
				transformers_config.save_pretrained(lowerCamelCase   )


if __name__ == "__main__":
							UpperCAmelCase_		:				Optional[int]									=     argparse.ArgumentParser()
							parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
							parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
							parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
							parser.add_argument("--enable_fusion", action="store_true", help="Whether to enable fusion or not")
							UpperCAmelCase_		:				Dict									=     parser.parse_args()

							convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)




