





"""simple docstring"""
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 			__snake_case						(      __A ,**__A    )		->				int:
   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 ,**__A ,)







class lowerCamelCase__  (    __UpperCamelCase				):



   @staticmethod
   def    _UpperCAmelCase	(       snake_case	) ->    List[str]:







      """simple docstring"""
      lowercase    :			Tuple  =       parser.add_parser("""run_beam"""      ,   help="""Run a Beam dataset processing pipeline"""	)
      run_beam_parser.add_argument("""dataset"""      ,   type=snake_case      ,   help="""Name of the dataset to download"""	)
      run_beam_parser.add_argument("""--name"""      ,   type=snake_case      ,   default=snake_case      ,   help="""Dataset config name"""	)
      run_beam_parser.add_argument(
          """--cache_dir"""      ,   type=snake_case      ,   default=snake_case      ,   help="""Cache directory where the datasets are stored"""      ,   )
      run_beam_parser.add_argument(
          """--beam_pipeline_options"""      ,   type=snake_case      ,   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=snake_case      ,   default=snake_case      ,   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=snake_case	)



   def __init__(       self      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case      ,   **snake_case      ,   ) ->    List[str]:







      """simple docstring"""
      lowercase    :			Optional[Any]  =       dataset
      lowercase    :			Dict  =       name
      lowercase    :			Optional[Any]  =       cache_dir
      lowercase    :			int  =       beam_pipeline_options
      lowercase    :			List[str]  =       data_dir
      lowercase    :			Dict  =       all_configs
      lowercase    :			Union[str, Any]  =       save_infos
      lowercase    :			Dict  =       ignore_verifications
      lowercase    :			Dict  =       force_redownload
      lowercase    :			Dict  =       config_kwargs





   def    _UpperCAmelCase	(       self	) ->    List[str]:







      """simple docstring"""
      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	)
      lowercase  ,					lowercase    :			int  =       self._dataset, self._name
      lowercase    :			str  =       dataset_module_factory(snake_case	)
      lowercase    :			List[Any]  =       import_main_class(dataset_module.module_path	)
      lowercase    :			List[DatasetBuilder]  =       []
      if self._beam_pipeline_options:
         lowercase    :			Tuple  =       beam.options.pipeline_options.PipelineOptions(
             flags=[f'''--{opt.strip()}''' for opt in self._beam_pipeline_options.split(""","""	) if opt]	)
      else:
         lowercase    :			str  =       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=snake_case      ,   cache_dir=self._cache_dir      ,   base_path=dataset_module.builder_kwargs.get("""base_path"""	)      ,   )	)
      else:
         builders.append(
             builder_cls(
                 config_name=snake_case      ,   data_dir=self._data_dir      ,   beam_options=snake_case      ,   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=snake_case      ,   )
         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:
         lowercase    :			List[str]  =       os.path.join(builder_cls.get_imported_module_dir()      ,   config.DATASETDICT_INFOS_FILENAME	)

         lowercase    :			Union[str, Any]  =       Path(snake_case	).name + """.py"""

         lowercase    :			Any  =       os.path.join(snake_case      ,   snake_case	)
         if os.path.isfile(snake_case	):
            lowercase    :			Optional[Any]  =       os.path.dirname(snake_case	)
         elif os.path.isfile(snake_case	):
            lowercase    :			List[Any]  =       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
         lowercase    :			List[str]  =       os.path.join(snake_case      ,   config.DATASETDICT_INFOS_FILENAME	)
         copyfile(snake_case      ,   snake_case	)
         print(f'''Dataset Infos file saved at {user_dataset_infos_path}'''	)









"""simple docstring"""
from typing import Optional, Union

from ...file_utils import TensorType
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy
class lowerCamelCase__  (    __UpperCamelCase				):
   __UpperCAmelCase        =					"""MarkupLMFeatureExtractor"""
   __UpperCAmelCase        =					("""MarkupLMTokenizer""", """MarkupLMTokenizerFast""")
   __UpperCAmelCase        =					True



   def __call__(       self      ,   snake_case=None      ,   snake_case=None      ,   snake_case=None      ,   snake_case=None      ,   snake_case=None      ,   snake_case = True      ,   snake_case = False      ,   snake_case = None      ,   snake_case = None      ,   snake_case = 0      ,   snake_case = None      ,   snake_case = None      ,   snake_case = None      ,   snake_case = False      ,   snake_case = False      ,   snake_case = False      ,   snake_case = False      ,   snake_case = True      ,   snake_case = None      ,   **snake_case      ,   ) ->    BatchEncoding:







      """simple docstring"""
      # first, create nodes and xpaths
      if self.parse_html:
         if html_strings is None:
            raise ValueError("""Make sure to pass HTML strings in case `parse_html` is set to `True`"""	)

         if nodes is not None or xpaths is not None or node_labels is not None:
            raise ValueError(
                """Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`"""	)

         lowercase    :			List[Any]  =       self.feature_extractor(snake_case	)
         lowercase    :			Union[str, Any]  =       features["""nodes"""]
         lowercase    :			List[Any]  =       features["""xpaths"""]
      else:
         if html_strings is not None:
            raise ValueError("""You have passed HTML strings but `parse_html` is set to `False`."""	)
         if nodes is None or xpaths is None:
            raise ValueError("""Make sure to pass nodes and xpaths in case `parse_html` is set to `False`"""	)

        # # second, apply the tokenizer
      if questions is not None and self.parse_html:
         if isinstance(snake_case      ,   snake_case	):
            lowercase    :			Dict  =       [questions]  # add batch dimension (as the feature extractor always adds a batch dimension)

      lowercase    :			Dict  =       self.tokenizer(
          text=questions if questions is not None else nodes      ,   text_pair=nodes if questions is not None else None      ,   xpaths=snake_case      ,   node_labels=snake_case      ,   add_special_tokens=snake_case      ,   padding=snake_case      ,   truncation=snake_case      ,   max_length=snake_case      ,   stride=snake_case      ,   pad_to_multiple_of=snake_case      ,   return_token_type_ids=snake_case      ,   return_attention_mask=snake_case      ,   return_overflowing_tokens=snake_case      ,   return_special_tokens_mask=snake_case      ,   return_offsets_mapping=snake_case      ,   return_length=snake_case      ,   verbose=snake_case      ,   return_tensors=snake_case      ,   **snake_case      ,   )

      return encoded_inputs



   def    _UpperCAmelCase	(       self      ,   *snake_case      ,   **snake_case	) ->    Optional[Any]:







      """simple docstring"""
      return self.tokenizer.batch_decode(*snake_case      ,   **snake_case	)



   def    _UpperCAmelCase	(       self      ,   *snake_case      ,   **snake_case	) ->    Tuple:







      """simple docstring"""
      return self.tokenizer.decode(*snake_case      ,   **snake_case	)





   @property
   def    _UpperCAmelCase	(       self	) ->    Dict:







      """simple docstring"""
      lowercase    :			Any  =       self.tokenizer.model_input_names
      return tokenizer_input_names


