

# 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


lowerCAmelCase__							=			os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
lowerCAmelCase__							=			os.path.join(hf_cache_home, "accelerate")
lowerCAmelCase__							=			os.path.join(cache_dir, "default_config.yaml")
lowerCAmelCase__							=			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):
      lowerCAmelCase__							=			default_yaml_config_file
else:
      lowerCAmelCase__							=			default_json_config_file
def   _lowerCAmelCase(						__A      ):
  if config_file is not None:
    if not os.path.isfile(__A      ):
      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:
    UpperCAmelCase          =	default_config_file
  with open(__A ,							"r" ,							encoding="utf-8"      ) as f:
    if config_file.endswith(".json"      ):
      if (
          json.load(__A      ).get("compute_environment" ,							ComputeEnvironment.LOCAL_MACHINE      )
          == ComputeEnvironment.LOCAL_MACHINE
      ):
        UpperCAmelCase          =	ClusterConfig
      else:
        UpperCAmelCase          =	SageMakerConfig
      return config_class.from_json_file(json_file=__A      )
    else:
      if (
          yaml.safe_load(__A      ).get("compute_environment" ,							ComputeEnvironment.LOCAL_MACHINE      )
          == ComputeEnvironment.LOCAL_MACHINE
      ):
        UpperCAmelCase          =	ClusterConfig
      else:
        UpperCAmelCase          =	SageMakerConfig
      return config_class.from_yaml_file(yaml_file=__A      )






