


# 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.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_snake_case					=					os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
_snake_case					=					os.path.join(hf_cache_home, '''accelerate''')
_snake_case					=					os.path.join(cache_dir, '''default_config.yaml''')
_snake_case					=					os.path.join(cache_dir, '''default_config.yaml''')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
     _snake_case					=					default_yaml_config_file
else:
     _snake_case					=					default_json_config_file






def 		lowercase_(  SCREAMING_SNAKE_CASE_     ):


  '''simple docstring'''

  if config_file is not None:
    if not os.path.isfile(SCREAMING_SNAKE_CASE_     ):
      raise FileNotFoundError(
          f"""The passed configuration file `{config_file}` does not exist. """
          "Please pass an existing file to `accelerate launch`, or use the the default one "
          "created through `accelerate config` and run `accelerate launch` "
          "without the `--config_file` argument."     )
  else:
    lowerCamelCase			: Optional[int]   =    default_config_file
  with open(SCREAMING_SNAKE_CASE_				,						"r"				,						encoding="utf-8"     ) as f:
    if config_file.endswith(".json"     ):
      if (
          json.load(SCREAMING_SNAKE_CASE_     ).get("compute_environment"				,						ComputeEnvironment.LOCAL_MACHINE     )
          == ComputeEnvironment.LOCAL_MACHINE
      ):
        lowerCamelCase			: int   =    ClusterConfig
      else:
        lowerCamelCase			: List[str]   =    SageMakerConfig
      return config_class.from_json_file(json_file=SCREAMING_SNAKE_CASE_     )
    else:
      if (
          yaml.safe_load(SCREAMING_SNAKE_CASE_     ).get("compute_environment"				,						ComputeEnvironment.LOCAL_MACHINE     )
          == ComputeEnvironment.LOCAL_MACHINE
      ):
        lowerCamelCase			: List[Any]   =    ClusterConfig
      else:
        lowerCamelCase			: Dict   =    SageMakerConfig
      return config_class.from_yaml_file(yaml_file=SCREAMING_SNAKE_CASE_     )
