

from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


UpperCamelCase__		 =     logging.get_logger(__name__)

class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , **_UpperCamelCase   )      ->							Optional[Any]:






              """simple docstring"""


              __snake_case       	=							feature_size
              __snake_case       	=							sampling_rate
              __snake_case       	=							padding_value

              __snake_case       	=							kwargs.pop("""padding_side"""      , """right"""   )
              __snake_case       	=							kwargs.pop("""return_attention_mask"""      , _UpperCamelCase   )

              super().__init__(**_UpperCamelCase   )


       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase = True      , _UpperCamelCase = None      , _UpperCamelCase = False      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , )      ->							BatchFeature:






              """simple docstring"""


              if isinstance(_UpperCamelCase      , (list, tuple)   ) and isinstance(processed_features[0]      , (dict, BatchFeature)   ):
                     __snake_case       	=							{
                         key: [example[key] for example in processed_features] for key in processed_features[0].keys()
                     }

              # The model's main input name, usually `input_values`, has be passed for padding
              if self.model_input_names[0] not in processed_features:
                     raise ValueError(
                         """You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"""
                         F' to this method that includes {self.model_input_names[0]}, but you provided'
                         F' {list(processed_features.keys()   )}'   )

              __snake_case       	=							processed_features[self.model_input_names[0]]
              __snake_case       	=							(
                  return_attention_mask if return_attention_mask is not None else self.return_attention_mask
              )

              if len(_UpperCamelCase   ) == 0:
                     if return_attention_mask:
                            __snake_case       	=							[]
                     return processed_features

              # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
              # and rebuild them afterwards if no return_tensors is specified
              # Note that we lose the specific device the tensor may be on for PyTorch

              __snake_case       	=							required_input[0]
              if isinstance(_UpperCamelCase      , (list, tuple)   ):
                     # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
                     __snake_case       	=							0
                     while len(required_input[index]   ) == 0:
                            index += 1
                     if index < len(_UpperCamelCase   ):
                            __snake_case       	=							required_input[index][0]

              if return_tensors is None:
                     if is_tf_tensor(_UpperCamelCase   ):
                            __snake_case       	=							"""tf"""
                     elif is_torch_tensor(_UpperCamelCase   ):
                            __snake_case       	=							"""pt"""
                     elif isinstance(_UpperCamelCase      , (int, float, list, tuple, np.ndarray)   ):
                            __snake_case       	=							"""np"""
                     else:
                            raise ValueError(
                                F'type of {first_element} unknown: {type(_UpperCamelCase   )}. '
                                """Should be one of a python, numpy, pytorch or tensorflow object."""   )

              for key, value in processed_features.items():
                     if isinstance(value[0]      , (int, float)   ):
                            __snake_case       	=							to_numpy(_UpperCamelCase   )
                     else:
                            __snake_case       	=							[to_numpy(_UpperCamelCase   ) for v in value]

        # Convert padding_strategy in PaddingStrategy
              __snake_case       	=							self._get_padding_strategies(padding=_UpperCamelCase      , max_length=_UpperCamelCase   )

              __snake_case       	=							processed_features[self.model_input_names[0]]

              __snake_case       	=							len(_UpperCamelCase   )
              if not all(len(_UpperCamelCase   ) == batch_size for v in processed_features.values()   ):
                     raise ValueError("""Some items in the output dictionary have a different batch size than others."""   )

              __snake_case       	=							[]
              for i in range(_UpperCamelCase   ):
                     __snake_case       	=							{k: v[i] for k, v in processed_features.items()}
                     # truncation
                     __snake_case       	=							self._truncate(
                         _UpperCamelCase      , max_length=_UpperCamelCase      , pad_to_multiple_of=_UpperCamelCase      , truncation=_UpperCamelCase      , )
                     truncated_inputs.append(_UpperCamelCase   )

              if padding_strategy == PaddingStrategy.LONGEST:
                     # make sure that `max_length` cannot be longer than the longest truncated length
                     __snake_case       	=							max(len(input_slice[self.model_input_names[0]]   ) for input_slice in truncated_inputs   )
                     __snake_case       	=							PaddingStrategy.MAX_LENGTH

              __snake_case       	=							{}
              for i in range(_UpperCamelCase   ):
                     # padding
                     __snake_case       	=							self._pad(
                         truncated_inputs[i]      , max_length=_UpperCamelCase      , padding_strategy=_UpperCamelCase      , pad_to_multiple_of=_UpperCamelCase      , return_attention_mask=_UpperCamelCase      , )

                     for key, value in outputs.items():
                            if key not in batch_outputs:
                                   __snake_case       	=							[]
                            if value.dtype is np.dtype(np.floataa   ):
                                   __snake_case       	=							value.astype(np.floataa   )
                            batch_outputs[key].append(_UpperCamelCase   )

              return BatchFeature(_UpperCamelCase      , tensor_type=_UpperCamelCase   )


       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase = None      , _UpperCamelCase = PaddingStrategy.DO_NOT_PAD      , _UpperCamelCase = None      , _UpperCamelCase = None      , )      ->							dict:






              """simple docstring"""


              __snake_case       	=							processed_features[self.model_input_names[0]]

              if padding_strategy == PaddingStrategy.LONGEST:
                     __snake_case       	=							len(_UpperCamelCase   )

              if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
                     __snake_case       	=							((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

              __snake_case       	=							padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_UpperCamelCase   ) < max_length

              if return_attention_mask and "attention_mask" not in processed_features:
                     __snake_case       	=							np.ones(len(_UpperCamelCase   )      , dtype=np.intaa   )

              if needs_to_be_padded:
                     __snake_case       	=							max_length - len(_UpperCamelCase   )
                     if self.padding_side == "right":
                            if return_attention_mask:
                                   __snake_case       	=							np.pad(
                                       processed_features["""attention_mask"""]      , (0, difference)   )
                            __snake_case       	=							((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
                            __snake_case       	=							np.pad(
                                _UpperCamelCase      , _UpperCamelCase      , """constant"""      , constant_values=self.padding_value   )
                     elif self.padding_side == "left":
                            if return_attention_mask:
                                   __snake_case       	=							np.pad(
                                       processed_features["""attention_mask"""]      , (difference, 0)   )
                            __snake_case       	=							((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
                            __snake_case       	=							np.pad(
                                _UpperCamelCase      , _UpperCamelCase      , """constant"""      , constant_values=self.padding_value   )
                     else:
                            raise ValueError("""Invalid padding strategy:""" + str(self.padding_side   )   )

              return processed_features


       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , )      ->							Optional[int]:






              """simple docstring"""


              if not truncation:
                     return processed_features
              elif truncation and max_length is None:
                     raise ValueError("""When setting ``truncation=True``, make sure that ``max_length`` is defined."""   )

              __snake_case       	=							processed_features[self.model_input_names[0]]

              # find `max_length` that fits `pad_to_multiple_of`
              if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
                     __snake_case       	=							((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

              __snake_case       	=							len(_UpperCamelCase   ) > max_length

              if needs_to_be_truncated:
                     __snake_case       	=							processed_features[self.model_input_names[0]][:max_length]
                     if "attention_mask" in processed_features:
                            __snake_case       	=							processed_features["""attention_mask"""][:max_length]

              return processed_features






       def 			a		(		self      , _UpperCamelCase=False      , _UpperCamelCase=None   )      ->							Optional[int]:






              """simple docstring"""


              if padding is not False:
                     if padding is True:
                            __snake_case       	=							PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
                     elif not isinstance(_UpperCamelCase      , _UpperCamelCase   ):
                            __snake_case       	=							PaddingStrategy(_UpperCamelCase   )
                     elif isinstance(_UpperCamelCase      , _UpperCamelCase   ):
                            __snake_case       	=							padding
              else:
                     __snake_case       	=							PaddingStrategy.DO_NOT_PAD

              # Set max length if needed
              if max_length is None:
                     if padding_strategy == PaddingStrategy.MAX_LENGTH:
                            raise ValueError(
                                F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined'   )

        # Test if we have a padding value
              if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
                     raise ValueError(
                         """Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"""
                         """ as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."""   )

              return padding_strategy




# 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


UpperCamelCase__		 =     '''Create a default config file for Accelerate with only a few flags set.'''







def 						lowerCamelCase__      ( __A    :List[Any]="no"	,__A    :str = default_json_config_file	,__A    :bool = False		):


       """simple docstring"""




       __snake_case       	=							Path(__A		)
       path.parent.mkdir(parents=__A	,exist_ok=__A		)
       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
       __snake_case       	=							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}'		)
       __snake_case       	=							{
           """compute_environment""": """LOCAL_MACHINE""",
           """mixed_precision""": mixed_precision,
       }
       if torch.cuda.is_available():
              __snake_case       	=							torch.cuda.device_count()
              __snake_case       	=							num_gpus
              __snake_case       	=							False
              if num_gpus > 1:
                     __snake_case       	=							"""MULTI_GPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_xpu_available() and use_xpu:
              __snake_case       	=							torch.xpu.device_count()
              __snake_case       	=							num_xpus
              __snake_case       	=							False
              if num_xpus > 1:
                     __snake_case       	=							"""MULTI_XPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_npu_available():
              __snake_case       	=							torch.npu.device_count()
              __snake_case       	=							num_npus
              __snake_case       	=							False
              if num_npus > 1:
                     __snake_case       	=							"""MULTI_NPU"""
              else:
                     __snake_case       	=							"""NO"""
       else:
              __snake_case       	=							0
              __snake_case       	=							True
              __snake_case       	=							1
              __snake_case       	=							"""NO"""
       __snake_case       	=							ClusterConfig(**__A		)
       config.to_json_file(__A		)
       return path







def 						lowerCamelCase__      ( __A    :Dict	,__A    :List[Any]		):


       """simple docstring"""




       __snake_case       	=							parser.add_parser("""default"""	,parents=__A	,help=__A	,formatter_class=__A		)
       parser.add_argument(
           """--config_file"""	,default=__A	,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=__A	,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=__A		)
       return parser







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       __snake_case       	=							write_basic_config(args.mixed_precision	,args.save_location		)
       if config_file:
              print(F'accelerate configuration saved at {config_file}'		)

