

import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile
from typing import List

from datasets import config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.info_utils import VerificationMode



def    UpperCamelCase(					lowercase_			,					**lowercase_							)	->				List[Any]:





  '''simple docstring'''





  return RunBeamCommand(
      args.dataset			,					args.name			,					args.cache_dir			,					args.beam_pipeline_options			,					args.data_dir			,					args.all_configs			,					args.save_info or args.save_infos			,					args.ignore_verifications			,					args.force_redownload			,					**lowercase_			,					)







class  __lowerCamelCase				(	__snake_case	):







      @staticmethod
      def 	lowerCAmelCase_    (     lowerCamelCase   )						->       Tuple:
        snake_case_       						=      parser.add_parser("""run_beam"""							,  help="""Run a Beam dataset processing pipeline"""   )
        run_beam_parser.add_argument("""dataset"""							,  type=lowerCamelCase							,  help="""Name of the dataset to download"""   )
        run_beam_parser.add_argument("""--name"""							,  type=lowerCamelCase							,  default=lowerCamelCase							,  help="""Dataset config name"""   )
        run_beam_parser.add_argument(
            """--cache_dir"""							,  type=lowerCamelCase							,  default=lowerCamelCase							,  help="""Cache directory where the datasets are stored"""							,  )
        run_beam_parser.add_argument(
            """--beam_pipeline_options"""							,  type=lowerCamelCase							,  default=""""""							,  help="""Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`"""							,  )
        run_beam_parser.add_argument(
            """--data_dir"""							,  type=lowerCamelCase							,  default=lowerCamelCase							,  help="""Can be used to specify a manual directory to get the files from"""							,  )
        run_beam_parser.add_argument("""--all_configs"""							,  action="""store_true"""							,  help="""Test all dataset configurations"""   )
        run_beam_parser.add_argument("""--save_info"""							,  action="""store_true"""							,  help="""Save the dataset infos file"""   )
        run_beam_parser.add_argument(
            """--ignore_verifications"""							,  action="""store_true"""							,  help="""Run the test without checksums and splits checks"""   )
        run_beam_parser.add_argument("""--force_redownload"""							,  action="""store_true"""							,  help="""Force dataset redownload"""   )
        # aliases
        run_beam_parser.add_argument("""--save_infos"""							,  action="""store_true"""							,  help="""alias for save_info"""   )
        run_beam_parser.set_defaults(func=lowerCamelCase   )







      def __init__(     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  **lowerCamelCase							,  )						->       Optional[Any]:
        snake_case_       						=      dataset
        snake_case_       						=      name
        snake_case_       						=      cache_dir
        snake_case_       						=      beam_pipeline_options
        snake_case_       						=      data_dir
        snake_case_       						=      all_configs
        snake_case_       						=      save_infos
        snake_case_       						=      ignore_verifications
        snake_case_       						=      force_redownload
        snake_case_       						=      config_kwargs







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        import apache_beam as beam

        if self._name is not None and self._all_configs:
          print("""Both parameters `name` and `all_configs` can't be used at once."""   )
          exit(1   )
        snake_case_						,				snake_case_       						=      self._dataset, self._name
        snake_case_       						=      dataset_module_factory(lowerCamelCase   )
        snake_case_       						=      import_main_class(dataset_module.module_path   )
        snake_case_       						=      []
        if self._beam_pipeline_options:
          snake_case_       						=      beam.options.pipeline_options.PipelineOptions(
              flags=[f'''--{opt.strip()}''' for opt in self._beam_pipeline_options.split(""","""   ) if opt]   )
        else:
          snake_case_       						=      None
        if self._all_configs and len(builder_cls.BUILDER_CONFIGS   ) > 0:
          for builder_config in builder_cls.BUILDER_CONFIGS:
            builders.append(
                builder_cls(
                    config_name=builder_config.name							,  data_dir=self._data_dir							,  hash=dataset_module.hash							,  beam_options=lowerCamelCase							,  cache_dir=self._cache_dir							,  base_path=dataset_module.builder_kwargs.get("""base_path"""   )							,  )   )
        else:
          builders.append(
              builder_cls(
                  config_name=lowerCamelCase							,  data_dir=self._data_dir							,  beam_options=lowerCamelCase							,  cache_dir=self._cache_dir							,  base_path=dataset_module.builder_kwargs.get("""base_path"""   )							,  **self._config_kwargs							,  )   )

        for builder in builders:
          builder.download_and_prepare(
              download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
              if not self._force_redownload
              else DownloadMode.FORCE_REDOWNLOAD							,  download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH   )							,  verification_mode=VerificationMode.NO_CHECKS
              if self._ignore_verifications
              else VerificationMode.ALL_CHECKS							,  try_from_hf_gcs=lowerCamelCase							,  )
          if self._save_infos:
            builder._save_infos()

        print("""Apache beam run successful."""   )

        # If save_infos=True, the dataset infos file is created next to the loaded module file.
        # Let's move it to the original directory of the dataset script, to allow the user to
        # upload them on S3 at the same time afterwards.
        if self._save_infos:
          snake_case_       						=      os.path.join(builder_cls.get_imported_module_dir()							,  config.DATASETDICT_INFOS_FILENAME   )

          snake_case_       						=      Path(lowerCamelCase   ).name + """.py"""

          snake_case_       						=      os.path.join(lowerCamelCase							,  lowerCamelCase   )
          if os.path.isfile(lowerCamelCase   ):
            snake_case_       						=      os.path.dirname(lowerCamelCase   )
          elif os.path.isfile(lowerCamelCase   ):
            snake_case_       						=      path
          else:  # in case of a remote dataset
            print(f'''Dataset Infos file saved at {dataset_infos_path}'''   )
            exit(1   )

          # Move datasetinfo back to the user
          snake_case_       						=      os.path.join(lowerCamelCase							,  config.DATASETDICT_INFOS_FILENAME   )
          copyfile(lowerCamelCase							,  lowerCamelCase   )
          print(f'''Dataset Infos file saved at {user_dataset_infos_path}'''   )