@dataclass
class      UpperCAmelCase_ :

   '''simple docstring'''




   __A			:				ComputeEnvironment
   __A			:				Union[DistributedType, SageMakerDistributedType]
   __A			:				str
   __A			:				bool






   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Optional[Any]   =    self.__dict__
     # For serialization, it's best to convert Enums to strings (or their underlying value type).
     for key, value in result.items():
       if isinstance(__A						,    __A			):
         lowerCamelCase			: Optional[int]   =    value.value
       if isinstance(__A						,    __A			) and not bool(__A			):
         lowerCamelCase			: Dict   =    None
     lowerCamelCase			: int   =    {k: v for k, v in result.items() if v is not None}
     return result






   @classmethod
   def _snake_case   (		cls						,    __A=None			):






     """simple docstring"""





     lowerCamelCase			: str   =    default_json_config_file if json_file is None else json_file
     with open(__A						,    "r"						,    encoding="utf-8"			) as f:
       lowerCamelCase			: Optional[Any]   =    json.load(__A			)
     if "compute_environment" not in config_dict:
       lowerCamelCase			: List[str]   =    ComputeEnvironment.LOCAL_MACHINE
     if "mixed_precision" not in config_dict:
       lowerCamelCase			: Tuple   =    "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
     if "fp16" in config_dict:  # Convert the config to the new format.
       del config_dict["fp16"]
     if "dynamo_backend" in config_dict:  # Convert the config to the new format.
       lowerCamelCase			: List[str]   =    config_dict.pop("dynamo_backend"			)
       lowerCamelCase			: Optional[int]   =    {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
     if "use_cpu" not in config_dict:
       lowerCamelCase			: Tuple   =    False
     return cls(**__A			)






   def _snake_case   (		self						,    __A			):






     """simple docstring"""





     with open(__A						,    "w"						,    encoding="utf-8"			) as f:
       lowerCamelCase			: Any   =    json.dumps(self.to_dict()						,    indent=2						,    sort_keys=__A			) + "\n"
       f.write(__A			)






   @classmethod
   def _snake_case   (		cls						,    __A=None			):






     """simple docstring"""





     lowerCamelCase			: Tuple   =    default_yaml_config_file if yaml_file is None else yaml_file
     with open(__A						,    "r"						,    encoding="utf-8"			) as f:
       lowerCamelCase			: Optional[int]   =    yaml.safe_load(__A			)
     if "compute_environment" not in config_dict:
       lowerCamelCase			: str   =    ComputeEnvironment.LOCAL_MACHINE

     if "mixed_precision" not in config_dict:
       lowerCamelCase			: int   =    "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
     if isinstance(config_dict["mixed_precision"]						,    __A			) and not config_dict["mixed_precision"]:
       lowerCamelCase			: str   =    "no"
     if "fp16" in config_dict:  # Convert the config to the new format.
       del config_dict["fp16"]
     if "dynamo_backend" in config_dict:  # Convert the config to the new format.
       lowerCamelCase			: List[Any]   =    config_dict.pop("dynamo_backend"			)
       lowerCamelCase			: Any   =    {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
     if "use_cpu" not in config_dict:
       lowerCamelCase			: List[Any]   =    False
     return cls(**__A			)






   def _snake_case   (		self						,    __A			):






     """simple docstring"""





     with open(__A						,    "w"						,    encoding="utf-8"			) as f:
       yaml.safe_dump(self.to_dict()						,    __A			)






   def _snake_case   (		self			):






     """simple docstring"""





     if isinstance(self.compute_environment						,    __A			):
       lowerCamelCase			: Any   =    ComputeEnvironment(self.compute_environment			)
     if isinstance(self.distributed_type						,    __A			):
       if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
         lowerCamelCase			: int   =    SageMakerDistributedType(self.distributed_type			)
       else:
         lowerCamelCase			: Dict   =    DistributedType(self.distributed_type			)
     if self.dynamo_config is None:
       lowerCamelCase			: Dict   =    {}



@dataclass
class      UpperCAmelCase_ ( UpperCamelCase   ):

   '''simple docstring'''




   __A			:				int
   __A			:				int							=		0
   __A			:				int							=		1
   __A			:				Optional[str]							=		None
   __A			:				Optional[str]							=		None
   __A			:				Optional[int]							=		None
   __A			:				Optional[str]							=		"static"
   __A			:				Optional[bool]							=		False
   __A			:				str							=		"main"

   # args for deepspeed_plugin
   __A			:				dict							=		None
   # args for fsdp
   __A			:				dict							=		None
   # args for megatron_lm
   __A			:				dict							=		None
   # args for ipex
   __A			:				dict							=		None
   # args for TPU
   __A			:				bool							=		False

   # args for TPU pods
   __A			:				str							=		None
   __A			:				str							=		None
   __A			:				bool							=		False
   __A			:				bool							=		False
   __A			:				str							=		None
   __A			:				List[str]							=		None
   __A			:				List[str]							=		None
   __A			:				List[str]							=		None

   # args for dynamo
   __A			:				dict							=		None






   def _snake_case   (		self			):






     """simple docstring"""





     if self.deepspeed_config is None:
       lowerCamelCase			: Optional[int]   =    {}
     if self.fsdp_config is None:
       lowerCamelCase			: int   =    {}
     if self.megatron_lm_config is None:
       lowerCamelCase			: Union[str, Any]   =    {}
     if self.ipex_config is None:
       lowerCamelCase			: List[Any]   =    {}
     return super().__post_init__()



@dataclass
class      UpperCAmelCase_ ( UpperCamelCase   ):

   '''simple docstring'''




   __A			:				str
   __A			:				str
   __A			:				Optional[str]							=		None
   __A			:				Optional[str]							=		None
   __A			:				str							=		"us-east-1"
   __A			:				int							=		1
   __A			:				str							=		"all"
   __A			:				str							=		f"accelerate-sagemaker-{num_machines}"
   __A			:				str							=		SAGEMAKER_PYTORCH_VERSION
   __A			:				str							=		SAGEMAKER_TRANSFORMERS_VERSION
   __A			:				str							=		SAGEMAKER_PYTHON_VERSION
   __A			:				str							=		None
   __A			:				str							=		None
   __A			:				dict							=		None
   __A			:				dict							=		None







from typing import Optional, Union

from ...file_utils import TensorType
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy
class      UpperCAmelCase_ ( UpperCamelCase   ):

   '''simple docstring'''




   __A			:				Union[str, Any]							=		"MarkupLMFeatureExtractor"
   __A			:				List[str]							=		("MarkupLMTokenizer", "MarkupLMTokenizerFast")
   __A			:				str							=		True






   def __call__(		self						,    __A=None						,    __A=None						,    __A=None						,    __A=None						,    __A=None						,    __A = True						,    __A = False						,    __A = None						,    __A = None						,    __A = 0						,    __A = None						,    __A = None						,    __A = None						,    __A = False						,    __A = False						,    __A = False						,    __A = False						,    __A = True						,    __A = None						,    **__A						,    ):






     """simple docstring"""





     if self.parse_html:
       if html_strings is None:
         raise ValueError("Make sure to pass HTML strings in case `parse_html` is set to `True`"			)

       if nodes is not None or xpaths is not None or node_labels is not None:
         raise ValueError(
             "Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`"			)

       lowerCamelCase			: Any   =    self.feature_extractor(__A			)
       lowerCamelCase			: Optional[int]   =    features["nodes"]
       lowerCamelCase			: Any   =    features["xpaths"]
     else:
       if html_strings is not None:
         raise ValueError("You have passed HTML strings but `parse_html` is set to `False`."			)
       if nodes is None or xpaths is None:
         raise ValueError("Make sure to pass nodes and xpaths in case `parse_html` is set to `False`"			)

        # # second, apply the tokenizer
     if questions is not None and self.parse_html:
       if isinstance(__A						,    __A			):
         lowerCamelCase			: Tuple   =    [questions]  # add batch dimension (as the feature extractor always adds a batch dimension)

     lowerCamelCase			: Tuple   =    self.tokenizer(
         text=questions if questions is not None else nodes						,    text_pair=nodes if questions is not None else None						,    xpaths=__A						,    node_labels=__A						,    add_special_tokens=__A						,    padding=__A						,    truncation=__A						,    max_length=__A						,    stride=__A						,    pad_to_multiple_of=__A						,    return_token_type_ids=__A						,    return_attention_mask=__A						,    return_overflowing_tokens=__A						,    return_special_tokens_mask=__A						,    return_offsets_mapping=__A						,    return_length=__A						,    verbose=__A						,    return_tensors=__A						,    **__A						,    )

     return encoded_inputs






   def _snake_case   (		self						,    *__A						,    **__A			):






     """simple docstring"""





     return self.tokenizer.batch_decode(*__A						,    **__A			)






   def _snake_case   (		self						,    *__A						,    **__A			):






     """simple docstring"""





     return self.tokenizer.decode(*__A						,    **__A			)






   @property
   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Dict   =    self.tokenizer.model_input_names
     return tokenizer_input_names



