

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}'''   )







"""simple docstring"""







import unittest

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


if is_torch_available():
			import torch

			from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer


@require_torch
class     __UpperCAmelCase(   unittest.TestCase							):




						"""simple docstring"""




						@slow
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Optional[int]=       XLMProphetNetForConditionalGeneration.from_pretrained("microsoft/xprophetnet-large-wiki100-cased"			)
												model.to(snake_case__			)

												# encoder-decoder outputs
												lowercase__				:      Dict=       torch.tensor([[17, 96208, 103471, 2]]			).to(snake_case__			)
												lowercase__				:      Optional[Any]=       torch.tensor(
												    [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]			).to(snake_case__			)
												lowercase__				:      Dict=       model(
												    input_ids=snake_case__       ,  attention_mask=snake_case__       ,  encoder_outputs=snake_case__       ,  decoder_input_ids=snake_case__			)
												lowercase__				:      int=       output[0]
												lowercase__				:      str=       torch.Size((1, 14, 250012)			)
												self.assertEqual(output_predited_logis.shape       ,  snake_case__			)
												lowercase__				:      Union[str, Any]=       torch.tensor(
												    [[[-6.39_86, -8.23_91, 12.51_89], [-6.32_89, -8.08_64, 12.62_11], [-6.24_18, -8.04_45, 12.79_68]]]			).to(snake_case__			)
												self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]       ,  snake_case__       ,  atol=1e-4			)			)

												# encoder outputs
												lowercase__				:      Tuple=       model.prophetnet.encoder(snake_case__			)[0]
												lowercase__				:      Union[str, Any]=       torch.tensor(
												    [[[-1.42_60, -0.76_28, 0.84_53], [-1.47_19, -0.13_91, 0.78_07], [-1.76_78, 0.01_14, 0.46_46]]]			).to(snake_case__			)
												lowercase__				:      List[Any]=       torch.Size((1, 4, 1024)			)
												self.assertEqual(encoder_outputs.shape       ,  snake_case__			)
												self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]       ,  snake_case__       ,  atol=1e-4			)			)

												# decoder outputs
												lowercase__				:      int=       model.prophetnet.decoder(
												    snake_case__       ,  encoder_hidden_states=snake_case__       ,  )
												lowercase__				:      Union[str, Any]=       decoder_outputs[1].view(1       ,  model.config.ngram       ,  14       ,  -1			)
												lowercase__				:      List[Any]=       model.lm_head(snake_case__			)
												lowercase__				:      str=       predicting_streams_logits[:, 0]
												self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]       ,  snake_case__       ,  atol=1e-4			)			)




						@slow
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Union[str, Any]=       XLMProphetNetForConditionalGeneration.from_pretrained(
												    "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"			)
												model.to(snake_case__			)

												lowercase__				:      Dict=       torch.tensor([[17, 96208, 103471, 2]]			).to(snake_case__			)
												lowercase__				:      List[str]=       torch.tensor(
												    [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]			).to(snake_case__			)
												lowercase__				:      List[Any]=       model(
												    input_ids=snake_case__       ,  attention_mask=snake_case__       ,  encoder_outputs=snake_case__       ,  decoder_input_ids=snake_case__			)
												lowercase__				:      str=       output[0]
												lowercase__				:      Optional[Any]=       torch.Size((1, 14, 250012)			)
												self.assertEqual(output_predited_logis.shape       ,  snake_case__			)
												# compare the actual values for a slice.
												lowercase__				:      str=       torch.tensor(
												    [[[-9.22_53, -9.71_73, -6.35_29], [-7.67_01, -9.01_45, -1.93_82], [-8.01_95, -7.00_04, -0.15_23]]]			).to(snake_case__			)

												self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]       ,  snake_case__       ,  atol=1e-4			)			)




						@slow
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Tuple=       XLMProphetNetForConditionalGeneration.from_pretrained(
												    "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"			)
												model.to(snake_case__			)
												lowercase__				:      Optional[int]=       512

												lowercase__				:      int=       XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"			)

												lowercase__				:      str=       (
												    "Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"
												    " January 14, 2020, according to the official portal of the organization. From that day, users of this"
												    " system will not be able to receive security updates, which could make their computers vulnerable to"
												    " cyber attacks."
												)
												lowercase__				:      Tuple=       (
												    "орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"
												    " после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"
												    " этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"
												    " к кибератакам."
												)
												lowercase__				:      Optional[int]=       (
												    "根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"
												)

												lowercase__				:      Dict=       tokenizer(
												    [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]       ,  padding=snake_case__       ,  max_length=255       ,  return_tensors="pt"			).input_ids
												lowercase__				:      Any=       input_ids.to(snake_case__			)

												lowercase__				:      List[Any]=       model.generate(
												    snake_case__       ,  num_beams=10       ,  length_penalty=1.0       ,  no_repeat_ngram_size=3       ,  early_stopping=snake_case__			)
												lowercase__				:      str=       [tokenizer.decode(snake_case__       ,  skip_special_tokens=snake_case__			) for g in summary_ids]
												lowercase__				:      Dict=       "Microsoft to end Windows 7 free support after January 14, 2020"
												lowercase__				:      int=       "Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"
												lowercase__				:      List[str]=       "微软打算终止对Windows 7操作系统的免费支持"
												self.assertListEqual(
												    [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]       ,  snake_case__       ,  )

												lowercase__				:      List[str]=       model.generate(
												    snake_case__       ,  num_beams=1       ,  length_penalty=1.0       ,  no_repeat_ngram_size=3       ,  early_stopping=snake_case__			)
												lowercase__				:      Optional[Any]=       [
												    tokenizer.convert_ids_to_tokens(snake_case__       ,  skip_special_tokens=snake_case__			) for g in summary_ids_beama
												]
												lowercase__				:      List[str]=       "▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7".split(" "			)
												lowercase__				:      List[Any]=       "▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года".split(
												    " "			)
												lowercase__				:      int=       "微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持".split(" "			)
												self.assertListEqual(
												    [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]       ,  snake_case__       ,  )






