


'''simple docstring'''



import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


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

__A		=logging.getLogger(__name__)


@dataclass
class 						_snake_case   :
					lowerCAmelCase :str						=   field(
					    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''': '''Pretrained tokenizer 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 huggingface.co'''}    ,				)
					lowerCAmelCase :bool						=   field(
					    default=_UpperCamelCase    ,				metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}    ,				)
					lowerCAmelCase :str						=   field(
					    default='''main'''    ,				metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}    ,				)
					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).'''
					        )
					    }    ,				)


@dataclass
class 						_snake_case   :
					lowerCAmelCase :Optional[str]						=   field(default=_UpperCamelCase    ,				metadata={'''help''': '''The input training data file (a text file).'''}		)
					lowerCAmelCase :Optional[str]						=   field(
					    default=_UpperCamelCase    ,				metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}    ,				)
					lowerCAmelCase :bool						=   field(
					    default=_UpperCamelCase    ,				metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}		)
					lowerCAmelCase :Optional[int]						=   field(
					    default=_UpperCamelCase    ,				metadata={'''help''': '''The number of processes to use for the preprocessing.'''}    ,				)
					lowerCAmelCase :Optional[int]						=   field(
					    default=_UpperCamelCase    ,				metadata={
					        '''help''': (
					            '''The maximum total input sequence length after tokenization. If passed, sequences longer '''
					            '''than this will be truncated, sequences shorter will be padded.'''
					        )
					    }    ,				)
					lowerCAmelCase :bool						=   field(
					    default=_UpperCamelCase    ,				metadata={
					        '''help''': (
					            '''Whether to pad all samples to the maximum sentence length. '''
					            '''If False, will pad the samples dynamically when batching to the maximum length in the batch. More '''
					            '''efficient on GPU but very bad for TPU.'''
					        )
					    }    ,				)
					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.'''
					        )
					    }    ,				)




					def 			snake_case__  ( self):
								if self.train_file is not None:
											UpperCAmelCase__					:   List[str]       				=       self.train_file.split(""".""")[-1]
											assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
								if self.validation_file is not None:
											UpperCAmelCase__					:   Union[str, Any]       				=       self.validation_file.split(""".""")[-1]
											assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."


@dataclass
class 						_snake_case   :
					lowerCAmelCase :PreTrainedTokenizerBase
					lowerCAmelCase :Union[bool, str, PaddingStrategy]						=   True
					lowerCAmelCase :Optional[int]						=   None
					lowerCAmelCase :Optional[int]						=   None




					def __call__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   int       				=       'label' if 'label' in features[0].keys() else 'labels'
								UpperCAmelCase__					:   int       				=       [feature.pop(_UpperCAmelCase) for feature in features]
								UpperCAmelCase__					:   int       				=       len(_UpperCAmelCase)
								UpperCAmelCase__					:   List[str]       				=       len(features[0]["""input_ids"""])
								UpperCAmelCase__					:   Tuple       				=       [
								    [{k: v[i] for k, v in feature.items()} for i in range(_UpperCAmelCase)] for feature in features
								]
								UpperCAmelCase__					:   List[str]       				=       list(chain(*_UpperCAmelCase))

								UpperCAmelCase__					:   Optional[Any]       				=       self.tokenizer.pad(
								    _UpperCAmelCase							,							padding=self.padding							,							max_length=self.max_length							,							pad_to_multiple_of=self.pad_to_multiple_of							,							return_tensors="""pt"""							,							)

								# Un-flatten
								UpperCAmelCase__					:   List[Any]       				=       {k: v.view(_UpperCAmelCase							,							_UpperCAmelCase							,							-1) for k, v in batch.items()}
								# Add back labels
								UpperCAmelCase__					:   List[str]       				=       torch.tensor(_UpperCAmelCase							,							dtype=torch.intaa)
								return batch







def       _UpperCamelCase (						):
			# 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.

			UpperCAmelCase__					:   List[str]       				=       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.
						UpperCAmelCase__					:   Union[str, Any]       				=       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
			else:
						UpperCAmelCase__					:   Dict       				=       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_swag"""	, 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()

			UpperCAmelCase__					:   Tuple       				=       training_args.get_process_log_level()
			logger.setLevel(lowerCAmelCase_   )
			datasets.utils.logging.set_verbosity(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}'''   )

			# Detecting last checkpoint.
			UpperCAmelCase__					:   List[Any]       				=       None
			if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
						UpperCAmelCase__					:   int       				=       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 overcome."""   )
						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."""   )

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

			# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
			# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
			# (the dataset will be downloaded automatically from the datasets Hub).

			# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
			# 'text' is found. You can easily tweak this behavior (see below).

			# In distributed training, the load_dataset function guarantee that only one local process can concurrently
			# download the dataset.
			if data_args.train_file is not None or data_args.validation_file is not None:
						UpperCAmelCase__					:   List[str]       				=       {}
						if data_args.train_file is not None:
									UpperCAmelCase__					:   Optional[Any]       				=       data_args.train_file
						if data_args.validation_file is not None:
									UpperCAmelCase__					:   Dict       				=       data_args.validation_file
						UpperCAmelCase__					:   Dict       				=       data_args.train_file.split("""."""   )[-1]
						UpperCAmelCase__					:   Any       				=       load_dataset(
						    lowerCAmelCase_	, data_files=lowerCAmelCase_	, cache_dir=model_args.cache_dir	, use_auth_token=True if model_args.use_auth_token else None	, )
			else:
						# Downloading and loading the swag dataset from the hub.
						UpperCAmelCase__					:   Optional[int]       				=       load_dataset(
						    """swag"""	, """regular"""	, cache_dir=model_args.cache_dir	, use_auth_token=True if model_args.use_auth_token else None	, )
			# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
			# https://huggingface.co/docs/datasets/loading_datasets.html.

			# Load pretrained model and tokenizer

			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.
			UpperCAmelCase__					:   Tuple       				=       AutoConfig.from_pretrained(
			    model_args.config_name if model_args.config_name else model_args.model_name_or_path	, cache_dir=model_args.cache_dir	, revision=model_args.model_revision	, use_auth_token=True if model_args.use_auth_token else None	, )
			UpperCAmelCase__					:   Any       				=       AutoTokenizer.from_pretrained(
			    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path	, cache_dir=model_args.cache_dir	, use_fast=model_args.use_fast_tokenizer	, revision=model_args.model_revision	, use_auth_token=True if model_args.use_auth_token else None	, )
			UpperCAmelCase__					:   int       				=       AutoModelForMultipleChoice.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	, )

			# When using your own dataset or a different dataset from swag, you will probably need to change this.
			UpperCAmelCase__					:   Optional[Any]       				=       [f'''ending{i}''' for i in range(4   )]
			UpperCAmelCase__					:   Optional[Any]       				=       'sent1'
			UpperCAmelCase__					:   List[str]       				=       'sent2'

			if data_args.max_seq_length is None:
						UpperCAmelCase__					:   str       				=       tokenizer.model_max_length
						if max_seq_length > 1_0_2_4:
									logger.warning(
									    """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"""
									    """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"""
									    """ override this default with `--block_size xxx`."""   )
									UpperCAmelCase__					:   Optional[Any]       				=       1_0_2_4
			else:
						if data_args.max_seq_length > tokenizer.model_max_length:
									logger.warning(
									    f'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the'''
									    f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'''   )
						UpperCAmelCase__					:   Union[str, Any]       				=       min(data_args.max_seq_length	, tokenizer.model_max_length   )

			# Preprocessing the datasets.
			def preprocess_function(UpperCamelCase__   ):
						UpperCAmelCase__					:   List[str]       				=       [[context] * 4 for context in examples[context_name]]
						UpperCAmelCase__					:   List[str]       				=       examples[question_header_name]
						UpperCAmelCase__					:   List[str]       				=       [
						    [f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(lowerCAmelCase_   )
						]

						# Flatten out
						UpperCAmelCase__					:   List[Any]       				=       list(chain(*lowerCAmelCase_   )   )
						UpperCAmelCase__					:   Tuple       				=       list(chain(*lowerCAmelCase_   )   )

						# Tokenize
						UpperCAmelCase__					:   Union[str, Any]       				=       tokenizer(
						    lowerCAmelCase_	, lowerCAmelCase_	, truncation=lowerCAmelCase_	, max_length=lowerCAmelCase_	, padding="""max_length""" if data_args.pad_to_max_length else False	, )
						# Un-flatten
						return {k: [v[i : i + 4] for i in range(0	, len(lowerCAmelCase_   )	, 4   )] for k, v in tokenized_examples.items()}

			if training_args.do_train:
						if "train" not in raw_datasets:
									raise ValueError("""--do_train requires a train dataset"""   )
						UpperCAmelCase__					:   List[Any]       				=       raw_datasets['train']
						if data_args.max_train_samples is not None:
									UpperCAmelCase__					:   Dict       				=       min(len(lowerCAmelCase_   )	, data_args.max_train_samples   )
									UpperCAmelCase__					:   Tuple       				=       train_dataset.select(range(lowerCAmelCase_   )   )
						with training_args.main_process_first(desc="""train dataset map pre-processing"""   ):
									UpperCAmelCase__					:   int       				=       train_dataset.map(
									    lowerCAmelCase_	, batched=lowerCAmelCase_	, num_proc=data_args.preprocessing_num_workers	, load_from_cache_file=not data_args.overwrite_cache	, )

			if training_args.do_eval:
						if "validation" not in raw_datasets:
									raise ValueError("""--do_eval requires a validation dataset"""   )
						UpperCAmelCase__					:   Optional[Any]       				=       raw_datasets['validation']
						if data_args.max_eval_samples is not None:
									UpperCAmelCase__					:   str       				=       min(len(lowerCAmelCase_   )	, data_args.max_eval_samples   )
									UpperCAmelCase__					:   Optional[int]       				=       eval_dataset.select(range(lowerCAmelCase_   )   )
						with training_args.main_process_first(desc="""validation dataset map pre-processing"""   ):
									UpperCAmelCase__					:   str       				=       eval_dataset.map(
									    lowerCAmelCase_	, batched=lowerCAmelCase_	, num_proc=data_args.preprocessing_num_workers	, load_from_cache_file=not data_args.overwrite_cache	, )

    # Data collator
			UpperCAmelCase__					:   Optional[Any]       				=       (
			    default_data_collator
			    if data_args.pad_to_max_length
			    else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_	, pad_to_multiple_of=8 if training_args.fpaa else None   )
			)

			# Metric
			def compute_metrics(UpperCamelCase__   ):
						UpperCAmelCase__					:   Optional[Any]       				=       eval_predictions
						UpperCAmelCase__					:   Dict       				=       np.argmax(lowerCAmelCase_	, axis=1   )
						return {"accuracy": (preds == label_ids).astype(np.floataa   ).mean().item()}

			# Initialize our Trainer
			UpperCAmelCase__					:   List[str]       				=       Trainer(
			    model=lowerCAmelCase_	, args=lowerCAmelCase_	, train_dataset=train_dataset if training_args.do_train else None	, eval_dataset=eval_dataset if training_args.do_eval else None	, tokenizer=lowerCAmelCase_	, data_collator=lowerCAmelCase_	, compute_metrics=lowerCAmelCase_	, )

			# Training
			if training_args.do_train:
						UpperCAmelCase__					:   List[str]       				=       None
						if training_args.resume_from_checkpoint is not None:
									UpperCAmelCase__					:   Optional[Any]       				=       training_args.resume_from_checkpoint
						elif last_checkpoint is not None:
									UpperCAmelCase__					:   int       				=       last_checkpoint
						UpperCAmelCase__					:   Union[str, Any]       				=       trainer.train(resume_from_checkpoint=lowerCAmelCase_   )
						trainer.save_model()  # Saves the tokenizer too for easy upload
						UpperCAmelCase__					:   Optional[Any]       				=       train_result.metrics

						UpperCAmelCase__					:   Union[str, Any]       				=       (
						    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_   )
						)
						UpperCAmelCase__					:   List[Any]       				=       min(lowerCAmelCase_	, len(lowerCAmelCase_   )   )

						trainer.log_metrics("""train"""	, lowerCAmelCase_   )
						trainer.save_metrics("""train"""	, lowerCAmelCase_   )
						trainer.save_state()

			# Evaluation
			if training_args.do_eval:
						logger.info("""*** Evaluate ***"""   )

						UpperCAmelCase__					:   Dict       				=       trainer.evaluate()
						UpperCAmelCase__					:   Any       				=       data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_   )
						UpperCAmelCase__					:   Union[str, Any]       				=       min(lowerCAmelCase_	, len(lowerCAmelCase_   )   )

						trainer.log_metrics("""eval"""	, lowerCAmelCase_   )
						trainer.save_metrics("""eval"""	, lowerCAmelCase_   )

			UpperCAmelCase__					:   List[Any]       				=       {
			    'finetuned_from': model_args.model_name_or_path,
			    'tasks': 'multiple-choice',
			    'dataset_tags': 'swag',
			    'dataset_args': 'regular',
			    'dataset': 'SWAG',
			    'language': 'en',
			}

			if training_args.push_to_hub:
						trainer.push_to_hub(**lowerCAmelCase_   )
			else:
						trainer.create_model_card(**lowerCAmelCase_   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			# For xla_spawn (TPUs)
			main()


if __name__ == "__main__":
		main()



'''simple docstring'''



import os
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen, xsplitext
from ..table import array_cast
from ..utils.py_utils import no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
		from .features import FeatureType


__A		,	__A		,	__A		=False, False, False


@dataclass
class 						_snake_case   :
					lowerCAmelCase :Optional[int]						=   None
					lowerCAmelCase :bool						=   True
					lowerCAmelCase :bool						=   True
					lowerCAmelCase :Optional[str]						=   None
					# Automatically constructed
					lowerCAmelCase :ClassVar[str]						=   "dict"
					lowerCAmelCase :ClassVar[Any]						=   pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()}		)
					lowerCAmelCase :str						=   field(default='''Audio'''    ,				init=a__    ,				repr=a__		)




					def __call__( self):
								return self.pa_type




					def 			snake_case__  ( self							,							_lowerCamelCase):
								try:
											import soundfile as sf  # soundfile is a dependency of librosa, needed to decode audio files.
								except ImportError as err:
											raise ImportError("""To support encoding audio data, please install 'soundfile'.""") from err
								if isinstance(_lowerCamelCase							,							_lowerCamelCase):
											return {"bytes": None, "path": value}
								elif isinstance(_lowerCamelCase							,							_lowerCamelCase):
											return {"bytes": value, "path": None}
								elif "array" in value:
											# convert the audio array to wav bytes
											UpperCAmelCase__					:   Optional[int]       				=       BytesIO()
											sf.write(_lowerCamelCase							,							value["""array"""]							,							value["""sampling_rate"""]							,							format="""wav""")
											return {"bytes": buffer.getvalue(), "path": None}
								elif value.get("""path""") is not None and os.path.isfile(value["""path"""]):
											# we set "bytes": None to not duplicate the data if they're already available locally
											if value["path"].endswith("""pcm"""):
														# "PCM" only has raw audio bytes
														if value.get("""sampling_rate""") is None:
																	# At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate
																	raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""")
														if value.get("""bytes"""):
																	# If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!)
																	UpperCAmelCase__					:   Tuple       				=       np.frombuffer(value["""bytes"""]							,							dtype=np.intaa).astype(np.floataa) / 3_2767
														else:
																	UpperCAmelCase__					:   List[str]       				=       np.memmap(value["""path"""]							,							dtype="""h"""							,							mode="""r""").astype(np.floataa) / 3_2767

														UpperCAmelCase__					:   List[str]       				=       BytesIO(bytes())
														sf.write(_lowerCamelCase							,							_lowerCamelCase							,							value["""sampling_rate"""]							,							format="""wav""")
														return {"bytes": buffer.getvalue(), "path": None}
											else:
														return {"bytes": None, "path": value.get("""path""")}
								elif value.get("""bytes""") is not None or value.get("""path""") is not None:
											# store the audio bytes, and path is used to infer the audio format using the file extension
											return {"bytes": value.get("""bytes"""), "path": value.get("""path""")}
								else:
											raise ValueError(
											    f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''')




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if not self.decode:
											raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""")

								UpperCAmelCase__				,    UpperCAmelCase__					:   Tuple       				=       (value["""path"""], BytesIO(value["""bytes"""])) if value["""bytes"""] is not None else (value["""path"""], None)
								if path is None and file is None:
											raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''')

								try:
											import librosa
											import soundfile as sf
								except ImportError as err:
											raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""") from err

								UpperCAmelCase__					:   Dict       				=       xsplitext(_lowerCamelCase)[1][1:].lower() if path is not None else None
								if not config.IS_OPUS_SUPPORTED and audio_format == "opus":
											raise RuntimeError(
											    """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """
											    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """)
								elif not config.IS_MP3_SUPPORTED and audio_format == "mp3":
											raise RuntimeError(
											    """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """
											    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """)

								if file is None:
											UpperCAmelCase__					:   int       				=       token_per_repo_id or {}
											UpperCAmelCase__					:   Optional[int]       				=       path.split("""::""")[-1]
											try:
														UpperCAmelCase__					:   Dict       				=       string_to_dict(_lowerCamelCase							,							config.HUB_DATASETS_URL)["""repo_id"""]
														UpperCAmelCase__					:   Dict       				=       token_per_repo_id[repo_id]
											except (ValueError, KeyError):
														UpperCAmelCase__					:   List[Any]       				=       None

											with xopen(_lowerCamelCase							,							"""rb"""							,							use_auth_token=_lowerCamelCase) as f:
														UpperCAmelCase__				,    UpperCAmelCase__					:   List[str]       				=       sf.read(_lowerCamelCase)

								else:
											UpperCAmelCase__				,    UpperCAmelCase__					:   List[Any]       				=       sf.read(_lowerCamelCase)

								UpperCAmelCase__					:   str       				=       array.T
								if self.mono:
											UpperCAmelCase__					:   List[Any]       				=       librosa.to_mono(_lowerCamelCase)
								if self.sampling_rate and self.sampling_rate != sampling_rate:
											UpperCAmelCase__					:   int       				=       librosa.resample(_lowerCamelCase							,							orig_sr=_lowerCamelCase							,							target_sr=self.sampling_rate)
											UpperCAmelCase__					:   Tuple       				=       self.sampling_rate

								return {"path": path, "array": array, "sampling_rate": sampling_rate}




					def 			snake_case__  ( self):
								from .features import Value

								if self.decode:
											raise ValueError("""Cannot flatten a decoded Audio feature.""")
								return {
								    "bytes": Value("""binary"""),
								    "path": Value("""string"""),
								}




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if pa.types.is_string(storage.type):
											UpperCAmelCase__					:   Dict       				=       pa.array([None] * len(_lowerCamelCase)							,							type=pa.binary())
											UpperCAmelCase__					:   Tuple       				=       pa.StructArray.from_arrays([bytes_array, storage]							,							["""bytes""", """path"""]							,							mask=storage.is_null())
								elif pa.types.is_binary(storage.type):
											UpperCAmelCase__					:   Optional[int]       				=       pa.array([None] * len(_lowerCamelCase)							,							type=pa.string())
											UpperCAmelCase__					:   str       				=       pa.StructArray.from_arrays([storage, path_array]							,							["""bytes""", """path"""]							,							mask=storage.is_null())
								elif pa.types.is_struct(storage.type) and storage.type.get_all_field_indices("""array"""):
											UpperCAmelCase__					:   Optional[Any]       				=       pa.array([Audio().encode_example(_lowerCamelCase) if x is not None else None for x in storage.to_pylist()])
								elif pa.types.is_struct(storage.type):
											if storage.type.get_field_index("""bytes""") >= 0:
														UpperCAmelCase__					:   int       				=       storage.field("""bytes""")
											else:
														UpperCAmelCase__					:   List[str]       				=       pa.array([None] * len(_lowerCamelCase)							,							type=pa.binary())
											if storage.type.get_field_index("""path""") >= 0:
														UpperCAmelCase__					:   List[Any]       				=       storage.field("""path""")
											else:
														UpperCAmelCase__					:   Optional[int]       				=       pa.array([None] * len(_lowerCamelCase)							,							type=pa.string())
											UpperCAmelCase__					:   Optional[int]       				=       pa.StructArray.from_arrays([bytes_array, path_array]							,							["""bytes""", """path"""]							,							mask=storage.is_null())
								return array_cast(_lowerCamelCase							,							self.pa_type)




					def 			snake_case__  ( self							,							_lowerCamelCase):

								@no_op_if_value_is_null
								def path_to_bytes(_lowerCamelCase):
											with xopen(_lowerCamelCase							,							"""rb""") as f:
														UpperCAmelCase__					:   int       				=       f.read()
											return bytes_

								UpperCAmelCase__					:   Optional[Any]       				=       pa.array(
								    [
								        (path_to_bytes(x["""path"""]) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None
								        for x in storage.to_pylist()
								    ]							,							type=pa.binary()							,							)
								UpperCAmelCase__					:   Optional[Any]       				=       pa.array(
								    [os.path.basename(_lowerCamelCase) if path is not None else None for path in storage.field("""path""").to_pylist()]							,							type=pa.string()							,							)
								UpperCAmelCase__					:   List[str]       				=       pa.StructArray.from_arrays([bytes_array, path_array]							,							["""bytes""", """path"""]							,							mask=bytes_array.is_null())
								return array_cast(_lowerCamelCase							,							self.pa_type)