



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
UpperCAmelCase_									=							pytest.mark.integration


UpperCAmelCase_									=							{"comet"}
UpperCAmelCase_									=							importlib.util.find_spec("fairseq") is not None

UpperCAmelCase_									=							{"code_eval"}
UpperCAmelCase_									=							os.name == "nt"

UpperCAmelCase_									=							{"bertscore", "frugalscore", "perplexity"}
UpperCAmelCase_									=							importlib.util.find_spec("transformers") is not None
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Tuple				)->Tuple:
      @wraps(_SCREAMING_SNAKE_CASE				)
      def wrapper(self   :	Optional[Any]     ,				_SCREAMING_SNAKE_CASE   :	Any				):
            if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
                  self.skipTest('''"test requires Fairseq"'''				)
            else:
                  test_case(self     ,				_SCREAMING_SNAKE_CASE				)

      return wrapper
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	int				)->Dict:
      @wraps(_SCREAMING_SNAKE_CASE				)
      def wrapper(self   :	Dict     ,				_SCREAMING_SNAKE_CASE   :	List[Any]				):
            if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
                  self.skipTest('''"test requires transformers"'''				)
            else:
                  test_case(self     ,				_SCREAMING_SNAKE_CASE				)

      return wrapper
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Any				)->Tuple:
      @wraps(_SCREAMING_SNAKE_CASE				)
      def wrapper(self   :	Optional[int]     ,				_SCREAMING_SNAKE_CASE   :	str				):
            if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
                  self.skipTest('''"test not supported on Windows"'''				)
            else:
                  test_case(self     ,				_SCREAMING_SNAKE_CASE				)

      return wrapper
def 							UpperCAmelCase__		(				)->List[str]:
      _lowerCAmelCase 			=  [metric_dir.split(os.sep				)[-2] for metric_dir in glob.glob('''./metrics/*/'''				)]
      return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()				)
@for_all_test_methods(
    UpperCAmelCase_       ,UpperCAmelCase_       ,UpperCAmelCase_				)
@local
class 		UpperCAmelCase						(						parameterized.TestCase				):

   '''simple docstring'''





   SCREAMING_SNAKE_CASE__							=     {}
   SCREAMING_SNAKE_CASE__							=     None





   @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''			)
   @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''			)
   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  '[...]'
         _lowerCAmelCase 			=  importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''       ,     _lowercase			)			).module_path			)
         _lowerCAmelCase 			=  datasets.load.import_main_class(metric_module.__name__       ,     dataset=_lowercase			)
         # check parameters
         _lowerCAmelCase 			=  inspect.signature(metric._compute			).parameters
         self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()			)			)  # no **kwargs
         # run doctest
         with self.patch_intensive_calls(_lowercase       ,     metric_module.__name__			):
               with self.use_local_metrics():
                     try:
                           _lowerCAmelCase 			=  doctest.testmod(_lowercase       ,     verbose=_lowercase       ,     raise_on_error=_lowercase			)
                     except doctest.UnexpectedException as e:
                           raise e.exc_info[1]  # raise the exception that doctest caught
         self.assertEqual(results.failed       ,     0			)
         self.assertGreater(results.attempted       ,     1			)





   @slow
   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  '[...]'
         _lowerCAmelCase 			=  importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''       ,     _lowercase			)			).module_path			)
         # run doctest
         with self.use_local_metrics():
               _lowerCAmelCase 			=  doctest.testmod(_lowercase       ,     verbose=_lowercase       ,     raise_on_error=_lowercase			)
         self.assertEqual(results.failed       ,     0			)
         self.assertGreater(results.attempted       ,     1			)





   @contextmanager
   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         if metric_name in self.INTENSIVE_CALLS_PATCHER:
               with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowercase			):
                     yield
         else:
               yield





   @contextmanager
   def 	__lowerCAmelCase							(	self			):
         def load_local_metric(_lowerCAmelCase       ,     *_lowerCAmelCase       ,     **_lowerCAmelCase			):
               return load_metric(os.path.join('''metrics'''       ,     _lowercase			)       ,     *_lowercase       ,     **_lowercase			)

         with patch('''datasets.load_metric'''			) as mock_load_metric:
               _lowerCAmelCase 			=  load_local_metric
               yield





   @classmethod
   def 	__lowerCAmelCase							(	cls       ,     _lowerCAmelCase			):
         def wrapper(_lowerCAmelCase			):
               _lowerCAmelCase 			=  contextmanager(_lowercase			)
               _lowerCAmelCase 			=  patcher
               return patcher

         return wrapper