import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import (
        ErnieMForInformationExtraction,
        ErnieMForMultipleChoice,
        ErnieMForQuestionAnswering,
        ErnieMForSequenceClassification,
        ErnieMForTokenClassification,
        ErnieMModel,
    )
    from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST







class  __lowerCamelCase				:







      def __init__(     self							,  lowerCamelCase							,  lowerCamelCase=13							,  lowerCamelCase=7							,  lowerCamelCase=True							,  lowerCamelCase=True							,  lowerCamelCase=True							,  lowerCamelCase=99							,  lowerCamelCase=32							,  lowerCamelCase=5							,  lowerCamelCase=4							,  lowerCamelCase=37							,  lowerCamelCase="gelu"							,  lowerCamelCase=0.1							,  lowerCamelCase=0.1							,  lowerCamelCase=512							,  lowerCamelCase=16							,  lowerCamelCase=2							,  lowerCamelCase=0.02							,  lowerCamelCase=3							,  lowerCamelCase=4							,  lowerCamelCase=None							,  )						->       Optional[int]:
        snake_case_       						=      parent
        snake_case_       						=      batch_size
        snake_case_       						=      seq_length
        snake_case_       						=      is_training
        snake_case_       						=      use_input_mask
        snake_case_       						=      use_labels
        snake_case_       						=      vocab_size
        snake_case_       						=      hidden_size
        snake_case_       						=      num_hidden_layers
        snake_case_       						=      num_attention_heads
        snake_case_       						=      intermediate_size
        snake_case_       						=      hidden_act
        snake_case_       						=      hidden_dropout_prob
        snake_case_       						=      attention_probs_dropout_prob
        snake_case_       						=      max_position_embeddings
        snake_case_       						=      type_vocab_size
        snake_case_       						=      type_sequence_label_size
        snake_case_       						=      initializer_range
        snake_case_       						=      num_labels
        snake_case_       						=      num_choices
        snake_case_       						=      scope







      def 	lowerCAmelCase_    (     self   )						->       Optional[Any]:
        snake_case_       						=      ids_tensor([self.batch_size, self.seq_length]							,  self.vocab_size   )

        snake_case_       						=      None
        if self.use_input_mask:
          snake_case_       						=      random_attention_mask([self.batch_size, self.seq_length]   )

        snake_case_       						=      None
        snake_case_       						=      None
        snake_case_       						=      None
        if self.use_labels:
          snake_case_       						=      ids_tensor([self.batch_size]							,  self.type_sequence_label_size   )
          snake_case_       						=      ids_tensor([self.batch_size, self.seq_length]							,  self.num_labels   )
          snake_case_       						=      ids_tensor([self.batch_size]							,  self.num_choices   )

        snake_case_       						=      self.get_config()

        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels







      def 	lowerCAmelCase_    (     self   )						->       Optional[Any]:
        snake_case_       						=      ids_tensor([self.batch_size, self.seq_length]							,  self.vocab_size   )

        snake_case_       						=      None
        if self.use_input_mask:
          snake_case_       						=      random_attention_mask([self.batch_size, self.seq_length]   )
        snake_case_       						=      self.get_config()

        return config, input_ids, input_mask







      def 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        return ErnieMConfig(
            vocab_size=self.vocab_size							,  hidden_size=self.hidden_size							,  num_hidden_layers=self.num_hidden_layers							,  num_attention_heads=self.num_attention_heads							,  intermediate_size=self.intermediate_size							,  hidden_act=self.hidden_act							,  hidden_dropout_prob=self.hidden_dropout_prob							,  attention_probs_dropout_prob=self.attention_probs_dropout_prob							,  max_position_embeddings=self.max_position_embeddings							,  type_vocab_size=self.type_vocab_size							,  initializer_range=self.initializer_range							,  )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Union[str, Any]:
        snake_case_       						=      ErnieMModel(config=lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        snake_case_       						=      model(lowerCamelCase							,  return_dict=lowerCamelCase   )
        self.parent.assertEqual(result.last_hidden_state.shape							,  (self.batch_size, self.seq_length, self.hidden_size)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Tuple:
        snake_case_       						=      ErnieMForQuestionAnswering(config=lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        snake_case_       						=      model(
            lowerCamelCase							,  attention_mask=lowerCamelCase							,  start_positions=lowerCamelCase							,  end_positions=lowerCamelCase							,  )
        self.parent.assertEqual(result.start_logits.shape							,  (self.batch_size, self.seq_length)   )
        self.parent.assertEqual(result.end_logits.shape							,  (self.batch_size, self.seq_length)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Tuple:
        snake_case_       						=      ErnieMForInformationExtraction(config=lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        snake_case_       						=      torch.ones_like(lowerCamelCase							,  dtype=torch.floataa   )
        snake_case_       						=      model(
            lowerCamelCase							,  attention_mask=lowerCamelCase							,  start_positions=lowerCamelCase							,  end_positions=lowerCamelCase							,  )
        self.parent.assertEqual(result.start_logits.shape							,  (self.batch_size, self.seq_length)   )
        self.parent.assertEqual(result.end_logits.shape							,  (self.batch_size, self.seq_length)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Optional[Any]:
        snake_case_       						=      self.num_labels
        snake_case_       						=      ErnieMForSequenceClassification(lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        snake_case_       						=      model(lowerCamelCase							,  attention_mask=lowerCamelCase							,  labels=lowerCamelCase   )
        self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Union[str, Any]:
        snake_case_       						=      self.num_labels
        snake_case_       						=      ErnieMForTokenClassification(config=lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        input_ids.to(lowerCamelCase   )
        input_mask.to(lowerCamelCase   )
        token_labels.to(lowerCamelCase   )

        snake_case_       						=      model(lowerCamelCase							,  attention_mask=lowerCamelCase							,  labels=lowerCamelCase   )

        self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.seq_length, self.num_labels)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Any:
        snake_case_       						=      self.num_choices
        snake_case_       						=      ErnieMForMultipleChoice(config=lowerCamelCase   )
        model.to(lowerCamelCase   )
        model.eval()
        snake_case_       						=      input_ids.unsqueeze(1   ).expand(-1							,  self.num_choices							,  -1   ).contiguous()
        snake_case_       						=      input_mask.unsqueeze(1   ).expand(-1							,  self.num_choices							,  -1   ).contiguous()
        snake_case_       						=      model(
            lowerCamelCase							,  attention_mask=lowerCamelCase							,  labels=lowerCamelCase							,  )
        self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_choices)   )







      def 	lowerCAmelCase_    (     self   )						->       str:
        snake_case_       						=      self.prepare_config_and_inputs()
        (
            (
            snake_case_
        )						,				(
            snake_case_
        )						,				(
            snake_case_
        )						,				(
            snake_case_
        )						,				(
            snake_case_
        )						,				(
            snake_case_
        )						,				
        )       						=      config_and_inputs
        snake_case_       						=      {"""input_ids""": input_ids, """attention_mask""": input_mask}
        return config, inputs_dict







@require_torch
class  __lowerCamelCase				(	__snake_case  ,							__snake_case  ,							unittest.TestCase	):
      lowerCamelCase_	:      Optional[int]          =					(
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      lowerCamelCase_	:      List[str]          =					()
      lowerCamelCase_	:      Optional[int]          =					(
          {
              'feature-extraction': ErnieMModel,
              'question-answering': ErnieMForQuestionAnswering,
              'text-classification': ErnieMForSequenceClassification,
              'token-classification': ErnieMForTokenClassification,
              'zero-shot': ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      lowerCamelCase_	:      List[Any]          =					False







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Tuple:
        if pipeline_test_casse_name == "QAPipelineTests":
          return True

        return False







      def 	lowerCAmelCase_    (     self   )						->       Tuple:
        snake_case_       						=      ErnieMModelTester(self   )
        snake_case_       						=      ConfigTester(self							,  config_class=lowerCamelCase							,  hidden_size=37   )







      def 	lowerCAmelCase_    (     self   )						->       Any:
        self.config_tester.run_common_tests()







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       int:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
          snake_case_       						=      type
          self.model_tester.create_and_check_model(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Optional[Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_information_extraction(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Union[str, Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowerCamelCase   )







      @slow
      def 	lowerCAmelCase_    (     self   )						->       int:
        for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          snake_case_       						=      ErnieMModel.from_pretrained(lowerCamelCase   )
          self.assertIsNotNone(lowerCamelCase   )







@require_torch
class  __lowerCamelCase				(	unittest.TestCase	):







      @slow
      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_       						=      ErnieMModel.from_pretrained("""susnato/ernie-m-base_pytorch"""   )
        model.eval()
        snake_case_       						=      torch.tensor([[0, 1, 2, 3, 4, 5]]   )
        snake_case_       						=      model(lowerCamelCase   )[0]

        # TODO Replace vocab size
        snake_case_       						=      768

        snake_case_       						=      torch.Size((1, 6, hidden_size)   )
        self.assertEqual(output.shape							,  lowerCamelCase   )

        snake_case_       						=      torch.tensor(
            [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]   )

        self.assertTrue(torch.allclose(output[:, :3, :3]							,  lowerCamelCase							,  atol=1e-3   )   )