



"""simple docstring"""
import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
					import torch

if is_datasets_available():
					from datasets import load_dataset

SCREAMING_SNAKE_CASE_				= random.Random()



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__=1.0, SCREAMING_SNAKE_CASE__=None, SCREAMING_SNAKE_CASE__=None	)			->      Tuple:
		if rng is None:
				a_     :      Any 						=     global_rng

		a_     :      Dict 						=     []
		for batch_idx in range(shape[0]	):
				values.append([]	)
				for _ in range(shape[1]	):
						values[-1].append(rng.random() * scale	)

		return values




class 			snake_case_						(						unittest.TestCase				):






							def __init__(   self			,     a_			,     a_=7			,     a_=4_0_0			,     a_=2_0_0_0			,     a_=2_0_4_8			,     a_=1_2_8			,     a_=1			,     a_=5_1_2			,     a_=3_0			,     a_=4_4_1_0_0			,     ):
									a_     :      Optional[Any] 						=     parent
									a_     :      Tuple 						=     batch_size
									a_     :      Union[str, Any] 						=     min_seq_length
									a_     :      Dict 						=     max_seq_length
									a_     :      Union[str, Any] 						=     (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									a_     :      int 						=     spectrogram_length
									a_     :      Optional[Any] 						=     feature_size
									a_     :      Optional[int] 						=     num_audio_channels
									a_     :      List[str] 						=     hop_length
									a_     :      Optional[int] 						=     chunk_length
									a_     :      List[str] 						=     sampling_rate






							def snake_case_  (   self      ):
									return {
									    "spectrogram_length": self.spectrogram_length,
									    "feature_size": self.feature_size,
									    "num_audio_channels": self.num_audio_channels,
									    "hop_length": self.hop_length,
									    "chunk_length": self.chunk_length,
									    "sampling_rate": self.sampling_rate,
									}






							def snake_case_  (   self			,     a_=False			,     a_=False      ):
									def _flatten(a_      ):
											return list(itertools.chain(*a_      )      )

									if equal_length:
											a_     :      Tuple 						=     [floats_list((self.max_seq_length, self.feature_size)      ) for _ in range(self.batch_size      )]
									else:
											# make sure that inputs increase in size
											a_     :      Optional[Any] 						=     [
											    floats_list((x, self.feature_size)      )
											    for x in range(self.min_seq_length			,     self.max_seq_length			,     self.seq_length_diff      )
											]
									if numpify:
											a_     :      Tuple 						=     [np.asarray(a_      ) for x in speech_inputs]
									return speech_inputs




@require_torch
@require_torchaudio
class 			snake_case_						(						a_     ,unittest.TestCase				):
							__lowerCAmelCase    					=					TvltFeatureExtractor






							def snake_case_  (   self      ):
									a_     :      Dict 						=     TvltFeatureExtractionTester(self      )






							def snake_case_  (   self      ):
									a_     :      Optional[Any] 						=     self.feature_extraction_class(**self.feat_extract_dict      )
									self.assertTrue(hasattr(a_			,     "spectrogram_length"      )      )
									self.assertTrue(hasattr(a_			,     "feature_size"      )      )
									self.assertTrue(hasattr(a_			,     "num_audio_channels"      )      )
									self.assertTrue(hasattr(a_			,     "hop_length"      )      )
									self.assertTrue(hasattr(a_			,     "chunk_length"      )      )
									self.assertTrue(hasattr(a_			,     "sampling_rate"      )      )






							def snake_case_  (   self      ):
									a_     :      List[Any] 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									with tempfile.TemporaryDirectory() as tmpdirname:
											a_     :      List[Any] 						=     feat_extract_first.save_pretrained(a_      )[0]
											check_json_file_has_correct_format(a_      )
											a_     :      Tuple 						=     self.feature_extraction_class.from_pretrained(a_      )

									a_     :      Dict 						=     feat_extract_first.to_dict()
									a_     :      List[str] 						=     feat_extract_second.to_dict()
									a_     :      List[Any] 						=     dict_first.pop("mel_filters"      )
									a_     :      str 						=     dict_second.pop("mel_filters"      )
									self.assertTrue(np.allclose(a_			,     a_      )      )
									self.assertEqual(a_			,     a_      )






							def snake_case_  (   self      ):
									a_     :      List[str] 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									with tempfile.TemporaryDirectory() as tmpdirname:
											a_     :      Dict 						=     os.path.join(a_			,     "feat_extract.json"      )
											feat_extract_first.to_json_file(a_      )
											a_     :      str 						=     self.feature_extraction_class.from_json_file(a_      )

									a_     :      Dict 						=     feat_extract_first.to_dict()
									a_     :      str 						=     feat_extract_second.to_dict()
									a_     :      int 						=     dict_first.pop("mel_filters"      )
									a_     :      List[Any] 						=     dict_second.pop("mel_filters"      )
									self.assertTrue(np.allclose(a_			,     a_      )      )
									self.assertEqual(a_			,     a_      )






							def snake_case_  (   self      ):
									# Initialize feature_extractor
									a_     :      str 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									# create three inputs of length 800, 1000, and 1200
									a_     :      Optional[Any] 						=     [floats_list((1, x)      )[0] for x in range(8_0_0			,     1_4_0_0			,     2_0_0      )]
									a_     :      Union[str, Any] 						=     [np.asarray(a_      ) for speech_input in speech_inputs]

									# Test not batched input
									a_     :      Dict 						=     feature_extractor(np_speech_inputs[0]			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test batched
									a_     :      int 						=     feature_extractor(a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test audio masking
									a_     :      Optional[int] 						=     feature_extractor(
									    a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0			,     mask_audio=a_      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test 2-D numpy arrays are batched.
									a_     :      List[str] 						=     [floats_list((1, x)      )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									a_     :      Union[str, Any] 						=     np.asarray(a_      )
									a_     :      Dict 						=     feature_extractor(a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values
									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )






							def snake_case_  (   self			,     a_      ):
									a_     :      Optional[int] 						=     load_dataset("hf-internal-testing/librispeech_asr_dummy"			,     "clean"			,     split="validation"      )
									# automatic decoding with librispeech
									a_     :      List[str] 						=     ds.sort("id"      ).select(range(a_      )      )[:num_samples]["audio"]

									return [x["array"] for x in speech_samples]






							def snake_case_  (   self      ):
									a_     :      List[str] 						=     self._load_datasamples(1      )
									a_     :      Any 						=     TvltFeatureExtractor()
									a_     :      Union[str, Any] 						=     feature_extractor(a_			,     return_tensors="pt"      ).audio_values

									self.assertEquals(audio_values.shape			,     (1, 1, 1_9_2, 1_2_8)      )

									a_     :      Dict 						=     torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]]      )
									self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]			,     a_			,     atol=1e-4      )      )




"""simple docstring"""
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


SCREAMING_SNAKE_CASE_				= """Create a default config file for Accelerate with only a few flags set."""



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__="no", SCREAMING_SNAKE_CASE__ = default_json_config_file, SCREAMING_SNAKE_CASE__ = False	)			->      Tuple:
		a_     :      Union[str, Any] 						=     Path(SCREAMING_SNAKE_CASE__	)
		path.parent.mkdir(parents=SCREAMING_SNAKE_CASE__, exist_ok=SCREAMING_SNAKE_CASE__	)
		if path.exists():
				print(
				    F"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""	)
				return False
		a_     :      Optional[int] 						=     mixed_precision.lower()
		if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
				raise ValueError(
				    F"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""	)
		a_     :      str 						=     {
		    "compute_environment": "LOCAL_MACHINE",
		    "mixed_precision": mixed_precision,
		}
		if torch.cuda.is_available():
				a_     :      int 						=     torch.cuda.device_count()
				a_     :      Optional[Any] 						=     num_gpus
				a_     :      int 						=     False
				if num_gpus > 1:
						a_     :      Any 						=     "MULTI_GPU"
				else:
						a_     :      int 						=     "NO"
		elif is_xpu_available() and use_xpu:
				a_     :      int 						=     torch.xpu.device_count()
				a_     :      str 						=     num_xpus
				a_     :      Tuple 						=     False
				if num_xpus > 1:
						a_     :      int 						=     "MULTI_XPU"
				else:
						a_     :      List[str] 						=     "NO"
		elif is_npu_available():
				a_     :      List[Any] 						=     torch.npu.device_count()
				a_     :      int 						=     num_npus
				a_     :      List[Any] 						=     False
				if num_npus > 1:
						a_     :      str 						=     "MULTI_NPU"
				else:
						a_     :      Union[str, Any] 						=     "NO"
		else:
				a_     :      Optional[Any] 						=     0
				a_     :      Optional[Any] 						=     True
				a_     :      Tuple 						=     1
				a_     :      Optional[int] 						=     "NO"
		a_     :      str 						=     ClusterConfig(**SCREAMING_SNAKE_CASE__	)
		config.to_json_file(SCREAMING_SNAKE_CASE__	)
		return path



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__	)			->      Optional[Any]:
		a_     :      Dict 						=     parser.add_parser("default", parents=SCREAMING_SNAKE_CASE__, help=SCREAMING_SNAKE_CASE__, formatter_class=SCREAMING_SNAKE_CASE__	)
		parser.add_argument(
		    "--config_file", default=SCREAMING_SNAKE_CASE__, help=(
		        "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
		        "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
		        "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
		        "with 'huggingface'."
		    ), dest="save_location", )

		parser.add_argument(
		    "--mixed_precision", choices=["no", "fp16", "bf16"], type=SCREAMING_SNAKE_CASE__, help="Whether or not to use mixed precision training. "
		    "Choose between FP16 and BF16 (bfloat16) training. "
		    "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", default="no", )
		parser.set_defaults(func=SCREAMING_SNAKE_CASE__	)
		return parser



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__	)			->      Tuple:
		a_     :      Any 						=     write_basic_config(args.mixed_precision, args.save_location	)
		if config_file:
				print(F"""accelerate configuration saved at {config_file}"""	)