@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Dict				)->Any:
      import tensorflow.compat.va as tf
      from bleurt.score import Predictor

      tf.flags.DEFINE_string('''sv'''     ,				''''''     ,				''''''				)  # handle pytest cli flags





      class 		UpperCAmelCase						(						UpperCAmelCase_				):

         '''simple docstring'''





         def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
               assert len(input_dict['''input_ids''']			) == 2
               return np.array([1.03, 1.04]			)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
      with patch('''bleurt.score._create_predictor'''				) as mock_create_predictor:
            _lowerCAmelCase 			=  MockedPredictor()
            yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Union[str, Any]				)->Tuple:
      import torch

      def bert_cos_score_idf(_SCREAMING_SNAKE_CASE   :	Any     ,				_SCREAMING_SNAKE_CASE   :	List[str]     ,				*_SCREAMING_SNAKE_CASE   :	Tuple     ,				**_SCREAMING_SNAKE_CASE   :	int				):
            return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE				)				)

      # mock get_model which is supposed to do download a bert model
      # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
      with patch('''bert_score.scorer.get_model'''				), patch(
          '''bert_score.scorer.bert_cos_score_idf'''				) as mock_bert_cos_score_idf:
            _lowerCAmelCase 			=  bert_cos_score_idf
            yield
@LocalMetricTest.register_intensive_calls_patcher('''comet'''				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Dict				)->Any:
      def load_from_checkpoint(_SCREAMING_SNAKE_CASE   :	Any				):





            class 		UpperCAmelCase						:

               '''simple docstring'''





               def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     *_lowerCAmelCase       ,     **_lowerCAmelCase			):
                     assert len(_lowercase			) == 2
                     _lowerCAmelCase 			=  [0.19, 0.92]
                     return scores, sum(_lowercase			) / len(_lowercase			)






            return Model()

      # mock load_from_checkpoint which is supposed to do download a bert model
      # mock load_from_checkpoint which is supposed to do download a bert model
      with patch('''comet.download_model'''				) as mock_download_model:
            _lowerCAmelCase 			=  None
            with patch('''comet.load_from_checkpoint'''				) as mock_load_from_checkpoint:
                  _lowerCAmelCase 			=  load_from_checkpoint
                  yield


def 							UpperCAmelCase__		(				)->Optional[Any]:
      _lowerCAmelCase 			=  load_metric(os.path.join('''metrics'''     ,				'''seqeval'''				)				)
      _lowerCAmelCase 			=  'ERROR'
      _lowerCAmelCase 			=  f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
      with pytest.raises(_SCREAMING_SNAKE_CASE     ,				match=re.escape(_SCREAMING_SNAKE_CASE				)				):
            metric.compute(predictions=[]     ,				references=[]     ,				scheme=_SCREAMING_SNAKE_CASE				)




# 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 argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


UpperCAmelCase_									=							"Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"
def 							UpperCAmelCase__		(				)->Any:
      _lowerCAmelCase 			=  _ask_options(
          '''In which compute environment are you running?'''     ,				['''This machine''', '''AWS (Amazon SageMaker)''']     ,				_convert_compute_environment     ,				)
      if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
            _lowerCAmelCase 			=  get_sagemaker_input()
      else:
            _lowerCAmelCase 			=  get_cluster_input()
      return config
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	int=None				)->str:
      if subparsers is not None:
            _lowerCAmelCase 			=  subparsers.add_parser('''config'''     ,				description=_SCREAMING_SNAKE_CASE				)
      else:
            _lowerCAmelCase 			=  argparse.ArgumentParser('''Accelerate config command'''     ,				description=_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\'.'''
          )     ,				)

      if subparsers is not None:
            parser.set_defaults(func=_SCREAMING_SNAKE_CASE				)
      return parser
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Dict				)->str:
      _lowerCAmelCase 			=  get_user_input()
      if args.config_file is not None:
            _lowerCAmelCase 			=  args.config_file
      else:
            if not os.path.isdir(_SCREAMING_SNAKE_CASE				):
                  os.makedirs(_SCREAMING_SNAKE_CASE				)
            _lowerCAmelCase 			=  default_yaml_config_file

      if config_file.endswith('''.json'''				):
            config.to_json_file(_SCREAMING_SNAKE_CASE				)
      else:
            config.to_yaml_file(_SCREAMING_SNAKE_CASE				)
      print(f'''accelerate configuration saved at {config_file}'''				)
def 							UpperCAmelCase__		(				)->List[Any]:
      _lowerCAmelCase 			=  config_command_parser()
      _lowerCAmelCase 			=  parser.parse_args()
      config_command(_SCREAMING_SNAKE_CASE				)


if __name__ == "__main__":
    main()