





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__(__snake_case ,__snake_case ,__snake_case = 16000							)       ->   Optional[int]:







	'''simple docstring'''







	lowerCamelCase__              =	int(round(sample_rate * max_length							)							)
	if len(__snake_case							) <= sample_length:
		return wav
	lowerCamelCase__              =	randint(0 ,len(__snake_case							) - sample_length - 1							)
	return wav[random_offset : random_offset + sample_length]






@dataclass
class       __A					:

			'''simple docstring'''







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






@dataclass
class       __A					:

			'''simple docstring'''







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





			def 	__lowerCamelCase       (					self							):



				'''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 lowerCAmelCase__()       ->   str:







	'''simple docstring'''







	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''' ,__snake_case ,__snake_case							)

	# 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(__snake_case							)
	transformers.utils.logging.set_verbosity(__snake_case							)
	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(__snake_case							):
		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(__snake_case							)
		lowerCamelCase__              =	feature_extractor(__snake_case ,sampling_rate=feature_extractor.sampling_rate							)
		lowerCamelCase__              =	{model_input_name: inputs.get(__snake_case							)}
		lowerCamelCase__              =	list(batch[data_args.label_column_name]							)

		return output_batch

	def val_transforms(__snake_case							):
		lowerCamelCase__              =	[audio['''array'''] for audio in batch[data_args.audio_column_name]]
		lowerCamelCase__              =	feature_extractor(__snake_case ,sampling_rate=feature_extractor.sampling_rate							)
		lowerCamelCase__              =	{model_input_name: inputs.get(__snake_case							)}
		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(__snake_case							):
		lowerCamelCase__              =	str(__snake_case							)
		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(__snake_case							):
		lowerCamelCase__              =	np.argmax(eval_pred.predictions ,axis=1							)
		return metric.compute(predictions=__snake_case ,references=eval_pred.label_ids							)

	lowerCamelCase__              =	AutoConfig.from_pretrained(
	    model_args.config_name or model_args.model_name_or_path ,num_labels=len(__snake_case							) ,labelaid=__snake_case ,idalabel=__snake_case ,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=__snake_case ,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(__snake_case ,output_all_columns=__snake_case							)

	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(__snake_case ,output_all_columns=__snake_case							)

	# Initialize our trainer
	lowerCamelCase__              =	Trainer(
	    model=__snake_case ,args=__snake_case ,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=__snake_case ,tokenizer=__snake_case ,)

	# 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=__snake_case							)
		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''' ,__snake_case							)
		trainer.save_metrics('''eval''' ,__snake_case							)

	# 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(**__snake_case							)
	else:
		trainer.create_model_card(**__snake_case							)


if __name__ == "__main__":
			main()








# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   Any:







	'''simple docstring'''







	lowerCamelCase__              =	{
	    '''en''': '''Machine learning is great, isn\'t it?''',
	    '''ru''': '''Машинное обучение - это здорово, не так ли?''',
	    '''de''': '''Maschinelles Lernen ist großartig, nicht wahr?''',
	}

	# BLUE scores as follows:
	# "pair": [fairseq, transformers]
	lowerCamelCase__              =	{
	    '''wmt16-en-de-dist-12-1''': [2_8.3, 2_7.5_2],
	    '''wmt16-en-de-dist-6-1''': [2_7.4, 2_7.1_1],
	    '''wmt16-en-de-12-1''': [2_6.9, 2_5.7_5],
	}
	lowerCamelCase__              =	F'{src_lang}-{tgt_lang}'

	lowerCamelCase__              =	F'\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "allenai/{model_name}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel   | fairseq | transformers\n-------|---------|----------\n{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n    year={{2020}},\n    eprint={{2006.10369}},\n    archivePrefix={{arXiv}},\n    primaryClass={{cs.CL}}\n}}\n```\n\n'
	model_card_dir.mkdir(parents=__snake_case ,exist_ok=__snake_case							)
	lowerCamelCase__              =	os.path.join(__snake_case ,'''README.md'''							)
	print(F'Generating {path}'							)
	with open(__snake_case ,'''w''' ,encoding='''utf-8'''							) as f:
		f.write(__snake_case							)


# make sure we are under the root of the project
_a						=   Path(__file__).resolve().parent.parent.parent
_a						=   repo_dir / "model_cards"

for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
			_a						=   model_cards_dir / "allenai" / model_name
			write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)



