





import re
import tempfile
from pathlib import Path

import pytest
import yaml

from datasets.utils.readme import ReadMe


# @pytest.fixture
# def example_yaml_structure():

_UpperCAmelCase        =				yaml.safe_load(
    '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n  - name: "Dataset Card for X" # First-level markdown heading\n    allow_empty: false\n    allow_empty_text: true\n    subsections:\n      - name: "Table of Contents"\n        allow_empty: false\n        allow_empty_text: false\n        subsections: null\n      - name: "Dataset Description"\n        allow_empty: false\n        allow_empty_text: false\n        subsections:\n          - name: "Dataset Summary"\n            allow_empty: false\n            allow_empty_text: false\n            subsections: null\n          - name: "Supported Tasks and Leaderboards"\n            allow_empty: true\n            allow_empty_text: true\n            subsections: null\n          - name: Languages\n            allow_empty: false\n            allow_empty_text: true\n            subsections: null\n'
)


_UpperCAmelCase        =				{
    'name': 'root',
    'text': '',
    'is_empty_text': True,
    'subsections': [
        {
            'name': 'Dataset Card for My Dataset',
            'text': '',
            'is_empty_text': True,
            'subsections': [
                {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []},
                {
                    'name': 'Dataset Description',
                    'text': 'Some text here.',
                    'is_empty_text': False,
                    'subsections': [
                        {
                            'name': 'Dataset Summary',
                            'text': 'Some text here.',
                            'is_empty_text': False,
                            'subsections': [],
                        },
                        {
                            'name': 'Supported Tasks and Leaderboards',
                            'text': '',
                            'is_empty_text': True,
                            'subsections': [],
                        },
                        {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []},
                    ],
                },
            ],
        }
    ],
}


_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'


_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				{
    'name': 'root',
    'text': '',
    'is_empty_text': True,
    'subsections': [
        {
            'name': 'Dataset Card for My Dataset',
            'text': '',
            'is_empty_text': True,
            'subsections': [
                {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []},
                {
                    'name': 'Dataset Description',
                    'text': 'Some text here.',
                    'is_empty_text': False,
                    'subsections': [
                        {
                            'name': 'Dataset Summary',
                            'text': 'Some text here.',
                            'is_empty_text': False,
                            'subsections': [
                                {
                                    'name': 'Extra Ignored Subsection',
                                    'text': '',
                                    'is_empty_text': True,
                                    'subsections': [],
                                }
                            ],
                        },
                        {
                            'name': 'Supported Tasks and Leaderboards',
                            'text': '',
                            'is_empty_text': True,
                            'subsections': [],
                        },
                        {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []},
                    ],
                },
            ],
        }
    ],
}

_UpperCAmelCase        =				'\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				(
    'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.'
)

_UpperCAmelCase        =				'\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				(
    'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.'
)

_UpperCAmelCase        =				'\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).'


_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n'
_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.'


_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n'

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n'

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.'

_UpperCAmelCase        =				''

_UpperCAmelCase        =				'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.'

_UpperCAmelCase        =				'\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'

_UpperCAmelCase        =				'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.'