@dataclass
class     __magic_name__     :
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    42


 def _UpperCamelCase						(    self		:			str     )     ->   Any:
   UpperCAmelCase          =	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(lowerCAmelCase__      ,    lowerCAmelCase__     ):
       UpperCAmelCase          =	value.value
     if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) and not bool(lowerCAmelCase__     ):
       UpperCAmelCase          =	None
   UpperCAmelCase          =	{k: v for k, v in result.items() if v is not None}
   return result


 @classmethod
 def _UpperCamelCase						(    cls		:			List[str]      ,    lowerCAmelCase__		:			str=None     )     ->   str:
   UpperCAmelCase          =	default_json_config_file if json_file is None else json_file
   with open(lowerCAmelCase__      ,    "r"      ,    encoding="utf-8"     ) as f:
     UpperCAmelCase          =	json.load(lowerCAmelCase__     )
   if "compute_environment" not in config_dict:
     UpperCAmelCase          =	ComputeEnvironment.LOCAL_MACHINE
   if "mixed_precision" not in config_dict:
     UpperCAmelCase          =	"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.
     UpperCAmelCase          =	config_dict.pop("dynamo_backend"     )
     UpperCAmelCase          =	{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
   if "use_cpu" not in config_dict:
     UpperCAmelCase          =	False
   return cls(**lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Optional[int]      ,    lowerCAmelCase__		:			Optional[int]     )     ->   Any:
   with open(lowerCAmelCase__      ,    "w"      ,    encoding="utf-8"     ) as f:
     UpperCAmelCase          =	json.dumps(self.to_dict()      ,    indent=2      ,    sort_keys=lowerCAmelCase__     ) + "\n"
     f.write(lowerCAmelCase__     )


 @classmethod
 def _UpperCamelCase						(    cls		:			List[Any]      ,    lowerCAmelCase__		:			List[str]=None     )     ->   Union[str, Any]:
   UpperCAmelCase          =	default_yaml_config_file if yaml_file is None else yaml_file
   with open(lowerCAmelCase__      ,    "r"      ,    encoding="utf-8"     ) as f:
     UpperCAmelCase          =	yaml.safe_load(lowerCAmelCase__     )
   if "compute_environment" not in config_dict:
     UpperCAmelCase          =	ComputeEnvironment.LOCAL_MACHINE

   if "mixed_precision" not in config_dict:
     UpperCAmelCase          =	"fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
   if isinstance(config_dict["mixed_precision"]      ,    lowerCAmelCase__     ) and not config_dict["mixed_precision"]:
     UpperCAmelCase          =	"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.
     UpperCAmelCase          =	config_dict.pop("dynamo_backend"     )
     UpperCAmelCase          =	{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
   if "use_cpu" not in config_dict:
     UpperCAmelCase          =	False
   return cls(**lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			int      ,    lowerCAmelCase__		:			List[Any]     )     ->   Dict:
   with open(lowerCAmelCase__      ,    "w"      ,    encoding="utf-8"     ) as f:
     yaml.safe_dump(self.to_dict()      ,    lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			int     )     ->   int:
   if isinstance(self.compute_environment      ,    lowerCAmelCase__     ):
     UpperCAmelCase          =	ComputeEnvironment(self.compute_environment     )
   if isinstance(self.distributed_type      ,    lowerCAmelCase__     ):
     if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
       UpperCAmelCase          =	SageMakerDistributedType(self.distributed_type     )
     else:
       UpperCAmelCase          =	DistributedType(self.distributed_type     )
   if self.dynamo_config is None:
     UpperCAmelCase          =	{}






@dataclass
class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    0
 UpperCAmelCase				     =    1
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    "static"
 UpperCAmelCase				     =    False
 UpperCAmelCase				     =    "main"

 # args for deepspeed_plugin
 UpperCAmelCase				     =    None
 # args for fsdp
 UpperCAmelCase				     =    None
 # args for megatron_lm
 UpperCAmelCase				     =    None
 # args for ipex
 UpperCAmelCase				     =    None
 # args for TPU
 UpperCAmelCase				     =    False

 # args for TPU pods
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    False
 UpperCAmelCase				     =    False
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None

 # args for dynamo
 UpperCAmelCase				     =    None


 def _UpperCamelCase						(    self		:			str     )     ->   Dict:
   if self.deepspeed_config is None:
     UpperCAmelCase          =	{}
   if self.fsdp_config is None:
     UpperCAmelCase          =	{}
   if self.megatron_lm_config is None:
     UpperCAmelCase          =	{}
   if self.ipex_config is None:
     UpperCAmelCase          =	{}
   return super().__post_init__()






@dataclass
class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    42
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    "us-east-1"
 UpperCAmelCase				     =    1
 UpperCAmelCase				     =    "all"
 UpperCAmelCase				     =    f'''accelerate-sagemaker-{num_machines}'''
 UpperCAmelCase				     =    SAGEMAKER_PYTORCH_VERSION
 UpperCAmelCase				     =    SAGEMAKER_TRANSFORMERS_VERSION
 UpperCAmelCase				     =    SAGEMAKER_PYTHON_VERSION
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None
 UpperCAmelCase				     =    None






import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""image_processor""", """tokenizer"""]
 UpperCAmelCase				     =    """LayoutLMv2ImageProcessor"""
 UpperCAmelCase				     =    ("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")


 def __init__(    self		:			Any      ,    lowerCAmelCase__		:			Any=None      ,    lowerCAmelCase__		:			Optional[Any]=None      ,    **lowerCAmelCase__		:			int     )     ->   Union[str, Any]:
   UpperCAmelCase          =	None
   if "feature_extractor" in kwargs:
     warnings.warn(
         "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
         " instead."      ,    lowerCAmelCase__      ,    )
     UpperCAmelCase          =	kwargs.pop("feature_extractor"     )

   UpperCAmelCase          =	image_processor if image_processor is not None else feature_extractor
   if image_processor is None:
     raise ValueError("You need to specify an `image_processor`."     )
   if tokenizer is None:
     raise ValueError("You need to specify a `tokenizer`."     )

   super().__init__(lowerCAmelCase__      ,    lowerCAmelCase__     )


 def __call__(    self		:			int      ,    lowerCAmelCase__		:			Tuple      ,    lowerCAmelCase__		:			Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,    lowerCAmelCase__		:			Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None      ,    lowerCAmelCase__		:			Union[List[List[int]], List[List[List[int]]]] = None      ,    lowerCAmelCase__		:			Optional[Union[List[int], List[List[int]]]] = None      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Union[bool, str, PaddingStrategy] = False      ,    lowerCAmelCase__		:			Union[bool, str, TruncationStrategy] = False      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			int = 0      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Optional[Union[str, TensorType]] = None      ,    **lowerCAmelCase__		:			Any      ,    )     ->   BatchEncoding:
   # verify input
   if self.image_processor.apply_ocr and (boxes is not None):
     raise ValueError(
         "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."     )

   if self.image_processor.apply_ocr and (word_labels is not None):
     raise ValueError(
         "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."     )

   if return_overflowing_tokens is True and return_offsets_mapping is False:
     raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."     )

   # first, apply the image processor
   UpperCAmelCase          =	self.image_processor(images=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__     )

   # second, apply the tokenizer
   if text is not None and self.image_processor.apply_ocr and text_pair is None:
     if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ):
       UpperCAmelCase          =	[text]  # add batch dimension (as the image processor always adds a batch dimension)
     UpperCAmelCase          =	features["words"]

   UpperCAmelCase          =	self.tokenizer(
       text=text if text is not None else features["words"]      ,    text_pair=text_pair if text_pair is not None else None      ,    boxes=boxes if boxes is not None else features["boxes"]      ,    word_labels=lowerCAmelCase__      ,    add_special_tokens=lowerCAmelCase__      ,    padding=lowerCAmelCase__      ,    truncation=lowerCAmelCase__      ,    max_length=lowerCAmelCase__      ,    stride=lowerCAmelCase__      ,    pad_to_multiple_of=lowerCAmelCase__      ,    return_token_type_ids=lowerCAmelCase__      ,    return_attention_mask=lowerCAmelCase__      ,    return_overflowing_tokens=lowerCAmelCase__      ,    return_special_tokens_mask=lowerCAmelCase__      ,    return_offsets_mapping=lowerCAmelCase__      ,    return_length=lowerCAmelCase__      ,    verbose=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__      ,    **lowerCAmelCase__      ,    )

   # add pixel values
   UpperCAmelCase          =	features.pop("pixel_values"     )
   if return_overflowing_tokens is True:
     UpperCAmelCase          =	self.get_overflowing_images(lowerCAmelCase__      ,    encoded_inputs["overflow_to_sample_mapping"]     )
   UpperCAmelCase          =	images

   return encoded_inputs


 def _UpperCamelCase						(    self		:			str      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Union[str, Any]     )     ->   int:
   # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
   UpperCAmelCase          =	[]
   for sample_idx in overflow_to_sample_mapping:
     images_with_overflow.append(images[sample_idx]     )

   if len(lowerCAmelCase__     ) != len(lowerCAmelCase__     ):
     raise ValueError(
         "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
         f" {len(lowerCAmelCase__     )} and {len(lowerCAmelCase__     )}"     )

   return images_with_overflow


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    *lowerCAmelCase__		:			int      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[str]:
   return self.tokenizer.batch_decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    *lowerCAmelCase__		:			Tuple      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[Any]:
   return self.tokenizer.decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   List[str]:
   return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]


 @property
 def _UpperCamelCase						(    self		:			Dict     )     ->   List[str]:
   warnings.warn(
       "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor_class


 @property
 def _UpperCamelCase						(    self		:			List[Any]     )     ->   int:
   warnings.warn(
       "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor



