import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
UpperCAmelCase				 =   logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=2.0.0""", """To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt""")







def 						UpperCAmelCase							(		lowerCAmelCase_    ,   lowerCAmelCase_    ,   lowerCAmelCase_=0							)						->						Optional[Any]:
     a	:     Dict						      =    (size, size) if isinstance(lowerCAmelCase_    ,   lowerCAmelCase_							) else size
     a      ,				a	:     int						      =    img.size
     a	:     Any						      =    size[1] - original_height if original_height < size[1] else 0
     a	:     str						      =    size[0] - original_width if original_width < size[0] else 0
     a	:     str						      =    functional.pad(lowerCAmelCase_    ,   (0, 0, pad_width, pad_height)    ,   fill=lowerCAmelCase_							)
     return img






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_     )						->int:
        a	:     int						      =    transforms


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->List[str]:
        for t in self.transforms:
             a      ,				a	:     List[str]						      =    t(lowerCAmelCase_				,  lowerCAmelCase_     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self     )						->str:
        pass


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->List[str]:
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_     )						->Tuple:
        a	:     Dict						      =    size


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Optional[Any]:
        a	:     List[str]						      =    functional.resize(lowerCAmelCase_				,  self.size     )
        a	:     Union[str, Any]						      =    functional.resize(lowerCAmelCase_				,  self.size				,  interpolation=transforms.InterpolationMode.NEAREST     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_=None     )						->Dict:
        a	:     Dict						      =    min_size
        if max_size is None:
             a	:     Any						      =    min_size
        a	:     str						      =    max_size


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->int:
        a	:     Any						      =    random.randint(self.min_size				,  self.max_size     )
        a	:     Optional[Any]						      =    functional.resize(lowerCAmelCase_				,  lowerCAmelCase_     )
        a	:     Any						      =    functional.resize(lowerCAmelCase_				,  lowerCAmelCase_				,  interpolation=transforms.InterpolationMode.NEAREST     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_     )						->List[str]:
        a	:     str						      =    size if isinstance(lowerCAmelCase_				,  lowerCAmelCase_     ) else (size, size)


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Optional[int]:
        a	:     Optional[int]						      =    pad_if_smaller(lowerCAmelCase_				,  self.size     )
        a	:     Union[str, Any]						      =    pad_if_smaller(lowerCAmelCase_				,  self.size				,  fill=2_55     )
        a	:     Optional[int]						      =    transforms.RandomCrop.get_params(lowerCAmelCase_				,  self.size     )
        a	:     Tuple						      =    functional.crop(lowerCAmelCase_				,  *lowerCAmelCase_     )
        a	:     Optional[Any]						      =    functional.crop(lowerCAmelCase_				,  *lowerCAmelCase_     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_     )						->int:
        a	:     List[str]						      =    flip_prob


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->List[str]:
        if random.random() < self.flip_prob:
             a	:     List[str]						      =    functional.hflip(lowerCAmelCase_     )
             a	:     Dict						      =    functional.hflip(lowerCAmelCase_     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Dict:
        a	:     Dict						      =    functional.pil_to_tensor(lowerCAmelCase_     )
        a	:     Tuple						      =    torch.as_tensor(np.array(lowerCAmelCase_     )				,  dtype=torch.intaa     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_     )						->Optional[int]:
        a	:     Any						      =    dtype


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->List[str]:
        a	:     List[Any]						      =    functional.convert_image_dtype(lowerCAmelCase_				,  self.dtype     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Union[str, Any]:
        a	:     List[Any]						      =    mean
        a	:     Tuple						      =    std


   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Tuple:
        a	:     str						      =    functional.normalize(lowerCAmelCase_				,  mean=self.mean				,  std=self.std     )
        return image, target






class 				_SCREAMING_SNAKE_CASE:
   def __call__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Optional[int]:
        if not isinstance(lowerCAmelCase_				,  np.ndarray     ):
             a	:     List[str]						      =    np.array(lowerCAmelCase_     ).astype(np.uinta     )
        # avoid using underflow conversion
        a	:     Dict						      =    2_55
        a	:     Optional[int]						      =    target - 1
        a	:     Optional[int]						      =    2_55

        a	:     str						      =    Image.fromarray(lowerCAmelCase_     )
        return image, target






@dataclass
class 				_SCREAMING_SNAKE_CASE:
   UpperCamelCase_					:    Optional[str]			      = field(
       default='segments/sidewalk-semantic'							,   metadata={
           'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'
       }							,   )
   UpperCamelCase_					:    Optional[str]			      = field(
       default=snake_case__							,   metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}						)
   UpperCamelCase_					:    Optional[float]			      = field(
       default=0.15							,   metadata={'help': 'Percent to split off of train for validation.'}						)
   UpperCamelCase_					:    Optional[int]			      = field(
       default=snake_case__							,   metadata={
           'help': (
               'For debugging purposes or quicker training, truncate the number of training examples to this '
               'value if set.'
           )
       }							,   )
   UpperCamelCase_					:    Optional[int]			      = field(
       default=snake_case__							,   metadata={
           'help': (
               'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
               'value if set.'
           )
       }							,   )
   UpperCamelCase_					:    Optional[bool]			      = field(
       default=snake_case__							,   metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}							,   )
   def _lowercase(     self     )						->Union[str, Any]:
        if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
             raise ValueError(
                 '''You must specify either a dataset name from the hub or a train and/or validation directory.'''     )






@dataclass
class 				_SCREAMING_SNAKE_CASE:
   UpperCamelCase_					:    str			      = field(
       default='nvidia/mit-b0'							,   metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}							,   )
   UpperCamelCase_					:    Optional[str]			      = field(
       default=snake_case__							,   metadata={'help': 'Pretrained config name or path if not the same as model_name'}						)
   UpperCamelCase_					:    Optional[str]			      = field(
       default=snake_case__							,   metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}						)
   UpperCamelCase_					:    str			      = field(
       default='main'							,   metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}							,   )
   UpperCamelCase_					:    str			      = field(default=snake_case__							,   metadata={'help': 'Name or path of preprocessor config.'}						)
   UpperCamelCase_					:    bool			      = field(
       default=snake_case__							,   metadata={
           'help': (
               'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
               'with private models).'
           )
       }							,   )







def 						UpperCAmelCase							(		)						->						Optional[Any]:
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.

     a	:     Tuple						      =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
     if len(sys.argv							) == 2 and sys.argv[1].endswith('''.json'''							):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          a      ,				a      ,				a	:     List[Any]						      =    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
     else:
          a      ,				a      ,				a	:     Union[str, Any]						      =    parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('''run_semantic_segmentation'''    ,   lowerCAmelCase_    ,   lowerCAmelCase_							)

     # Setup logging
     logging.basicConfig(
         format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''    ,   datefmt='''%m/%d/%Y %H:%M:%S'''    ,   handlers=[logging.StreamHandler(sys.stdout							)]    ,   )

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     a	:     Optional[Any]						      =    training_args.get_process_log_level()
     logger.setLevel(lowerCAmelCase_							)
     transformers.utils.logging.set_verbosity(lowerCAmelCase_							)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
         + f"""distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}"""							)
     logger.info(f"""Training/evaluation parameters {training_args}"""							)

     # Detecting last checkpoint.
     a	:     List[Any]						      =    None
     if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
          a	:     Union[str, Any]						      =    get_last_checkpoint(training_args.output_dir							)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
               raise ValueError(
                   f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                   '''Use --overwrite_output_dir to overcome.'''							)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                   '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''							)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
     a	:     str						      =    load_dataset(data_args.dataset_name    ,   cache_dir=model_args.cache_dir							)

     # Rename column names to standardized names (only "image" and "label" need to be present)
     if "pixel_values" in dataset["train"].column_names:
          a	:     List[str]						      =    dataset.rename_columns({'''pixel_values''': '''image'''}							)
     if "annotation" in dataset["train"].column_names:
          a	:     int						      =    dataset.rename_columns({'''annotation''': '''label'''}							)

     # If we don't have a validation split, split off a percentage of train as validation.
     a	:     Dict						      =    None if '''validation''' in dataset.keys() else data_args.train_val_split
     if isinstance(data_args.train_val_split    ,   lowerCAmelCase_							) and data_args.train_val_split > 0.0:
          a	:     Optional[Any]						      =    dataset['''train'''].train_test_split(data_args.train_val_split							)
          a	:     str						      =    split['''train''']
          a	:     Tuple						      =    split['''test''']

     # Prepare label mappings.
     # We'll include these in the model's config to get human readable labels in the Inference API.
     if data_args.dataset_name == "scene_parse_150":
          a	:     List[str]						      =    '''huggingface/label-files'''
          a	:     Dict						      =    '''ade20k-id2label.json'''
     else:
          a	:     Dict						      =    data_args.dataset_name
          a	:     Optional[Any]						      =    '''id2label.json'''
     a	:     Optional[int]						      =    json.load(open(hf_hub_download(lowerCAmelCase_    ,   lowerCAmelCase_    ,   repo_type='''dataset'''							)    ,   '''r'''							)							)
     a	:     Tuple						      =    {int(lowerCAmelCase_							): v for k, v in idalabel.items()}
     a	:     int						      =    {v: str(lowerCAmelCase_							) for k, v in idalabel.items()}

     # Load the mean IoU metric from the datasets package
     a	:     Optional[Any]						      =    evaluate.load('''mean_iou'''							)

     # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
     # predictions and label_ids field) and has to return a dictionary string to float.
     @torch.no_grad()
     def compute_metrics(lowerCAmelCase_							):
          a      ,				a	:     List[Any]						      =    eval_pred
          a	:     Union[str, Any]						      =    torch.from_numpy(lowerCAmelCase_							)
          # scale the logits to the size of the label
          a	:     Optional[int]						      =    nn.functional.interpolate(
              lowerCAmelCase_    ,   size=labels.shape[-2:]    ,   mode='''bilinear'''    ,   align_corners=lowerCAmelCase_    ,   ).argmax(dim=1							)

          a	:     str						      =    logits_tensor.detach().cpu().numpy()
          a	:     Optional[Any]						      =    metric.compute(
              predictions=lowerCAmelCase_    ,   references=lowerCAmelCase_    ,   num_labels=len(lowerCAmelCase_							)    ,   ignore_index=0    ,   reduce_labels=image_processor.do_reduce_labels    ,   )
          # add per category metrics as individual key-value pairs
          a	:     Optional[int]						      =    metrics.pop('''per_category_accuracy'''							).tolist()
          a	:     Optional[int]						      =    metrics.pop('''per_category_iou'''							).tolist()

          metrics.update({f"""accuracy_{idalabel[i]}""": v for i, v in enumerate(lowerCAmelCase_							)}							)
          metrics.update({f"""iou_{idalabel[i]}""": v for i, v in enumerate(lowerCAmelCase_							)}							)

          return metrics

     a	:     Tuple						      =    AutoConfig.from_pretrained(
         model_args.config_name or model_args.model_name_or_path    ,   labelaid=lowerCAmelCase_    ,   idalabel=lowerCAmelCase_    ,   cache_dir=model_args.cache_dir    ,   revision=model_args.model_revision    ,   use_auth_token=True if model_args.use_auth_token else None    ,   )
     a	:     Optional[Any]						      =    AutoModelForSemanticSegmentation.from_pretrained(
         model_args.model_name_or_path    ,   from_tf=bool('''.ckpt''' in model_args.model_name_or_path							)    ,   config=lowerCAmelCase_    ,   cache_dir=model_args.cache_dir    ,   revision=model_args.model_revision    ,   use_auth_token=True if model_args.use_auth_token else None    ,   )
     a	:     str						      =    AutoImageProcessor.from_pretrained(
         model_args.image_processor_name or model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir    ,   revision=model_args.model_revision    ,   use_auth_token=True if model_args.use_auth_token else None    ,   )

     # Define torchvision transforms to be applied to each image + target.
     # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
     # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
     if "shortest_edge" in image_processor.size:
          # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
          a	:     List[Any]						      =    (image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
     else:
          a	:     List[str]						      =    (image_processor.size['''height'''], image_processor.size['''width'''])
     a	:     List[str]						      =    Compose(
         [
             ReduceLabels() if data_args.reduce_labels else Identity(),
             RandomCrop(size=lowerCAmelCase_							),
             RandomHorizontalFlip(flip_prob=0.5							),
             PILToTensor(),
             ConvertImageDtype(torch.float							),
             Normalize(mean=image_processor.image_mean    ,   std=image_processor.image_std							),
         ]							)
     # Define torchvision transform to be applied to each image.
     # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
     a	:     int						      =    Compose(
         [
             ReduceLabels() if data_args.reduce_labels else Identity(),
             Resize(size=lowerCAmelCase_							),
             PILToTensor(),
             ConvertImageDtype(torch.float							),
             Normalize(mean=image_processor.image_mean    ,   std=image_processor.image_std							),
         ]							)

     def preprocess_train(lowerCAmelCase_							):
          a	:     Optional[int]						      =    []
          a	:     int						      =    []
          for image, target in zip(example_batch['''image''']    ,   example_batch['''label''']							):
               a      ,				a	:     List[str]						      =    train_transforms(image.convert('''RGB'''							)    ,   lowerCAmelCase_							)
               pixel_values.append(lowerCAmelCase_							)
               labels.append(lowerCAmelCase_							)

          a	:     Optional[Any]						      =    {}
          a	:     Union[str, Any]						      =    torch.stack(lowerCAmelCase_							)
          a	:     Optional[Any]						      =    torch.stack(lowerCAmelCase_							)

          return encoding

     def preprocess_val(lowerCAmelCase_							):
          a	:     Optional[int]						      =    []
          a	:     int						      =    []
          for image, target in zip(example_batch['''image''']    ,   example_batch['''label''']							):
               a      ,				a	:     Union[str, Any]						      =    val_transforms(image.convert('''RGB'''							)    ,   lowerCAmelCase_							)
               pixel_values.append(lowerCAmelCase_							)
               labels.append(lowerCAmelCase_							)

          a	:     Tuple						      =    {}
          a	:     Optional[Any]						      =    torch.stack(lowerCAmelCase_							)
          a	:     List[Any]						      =    torch.stack(lowerCAmelCase_							)

          return encoding

     if training_args.do_train:
          if "train" not in dataset:
               raise ValueError('''--do_train requires a train dataset'''							)
          if data_args.max_train_samples is not None:
               a	:     Union[str, Any]						      =    (
                   dataset['''train'''].shuffle(seed=training_args.seed							).select(range(data_args.max_train_samples							)							)
               )
          # Set the training transforms
          dataset["train"].set_transform(lowerCAmelCase_							)

     if training_args.do_eval:
          if "validation" not in dataset:
               raise ValueError('''--do_eval requires a validation dataset'''							)
          if data_args.max_eval_samples is not None:
               a	:     Any						      =    (
                   dataset['''validation'''].shuffle(seed=training_args.seed							).select(range(data_args.max_eval_samples							)							)
               )
          # Set the validation transforms
          dataset["validation"].set_transform(lowerCAmelCase_							)

     # Initalize our trainer
     a	:     Any						      =    Trainer(
         model=lowerCAmelCase_    ,   args=lowerCAmelCase_    ,   train_dataset=dataset['''train'''] if training_args.do_train else None    ,   eval_dataset=dataset['''validation'''] if training_args.do_eval else None    ,   compute_metrics=lowerCAmelCase_    ,   tokenizer=lowerCAmelCase_    ,   data_collator=lowerCAmelCase_    ,   )

     # Training
     if training_args.do_train:
          a	:     Optional[int]						      =    None
          if training_args.resume_from_checkpoint is not None:
               a	:     Dict						      =    training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               a	:     int						      =    last_checkpoint
          a	:     Tuple						      =    trainer.train(resume_from_checkpoint=lowerCAmelCase_							)
          trainer.save_model()
          trainer.log_metrics('''train'''    ,   train_result.metrics							)
          trainer.save_metrics('''train'''    ,   train_result.metrics							)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          a	:     str						      =    trainer.evaluate()
          trainer.log_metrics('''eval'''    ,   lowerCAmelCase_							)
          trainer.save_metrics('''eval'''    ,   lowerCAmelCase_							)

     # Write model card and (optionally) push to hub
     a	:     Optional[Any]						      =    {
         '''finetuned_from''': model_args.model_name_or_path,
         '''dataset''': data_args.dataset_name,
         '''tags''': ['''image-segmentation''', '''vision'''],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**lowerCAmelCase_							)
     else:
          trainer.create_model_card(**lowerCAmelCase_							)


if __name__ == "__main__":
  main()
import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata







def 						UpperCAmelCase							(		lowerCAmelCase_							)						->						str:
     a	:     Optional[Any]						      =    min(re.search('''^ +'''    ,   lowerCAmelCase_							).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(lowerCAmelCase_							)]							)


UpperCAmelCase				 =   """\
---
language:
- zh
- en
task_ids:
- sentiment-classification
---
# Begin of markdown

Some cool dataset card
"""

UpperCAmelCase				 =   """\
---
---
# Begin of markdown

Some cool dataset card
"""


UpperCAmelCase				 =   """\
# Begin of markdown

Some cool dataset card
"""






class 				_SCREAMING_SNAKE_CASE( unittest.TestCase						):
   def _lowercase(     self     )						->List[str]:
        with tempfile.TemporaryDirectory() as tmp_dir:
             a	:     List[str]						      =    Path(lowerCAmelCase_     ) / '''README.md'''
             with open(lowerCAmelCase_				,  '''w+'''     ) as readme_file:
                  readme_file.write(lowerCAmelCase_     )
             a	:     Dict						      =    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	:     List[str]						      =    DatasetMetadata.from_readme(lowerCAmelCase_     )
             self.assertDictEqual(lowerCAmelCase_				,  {}     )

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


   def _lowercase(     self     )						->Optional[Any]:
        a	:     Tuple						      =    _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	:     Dict						      =    _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	:     Optional[int]						      =    _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_     )