


import re
import tempfile
from pathlib import Path

import pytest
import yaml

from datasets.utils.readme import ReadMe


# @pytest.fixture
# def example_yaml_structure():

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


lowerCamelCase__							:						Dict							     =   {
    """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""": []},
                    ],
                },
            ],
        }
    ],
}


lowerCamelCase__							:						Tuple							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""


lowerCamelCase__							:						Optional[int]							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
#### Extra Ignored Subsection
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

lowerCamelCase__							:						int							     =   {
    """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""": []},
                    ],
                },
            ],
        }
    ],
}

lowerCamelCase__							:						Dict							     =   """\
---
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

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

lowerCamelCase__							:						Dict							     =   """\
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

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

lowerCamelCase__							:						List[str]							     =   """\
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

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

lowerCamelCase__							:						List[Any]							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
lowerCamelCase__							:						Optional[Any]							     =   """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)."""


lowerCamelCase__							:						str							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
"""
lowerCamelCase__							:						Optional[Any]							     =   """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'."""

lowerCamelCase__							:						List[str]							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Languages
Language Text
"""

lowerCamelCase__							:						List[str]							     =   """The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`."""


lowerCamelCase__							:						Optional[Any]							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
"""

lowerCamelCase__							:						Optional[Any]							     =   """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty."""

lowerCamelCase__							:						Tuple							     =   """\
---
language:
- zh
- en
---

## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
lowerCamelCase__							:						str							     =   """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."""

lowerCamelCase__							:						Optional[Any]							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
# Dataset Card My Dataset
"""

lowerCamelCase__							:						List[Any]							     =   """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."""

lowerCamelCase__							:						Union[str, Any]							     =   """\
---
language:
- zh
- en
---

# Dataset Card My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

lowerCamelCase__							:						Optional[Any]							     =   """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."""

lowerCamelCase__							:						Union[str, Any]							     =   """"""

lowerCamelCase__							:						Any							     =   """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."""

lowerCamelCase__							:						int							     =   """\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""

lowerCamelCase__							:						Optional[Any]							     =   """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 SCREAMING_SNAKE_CASE	(			__lowerCAmelCase							,   __lowerCAmelCase				)    ->				Optional[int]:
  assert ReadMe.from_string(__lowerCAmelCase							,   __lowerCAmelCase				).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 SCREAMING_SNAKE_CASE	(			__lowerCAmelCase							,   __lowerCAmelCase				)    ->				Dict:
  with pytest.raises(__lowerCAmelCase							,   match=re.escape(expected_error.format(path='''root'''				)				)				):
    snake_case__						= ReadMe.from_string(__lowerCAmelCase							,   __lowerCAmelCase				)
    readme.validate()







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







@pytest.mark.parametrize(
    '''readme_md,'''							,   [
        (README_MULTIPLE_SAME_HEADING_1),
    ]							,   )
def SCREAMING_SNAKE_CASE	(			__lowerCAmelCase				)    ->				str:
  ReadMe.from_string(__lowerCAmelCase							,   __lowerCAmelCase							,   suppress_parsing_errors=__lowerCAmelCase				)







@pytest.mark.parametrize(
    '''readme_md, expected_dict'''							,   [
        (README_CORRECT, CORRECT_DICT),
        (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
    ]							,   )
def SCREAMING_SNAKE_CASE	(			__lowerCAmelCase							,   __lowerCAmelCase				)    ->				Optional[Any]:
  with tempfile.TemporaryDirectory() as tmp_dir:
    snake_case__						= Path(__lowerCAmelCase				) / '''README.md'''
    with open(__lowerCAmelCase							,   '''w+'''				) as readme_file:
      readme_file.write(__lowerCAmelCase				)
    snake_case__						= ReadMe.from_readme(__lowerCAmelCase							,   __lowerCAmelCase				).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 SCREAMING_SNAKE_CASE	(			__lowerCAmelCase							,   __lowerCAmelCase				)    ->				List[Any]:
  with tempfile.TemporaryDirectory() as tmp_dir:
    snake_case__						= Path(__lowerCAmelCase				) / '''README.md'''
    with open(__lowerCAmelCase							,   '''w+'''				) as readme_file:
      readme_file.write(__lowerCAmelCase				)
    snake_case__						= expected_error.format(path=__lowerCAmelCase				)
    with pytest.raises(__lowerCAmelCase							,   match=re.escape(__lowerCAmelCase				)				):
      snake_case__						= ReadMe.from_readme(__lowerCAmelCase							,   __lowerCAmelCase				)
      readme.validate()







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







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





import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


lowerCamelCase__							:						Any							     =   """\

"""

lowerCamelCase__							:						List[str]							     =   """
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
"""

lowerCamelCase__							:						Any							     =   """
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to 'cuda' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        78.22
        >>> print(round(results[\"perplexities\"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = datasets.load_dataset(\"wikitext\",
        ...                                     \"wikitext-2-raw-v1\",
        ...                                     split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!='']
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        60.35
        >>> print(round(results[\"perplexities\"][0], 2))
        81.12
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,_KWARGS_DESCRIPTION				)
class 		__magic_name__						(datasets.Metric				):





     '''simple docstring'''



     def 	SCREAMING_SNAKE_CASE__						(					self:int   ):
       return datasets.MetricInfo(
           description=_DESCRIPTION     ,		citation=_CITATION     ,		inputs_description=_KWARGS_DESCRIPTION     ,		features=datasets.Features(
               {
                   '''input_texts''': datasets.Value('''string'''   ),
               }   )     ,		reference_urls=['''https://huggingface.co/docs/transformers/perplexity''']     ,		)







     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]     ,		_a:int     ,		_a:List[Any]     ,		_a:int = 16     ,		_a:bool = True     ,		_a:Any=None   ):
       if device is not None:
         assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
         if device == "gpu":
           snake_case__						= '''cuda'''
       else:
         snake_case__						= '''cuda''' if torch.cuda.is_available() else '''cpu'''

       snake_case__						= AutoModelForCausalLM.from_pretrained(_a   )
       snake_case__						= model.to(_a   )

       snake_case__						= AutoTokenizer.from_pretrained(_a   )

       # if batch_size > 1 (which generally leads to padding being required), and
       # if there is not an already assigned pad_token, assign an existing
       # special token to also be the padding token
       if tokenizer.pad_token is None and batch_size > 1:
         snake_case__						= list(tokenizer.special_tokens_map_extended.values()   )
         # check that the model already has at least one special token defined
         assert (
             len(_a   ) > 0
         ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
         # assign one of the special tokens to also be the pad token
         tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]}   )

       if add_start_token:
         # leave room for <BOS> token to be added:
         assert (
             tokenizer.bos_token is not None
         ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
         snake_case__						= model.config.max_length - 1
       else:
         snake_case__						= model.config.max_length

       snake_case__						= tokenizer(
           _a     ,		add_special_tokens=_a     ,		padding=_a     ,		truncation=_a     ,		max_length=_a     ,		return_tensors='''pt'''     ,		return_attention_mask=_a     ,		).to(_a   )

       snake_case__						= encodings['''input_ids''']
       snake_case__						= encodings['''attention_mask''']

       # check that each input is long enough:
       if add_start_token:
         assert torch.all(torch.ge(attn_masks.sum(1   )     ,		1   )   ), "Each input text must be at least one token long."
       else:
         assert torch.all(
             torch.ge(attn_masks.sum(1   )     ,		2   )   ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

       snake_case__						= []
       snake_case__						= CrossEntropyLoss(reduction='''none'''   )

       for start_index in logging.tqdm(range(0     ,		len(_a   )     ,		_a   )   ):
         snake_case__						= min(start_index + batch_size     ,		len(_a   )   )
         snake_case__						= encoded_texts[start_index:end_index]
         snake_case__						= attn_masks[start_index:end_index]

         if add_start_token:
           snake_case__						= torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0   )   ).to(_a   )
           snake_case__						= torch.cat([bos_tokens_tensor, encoded_batch]     ,		dim=1   )
           snake_case__						= torch.cat(
               [torch.ones(bos_tokens_tensor.size()     ,		dtype=torch.intaa   ).to(_a   ), attn_mask]     ,		dim=1   )

         snake_case__						= encoded_batch

         with torch.no_grad():
           snake_case__						= model(_a     ,		attention_mask=_a   ).logits

         snake_case__						= out_logits[..., :-1, :].contiguous()
         snake_case__						= labels[..., 1:].contiguous()
         snake_case__						= attn_mask[..., 1:].contiguous()

         snake_case__						= torch.expa(
             (loss_fct(shift_logits.transpose(1     ,		2   )     ,		_a   ) * shift_attention_mask_batch).sum(1   )
             / shift_attention_mask_batch.sum(1   )   )

         ppls += perplexity_batch.tolist()

       return {"perplexities": ppls, "mean_perplexity": np.mean(_a   )}

