
import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata






def 						lowerCamelCase__							(      a   )   ->     str:
   _A:						Dict	    = min(re.search('''^ +'''	,	a   ).end() if t.startswith(''' '''   ) else 0 for t in string.splitlines()   )
   return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(a   )]   )


UpperCAmelCase__	:  int      =   '\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n'

UpperCAmelCase__	:  Tuple      =   '\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n'


UpperCAmelCase__	:  str      =   '\\n# Begin of markdown\n\nSome cool dataset card\n'






class UpperCAmelCase	(		unittest.TestCase     ):





   '''simple docstring'''


   def 				__magic_name__       (      self  :							Union[str, Any]  ):

      """simple docstring"""
      with tempfile.TemporaryDirectory() as tmp_dir:
         _A:						Union[str, Any]	    = Path(lowerCAmelCase_  ) / '''README.md'''
         with open(lowerCAmelCase_    ,    '''w+'''  ) as readme_file:
            readme_file.write(lowerCAmelCase_  )
         _A:						Optional[int]	    = DatasetMetadata.from_readme(lowerCAmelCase_  )
         self.assertDictEqual(lowerCAmelCase_    ,    {'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}  )

         with open(lowerCAmelCase_    ,    '''w+'''  ) as readme_file:
            readme_file.write(lowerCAmelCase_  )
         _A:						Dict	    = DatasetMetadata.from_readme(lowerCAmelCase_  )
         self.assertDictEqual(lowerCAmelCase_    ,    {}  )

         with open(lowerCAmelCase_    ,    '''w+'''  ) as readme_file:
            readme_file.write(lowerCAmelCase_  )
         _A:						Union[str, Any]	    = DatasetMetadata.from_readme(lowerCAmelCase_  )
         self.assertEqual(lowerCAmelCase_    ,    {}  )


   def 				__magic_name__       (      self  :							Optional[int]  ):

      """simple docstring"""
      _A:						str	    = _dedent(
          '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            '''  )
      assert DatasetMetadata.from_yaml_string(lowerCAmelCase_  )

      _A:						Union[str, Any]	    = _dedent(
          '''\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            '''  )
      with self.assertRaises(lowerCAmelCase_  ):
         DatasetMetadata.from_yaml_string(lowerCAmelCase_  )

      _A:						Any	    = _dedent(
          '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            '''  )
      assert DatasetMetadata.from_yaml_string(lowerCAmelCase_  )





# This test is meant to be run in on an instance with TPUs like this:
#
#   python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py
#
# Replace 8 with the number of TPU cores you have.
#

import sys
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.utils import logging


UpperCAmelCase__	:  Union[str, Any]      =   logging.get_logger(__name__)


if is_torch_available():
   import torch
   from torch import nn
   from torch.utils.data import Dataset

   from transformers import Trainer






   class UpperCAmelCase     (		SCREAMING_SNAKE_CASE__     ):





      '''simple docstring'''


      def __init__(      self  :							List[Any]    ,    lowerCAmelCase_  :							int = 1_0_1  ):

         """simple docstring"""
         _A:						str	    = length


      def __len__(      self  :							List[Any]  ):

         """simple docstring"""
         return self.length


      def __getitem__(      self  :							Any    ,    lowerCAmelCase_  :							Any  ):

         """simple docstring"""
         return i






   class UpperCAmelCase     :





      '''simple docstring'''


      def __call__(      self  :							Any    ,    lowerCAmelCase_  :							Union[str, Any]  ):

         """simple docstring"""
         return {"input_ids": torch.tensor(lowerCAmelCase_  ), "labels": torch.tensor(lowerCAmelCase_  )}






   class UpperCAmelCase     (		nn.Module     ):





      '''simple docstring'''


      def __init__(      self  :							str  ):

         """simple docstring"""
         super().__init__()
         # Add some (unused) params otherwise DDP will complain.
         _A:						Tuple	    = nn.Linear(1_2_0    ,    8_0  )


      def 				__magic_name__       (      self  :							List[Any]    ,    lowerCAmelCase_  :							List[str]    ,    lowerCAmelCase_  :							List[str]=None  ):

         """simple docstring"""
         if labels is not None:
            return torch.tensor(0.0    ,    device=input_ids.device  ), input_ids
         else:
            return input_ids






def 						lowerCamelCase__							(      )   ->     Optional[int]:
   _A:						Any	    = HfArgumentParser((TrainingArguments,)   )
   sys.argv += ["--output_dir", "./examples"]
   _A:						Any	    = parser.parse_args_into_dataclasses()[0]

   logger.warning(
       f"""Process rank: {training_args.local_rank}, device: {training_args.device}, """
       f"""tpu_num_cores: {training_args.tpu_num_cores}"""	,	)

   # Essentially, what we want to verify in the distributed case is
   # that we get all samples back, in the right order.
   # (this is crucial for prediction for instance)
   for dataset_length in [10_01, 2_56, 15]:
      _A:						Any	    = DummyDataset(a   )

      def compute_metrics(a   ) -> Dict:
         _A:						Dict	    = list(range(len(a   )   )   )
         _A:						List[str]	    = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
         return {"success": success}

      _A:						Optional[Any]	    = Trainer(
          model=DummyModel()	,	args=a	,	data_collator=DummyDataCollator()	,	eval_dataset=a	,	compute_metrics=a	,	)
      _A:						List[str]	    = trainer.evaluate()
      logger.info(a   )
      if metrics["eval_success"] is not True:
         logger.error(a   )
         exit(1   )

      _A:						Optional[Any]	    = trainer.predict(a   )
      logger.info(p.metrics   )
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics   )
         exit(1   )

      _A:						str	    = 2

      _A:						Optional[Any]	    = trainer.evaluate()
      logger.info(a   )
      if metrics["eval_success"] is not True:
         logger.error(a   )
         exit(1   )

      _A:						Optional[Any]	    = trainer.predict(a   )
      logger.info(p.metrics   )
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics   )
         exit(1   )

      _A:						str	    = None

   logger.info('''🔥 All distributed tests successful'''   )






def 						lowerCamelCase__							(      a   )   ->     Optional[Any]:
   # For xla_spawn (TPUs)
   main()


if __name__ == "__main__":
   main()