@pytest.mark.parametrize(
    "readme_md, expected_dict"					,		[
        (README_CORRECT, CORRECT_DICT),
        (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		Union[str, Any]:
       assert ReadMe.from_string(UpperCamelCase_					,		UpperCamelCase_  ).to_dict() == expected_dict




@pytest.mark.parametrize(
    "readme_md, expected_error"					,		[
        (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
        (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
        (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
        (README_EMPTY, EXPECTED_ERROR_README_EMPTY),
        (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
        (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
        (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
        (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
        (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
        (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
        (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		int:
       with pytest.raises(UpperCamelCase_					,		match=re.escape(expected_error.format(path="root"  )  )  ):
              UpperCamelCase_          =  ReadMe.from_string(UpperCamelCase_					,		UpperCamelCase_  )
              readme.validate()




@pytest.mark.parametrize(
    "readme_md, expected_error"					,		[
        (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		List[Any]:
       with pytest.raises(UpperCamelCase_					,		match=re.escape(expected_error.format(path="root"  )  )  ):
              ReadMe.from_string(UpperCamelCase_					,		UpperCamelCase_  )




@pytest.mark.parametrize(
    "readme_md,"					,		[
        (README_MULTIPLE_SAME_HEADING_1),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_  )     ->		Optional[Any]:
       ReadMe.from_string(UpperCamelCase_					,		UpperCamelCase_					,		suppress_parsing_errors=UpperCamelCase_  )




@pytest.mark.parametrize(
    "readme_md, expected_dict"					,		[
        (README_CORRECT, CORRECT_DICT),
        (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		Tuple:
       with tempfile.TemporaryDirectory() as tmp_dir:
              UpperCamelCase_          =  Path(UpperCamelCase_  ) / "README.md"
              with open(UpperCamelCase_					,		"w+"  ) as readme_file:
                     readme_file.write(UpperCamelCase_  )
              UpperCamelCase_          =  ReadMe.from_readme(UpperCamelCase_					,		UpperCamelCase_  ).to_dict()
              assert out["name"] == path
              assert out["text"] == ""
              assert out["is_empty_text"]
              assert out["subsections"] == expected_dict["subsections"]




@pytest.mark.parametrize(
    "readme_md, expected_error"					,		[
        (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
        (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
        (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
        (README_EMPTY, EXPECTED_ERROR_README_EMPTY),
        (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
        (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
        (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
        (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
        (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
        (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
        (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		Tuple:
       with tempfile.TemporaryDirectory() as tmp_dir:
              UpperCamelCase_          =  Path(UpperCamelCase_  ) / "README.md"
              with open(UpperCamelCase_					,		"w+"  ) as readme_file:
                     readme_file.write(UpperCamelCase_  )
              UpperCamelCase_          =  expected_error.format(path=UpperCamelCase_  )
              with pytest.raises(UpperCamelCase_					,		match=re.escape(UpperCamelCase_  )  ):
                     UpperCamelCase_          =  ReadMe.from_readme(UpperCamelCase_					,		UpperCamelCase_  )
                     readme.validate()




@pytest.mark.parametrize(
    "readme_md, expected_error"					,		[
        (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_  )     ->		Any:
       with tempfile.TemporaryDirectory() as tmp_dir:
              UpperCamelCase_          =  Path(UpperCamelCase_  ) / "README.md"
              with open(UpperCamelCase_					,		"w+"  ) as readme_file:
                     readme_file.write(UpperCamelCase_  )
              UpperCamelCase_          =  expected_error.format(path=UpperCamelCase_  )
              with pytest.raises(UpperCamelCase_					,		match=re.escape(UpperCamelCase_  )  ):
                     ReadMe.from_readme(UpperCamelCase_					,		UpperCamelCase_  )







@pytest.mark.parametrize(
    "readme_md,"					,		[
        (README_MULTIPLE_SAME_HEADING_1),
    ]					,		)
def  lowerCAmelCase_ (							UpperCamelCase_  )     ->		Optional[Any]:
       with tempfile.TemporaryDirectory() as tmp_dir:
              UpperCamelCase_          =  Path(UpperCamelCase_  ) / "README.md"
              with open(UpperCamelCase_					,		"w+"  ) as readme_file:
                     readme_file.write(UpperCamelCase_  )
              ReadMe.from_readme(UpperCamelCase_					,		UpperCamelCase_					,		suppress_parsing_errors=UpperCamelCase_  )








import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment




def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=None					,		UpperCamelCase_="no"					,		UpperCamelCase_="29500"  )     ->		Optional[Any]:
       UpperCamelCase_          =  False
       UpperCamelCase_          =  False
       if any(key.startswith("KAGGLE"  ) for key in os.environ.keys()  ):
              UpperCamelCase_          =  True
       elif "IPython" in sys.modules:
              UpperCamelCase_          =  "google.colab" in str(sys.modules["IPython"].get_ipython()  )

       try:
              UpperCamelCase_          =  PrecisionType(mixed_precision.lower()  )
       except ValueError:
              raise ValueError(
                  F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''  )

       if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME"					,		UpperCamelCase_  ) is not None):
              # TPU launch
              import torch_xla.distributed.xla_multiprocessing as xmp

              if len(AcceleratorState._shared_state  ) > 0:
                     raise ValueError(
                         "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
                         "your training function. Restart your notebook and make sure no cells initializes an "
                         "`Accelerator`."  )
              if num_processes is None:
                     UpperCamelCase_          =  8

              UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="TPU"  )
              print(F'''Launching a training on {num_processes} TPU cores.'''  )
              xmp.spawn(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
       elif in_colab:
              # No need for a distributed launch otherwise as it's either CPU or one GPU.
              if torch.cuda.is_available():
                     print("Launching training on one GPU."  )
              else:
                     print("Launching training on one CPU."  )
              function(*UpperCamelCase_  )
       else:
              if num_processes is None:
                     raise ValueError(
                         "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."  )

              if num_processes > 1:
                     # Multi-GPU launch
                     from torch.multiprocessing import start_processes
                     from torch.multiprocessing.spawn import ProcessRaisedException

                     if len(AcceleratorState._shared_state  ) > 0:
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
                                "inside your training function. Restart your notebook and make sure no cells initializes an "
                                "`Accelerator`."  )

                     if torch.cuda.is_initialized():
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, you need to avoid running any instruction "
                                "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA "
                                "function."  )

                     # torch.distributed will expect a few environment variable to be here. We set the ones common to each
                     # process here (the other ones will be set be the launcher).
                     with patch_environment(
                         world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port=UpperCamelCase_					,		mixed_precision=UpperCamelCase_  ):
                            UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="MULTI_GPU"  )
                            print(F'''Launching training on {num_processes} GPUs.'''  )
                            try:
                                   start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
                            except ProcessRaisedException as e:
                                   if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                                          raise RuntimeError(
                                              "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
                                              "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
                                              "Please review your imports and test them when running the `notebook_launcher()` to identify "
                                              "which one is problematic."  ) from e

              else:
                     # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
                     if is_mps_available():
                            UpperCamelCase_          =  "1"
                            print("Launching training on MPS."  )
                     elif torch.cuda.is_available():
                            print("Launching training on one GPU."  )
                     else:
                            print("Launching training on CPU."  )
                     function(*UpperCamelCase_  )







def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=2  )     ->		Optional[Any]:
       from torch.multiprocessing import start_processes

       with tempfile.NamedTemporaryFile() as tmp_file:
              # torch.distributed will expect a few environment variable to be here. We set the ones common to each
              # process here (the other ones will be set be the launcher).
              with patch_environment(
                  world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port="29500"					,		accelerate_mixed_precision="no"					,		accelerate_debug_rdv_file=tmp_file.name					,		accelerate_use_cpu="yes"					,		):
                     UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		debug=UpperCamelCase_  )
                     start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )

