code: 
  
  
  '''simple docstring'''
  
  
  
  
  
  import unittest
  
  from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
  from transformers.models.auto import get_values
  from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
  
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_common import ModelTesterMixin, ids_tensor
  from ...test_pipeline_mixin import PipelineTesterMixin
  
  
  if is_torch_available():
  					import torch
  
  					from transformers import (
  					    MODEL_FOR_PRETRAINING_MAPPING,
  					    FunnelBaseModel,
  					    FunnelForMaskedLM,
  					    FunnelForMultipleChoice,
  					    FunnelForPreTraining,
  					    FunnelForQuestionAnswering,
  					    FunnelForSequenceClassification,
  					    FunnelForTokenClassification,
  					    FunnelModel,
  					)
  class 	a__				:
  
  
  
  
  
  			'''simple docstring'''
  
  			def __init__(     self       : Tuple ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : List[str]=13 ,						lowerCAmelCase_       : int=7 ,						lowerCAmelCase_       : Union[str, Any]=True ,						lowerCAmelCase_       : Union[str, Any]=True ,						lowerCAmelCase_       : Dict=True ,						lowerCAmelCase_       : Optional[Any]=True ,						lowerCAmelCase_       : List[str]=99 ,						lowerCAmelCase_       : Dict=[1, 1, 2] ,						lowerCAmelCase_       : Optional[int]=1 ,						lowerCAmelCase_       : List[str]=32 ,						lowerCAmelCase_       : Optional[int]=4 ,						lowerCAmelCase_       : Dict=8 ,						lowerCAmelCase_       : Tuple=37 ,						lowerCAmelCase_       : Union[str, Any]="gelu_new" ,						lowerCAmelCase_       : int=0.1 ,						lowerCAmelCase_       : List[str]=0.1 ,						lowerCAmelCase_       : Dict=0.0 ,						lowerCAmelCase_       : str=512 ,						lowerCAmelCase_       : int=3 ,						lowerCAmelCase_       : Optional[int]=0.02 ,						lowerCAmelCase_       : Dict=3 ,						lowerCAmelCase_       : Union[str, Any]=4 ,						lowerCAmelCase_       : Optional[int]=None ,						lowerCAmelCase_       : List[str]=False ,						)			->		int:
  						__A=  parent
  						__A=  batch_size
  						__A=  seq_length
  						__A=  is_training
  						__A=  use_input_mask
  						__A=  use_token_type_ids
  						__A=  use_labels
  						__A=  vocab_size
  						__A=  block_sizes
  						__A=  num_decoder_layers
  						__A=  d_model
  						__A=  n_head
  						__A=  d_head
  						__A=  d_inner
  						__A=  hidden_act
  						__A=  hidden_dropout
  						__A=  attention_dropout
  						__A=  activation_dropout
  						__A=  max_position_embeddings
  						__A=  type_vocab_size
  						__A=  2
  						__A=  num_labels
  						__A=  num_choices
  						__A=  scope
  						__A=  initializer_std
  
  						# Used in the tests to check the size of the first attention layer
  						__A=  n_head
  						# Used in the tests to check the size of the first hidden state
  						__A=  self.d_model
  						# Used in the tests to check the number of output hidden states/attentions
  						__A=  sum(self.block_sizes  ) + (0 if base else self.num_decoder_layers)
  						# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
  						# the last hidden state of the first block (which is the first hidden state of the decoder).
  						if not base:
  									__A=  self.num_hidden_layers + 2
  			def 				lowerCAmelCase    (     self       : List[str]  )			->		List[str]:
  						__A=  ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size  )
  
  						__A=  None
  						if self.use_input_mask:
  									__A=  ids_tensor([self.batch_size, self.seq_length] ,						vocab_size=2  )
  
  						__A=  None
  						if self.use_token_type_ids:
  									__A=  ids_tensor([self.batch_size, self.seq_length] ,						self.type_vocab_size  )
  
  						__A=  None
  						__A=  None
  						__A=  None
  						if self.use_labels:
  									__A=  ids_tensor([self.batch_size] ,						self.type_sequence_label_size  )
  									__A=  ids_tensor([self.batch_size, self.seq_length] ,						self.num_labels  )
  									__A=  ids_tensor([self.batch_size] ,						self.num_choices  )
  									__A=  ids_tensor([self.batch_size, self.seq_length] ,						1  )
  
  						__A=  self.get_config()
  
  						return (
  						    config,
  						    input_ids,
  						    token_type_ids,
  						    input_mask,
  						    sequence_labels,
  						    token_labels,
  						    choice_labels,
  						    fake_token_labels,
  						)
  			def 				lowerCAmelCase    (     self       : List[Any]  )			->		List[Any]:
  						return FunnelConfig(
  						    vocab_size=self.vocab_size ,						block_sizes=self.block_sizes ,						num_decoder_layers=self.num_decoder_layers ,						d_model=self.d_model ,						n_head=self.n_head ,						d_head=self.d_head ,						d_inner=self.d_inner ,						hidden_act=self.hidden_act ,						hidden_dropout=self.hidden_dropout ,						attention_dropout=self.attention_dropout ,						activation_dropout=self.activation_dropout ,						max_position_embeddings=self.max_position_embeddings ,						type_vocab_size=self.type_vocab_size ,						initializer_std=self.initializer_std ,						)
  			def 				lowerCAmelCase    (     self       : Dict ,						lowerCAmelCase_       : Optional[Any] ,						lowerCAmelCase_       : Optional[Any] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : str ,						)			->		Union[str, Any]:
  						__A=  FunnelModel(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )
  						__A=  model(_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.d_model)  )
  
  						__A=  False
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.d_model)  )
  
  						__A=  False
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.d_model)  )
  			def 				lowerCAmelCase    (     self       : Optional[Any] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : Optional[int] ,						)			->		Dict:
  						__A=  FunnelBaseModel(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )
  						__A=  model(_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, 2, self.d_model)  )
  
  						__A=  False
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, 3, self.d_model)  )
  
  						__A=  False
  						__A=  model(_lowerCAmelCase  )
  						self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, 2, self.d_model)  )
  			def 				lowerCAmelCase    (     self       : Optional[Any] ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : Dict ,						lowerCAmelCase_       : Dict ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : int ,						)			->		str:
  						__A=  self.num_labels
  						__A=  FunnelForPreTraining(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase ,						labels=_lowerCAmelCase  )
  						self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length)  )
  			def 				lowerCAmelCase    (     self       : Tuple ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : Optional[Any] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : Any ,						)			->		List[Any]:
  						__A=  FunnelForMaskedLM(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase ,						labels=_lowerCAmelCase  )
  						self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.vocab_size)  )
  			def 				lowerCAmelCase    (     self       : str ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : Dict ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : List[str] ,						lowerCAmelCase_       : List[str] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : List[Any] ,						)			->		List[str]:
  						__A=  self.num_labels
  						__A=  FunnelForSequenceClassification(_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase ,						labels=_lowerCAmelCase  )
  						self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_labels)  )
  			def 				lowerCAmelCase    (     self       : Dict ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : List[str] ,						)			->		List[Any]:
  						__A=  self.num_choices
  						__A=  FunnelForMultipleChoice(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  input_ids.unsqueeze(1  ).expand(-1 ,						self.num_choices ,						-1  ).contiguous()
  						__A=  token_type_ids.unsqueeze(1  ).expand(-1 ,						self.num_choices ,						-1  ).contiguous()
  						__A=  input_mask.unsqueeze(1  ).expand(-1 ,						self.num_choices ,						-1  ).contiguous()
  						__A=  model(
  						    _lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase ,						labels=_lowerCAmelCase ,						)
  						self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_choices)  )
  			def 				lowerCAmelCase    (     self       : Any ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : Union[str, Any] ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : List[str] ,						lowerCAmelCase_       : Union[str, Any] ,						)			->		str:
  						__A=  self.num_labels
  						__A=  FunnelForTokenClassification(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase ,						labels=_lowerCAmelCase  )
  						self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.num_labels)  )
  			def 				lowerCAmelCase    (     self       : str ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : List[str] ,						lowerCAmelCase_       : Any ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : Optional[Any] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : Dict ,						)			->		str:
  						__A=  FunnelForQuestionAnswering(config=_lowerCAmelCase  )
  						model.to(_lowerCAmelCase  )
  						model.eval()
  						__A=  model(
  						    _lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_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       : Dict  )			->		str:
  						__A=  self.prepare_config_and_inputs()
  						(
  						    (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),  (
  						    __A    
  						),      
  						)=  config_and_inputs
  						__A=  {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
  						return config, inputs_dict
  
  
  
  @require_torch
  class 	a__				(				A__			,     A__			,     unittest.TestCase      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			A	:							Dict							= False
  			A	:							str							= False
  			A	:							str							= (
  			    (
  			        FunnelModel,
  			        FunnelForMaskedLM,
  			        FunnelForPreTraining,
  			        FunnelForQuestionAnswering,
  			        FunnelForTokenClassification,
  			    )
  			    if is_torch_available()
  			    else ()
  			)
  			A	:							Dict							= (
  			    {
  			        '''feature-extraction''': (FunnelBaseModel, FunnelModel),
  			        '''fill-mask''': FunnelForMaskedLM,
  			        '''question-answering''': FunnelForQuestionAnswering,
  			        '''text-classification''': FunnelForSequenceClassification,
  			        '''token-classification''': FunnelForTokenClassification,
  			        '''zero-shot''': FunnelForSequenceClassification,
  			    }
  			    if is_torch_available()
  			    else {}
  			)
  			def 				lowerCAmelCase    (     self       : Tuple ,						lowerCAmelCase_       : Optional[int] ,						lowerCAmelCase_       : List[Any] ,						lowerCAmelCase_       : str=False  )			->		Dict:
  						__A=  super()._prepare_for_class(_lowerCAmelCase ,						_lowerCAmelCase ,						return_labels=_lowerCAmelCase  )
  
  						if return_labels:
  									if model_class in get_values(_lowerCAmelCase  ):
  												__A=  torch.zeros(
  												    (self.model_tester.batch_size, self.model_tester.seq_length) ,						dtype=torch.long ,						device=_lowerCAmelCase  )
  						return inputs_dict
  			def 				lowerCAmelCase    (     self       : int  )			->		str:
  						__A=  FunnelModelTester(self  )
  						__A=  ConfigTester(self ,						config_class=_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : Tuple  )			->		List[Any]:
  						self.config_tester.run_common_tests()
  			def 				lowerCAmelCase    (     self       : Optional[Any]  )			->		Dict:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_model(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : Tuple  )			->		List[str]:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_pretraining(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : Optional[Any]  )			->		Union[str, Any]:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_masked_lm(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : Union[str, Any]  )			->		Dict:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_token_classification(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : List[str]  )			->		List[str]:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_question_answering(*_lowerCAmelCase  )
  
  			def 				lowerCAmelCase    (     self       : Dict ,						lowerCAmelCase_       : List[str]  )			->		Optional[Any]:
  						if hasattr(_lowerCAmelCase ,						'weight'  ) and module.weight is not None:
  									module.weight.data.fill_(3  )
  						if hasattr(_lowerCAmelCase ,						'bias'  ) and module.bias is not None:
  									module.bias.data.fill_(3  )
  
  						for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
  									if hasattr(_lowerCAmelCase ,						_lowerCAmelCase  ) and getattr(_lowerCAmelCase ,						_lowerCAmelCase  ) is not None:
  												__A=  getattr(_lowerCAmelCase ,						_lowerCAmelCase  )
  												weight.data.fill_(3  )
  
  
  
  @require_torch
  class 	a__				(				A__			,     unittest.TestCase      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			A	:							Optional[int]							= False
  			A	:							List[Any]							= False
  			A	:							Optional[Any]							= (
  			    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
  			)
  			def 				lowerCAmelCase    (     self       : str  )			->		List[Any]:
  						__A=  FunnelModelTester(self ,						base=_lowerCAmelCase  )
  						__A=  ConfigTester(self ,						config_class=_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : List[str]  )			->		Union[str, Any]:
  						self.config_tester.run_common_tests()
  			def 				lowerCAmelCase    (     self       : Tuple  )			->		str:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_base_model(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : List[str]  )			->		Optional[Any]:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_sequence_classification(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : Union[str, Any]  )			->		Tuple:
  						__A=  self.model_tester.prepare_config_and_inputs()
  						self.model_tester.create_and_check_for_multiple_choice(*_lowerCAmelCase  )
  			def 				lowerCAmelCase    (     self       : int  )			->		Union[str, Any]:
  						__A,  __A=  self.model_tester.prepare_config_and_inputs_for_common()
  						__A=  True
  
  						for model_class in self.all_model_classes:
  									if model_class.__name__ == "FunnelBaseModel":
  												continue
  									__A=  model_class(_lowerCAmelCase  )
  									model.to(_lowerCAmelCase  )
  									model.train()
  									__A=  self._prepare_for_class(_lowerCAmelCase ,						_lowerCAmelCase ,						return_labels=_lowerCAmelCase  )
  									__A=  model(**_lowerCAmelCase  ).loss
  									loss.backward()
  
  			def 				lowerCAmelCase    (     self       : Optional[int] ,						lowerCAmelCase_       : Union[str, Any]  )			->		List[Any]:
  						if hasattr(_lowerCAmelCase ,						'weight'  ) and module.weight is not None:
  									module.weight.data.fill_(3  )
  						if hasattr(_lowerCAmelCase ,						'bias'  ) and module.bias is not None:
  									module.bias.data.fill_(3  )
  
  						for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
  									if hasattr(_lowerCAmelCase ,						_lowerCAmelCase  ) and getattr(_lowerCAmelCase ,						_lowerCAmelCase  ) is not None:
  												__A=  getattr(_lowerCAmelCase ,						_lowerCAmelCase  )
  												weight.data.fill_(3  )
  
  
  
  @require_torch
  @require_sentencepiece
  @require_tokenizers
  class 	a__				(				unittest.TestCase      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			def 				lowerCAmelCase    (     self       : Optional[Any]  )			->		Tuple:
  						__A=  13
  						__A=  7
  						__A=  torch.arange(0 ,						batch_size * sequence_length  ).long().reshape(_lowerCAmelCase ,						_lowerCAmelCase  )
  						__A=  [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
  						__A=  torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]  )
  
  						__A=  FunnelModel.from_pretrained('sgugger/funnel-random-tiny'  )
  						__A=  model(_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )[0].abs()
  
  						__A=  torch.tensor(2_344.8_352  )
  						__A=  torch.tensor(0.80_52  )
  						self.assertTrue(torch.allclose(output.sum() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  						self.assertTrue(torch.allclose(output.mean() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  
  						__A=  torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]]  )
  						__A=  model(_lowerCAmelCase ,						attention_mask=_lowerCAmelCase ,						token_type_ids=_lowerCAmelCase  )[0].abs()
  
  						__A=  torch.tensor(2_343.8_425  )
  						__A=  torch.tensor(0.80_49  )
  						self.assertTrue(torch.allclose(output.sum() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  						self.assertTrue(torch.allclose(output.mean() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  
  			@slow
  			def 				lowerCAmelCase    (     self       : Optional[int]  )			->		str:
  						__A=  FunnelTokenizer.from_pretrained('huggingface/funnel-small'  )
  						__A=  FunnelModel.from_pretrained('huggingface/funnel-small'  )
  						__A=  tokenizer('Hello! I am the Funnel Transformer model.' ,						return_tensors='pt'  )
  						__A=  model(**_lowerCAmelCase  )[0]
  
  						__A=  torch.tensor(2_35.72_46  )
  						__A=  torch.tensor(0.02_56  )
  						self.assertTrue(torch.allclose(output.sum() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  						self.assertTrue(torch.allclose(output.mean() ,						_lowerCAmelCase ,						atol=1E-4  )  )
  
  
  
  
style_context: 
  
  
  '''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 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   Any,**_SCREAMING_SNAKE_CASE				:   Tuple   ):
  
  
  
  
  
  
  			"""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,**_SCREAMING_SNAKE_CASE,)
  
  
  
  
  
  
  class 	a__				(				a_      ):
  
  
  
  
  
  			'''simple docstring'''
  
  			@staticmethod
  			def 				lowerCAmelCase    (     lowerCAmelCase_       : ArgumentParser  )			->		Tuple:
  						__A=  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       : Any ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : str ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						lowerCAmelCase_       : bool ,						**lowerCAmelCase_       : Tuple ,						)			->		List[Any]:
  						__A=  dataset
  						__A=  name
  						__A=  cache_dir
  						__A=  beam_pipeline_options
  						__A=  data_dir
  						__A=  all_configs
  						__A=  save_infos
  						__A=  ignore_verifications
  						__A=  force_redownload
  						__A=  config_kwargs
  
  			def 				lowerCAmelCase    (     self       : Optional[int]  )			->		Optional[Any]:
  						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  )
  						__A,  __A=  self._dataset, self._name
  						__A=  dataset_module_factory(lowerCAmelCase_  )
  						__A=  import_main_class(dataset_module.module_path  )
  						__A=  []
  						if self._beam_pipeline_options:
  									__A=  beam.options.pipeline_options.PipelineOptions(
  									    flags=[F"""--{opt.strip()}""" for opt in self._beam_pipeline_options.split(','  ) if opt]  )
  						else:
  									__A=  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:
  									__A=  os.path.join(builder_cls.get_imported_module_dir() ,						config.DATASETDICT_INFOS_FILENAME  )
  
  									__A=  Path(lowerCAmelCase_  ).name + '.py'
  
  									__A=  os.path.join(lowerCAmelCase_ ,						lowerCAmelCase_  )
  									if os.path.isfile(lowerCAmelCase_  ):
  												__A=  os.path.dirname(lowerCAmelCase_  )
  									elif os.path.isfile(lowerCAmelCase_  ):
  												__A=  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
  									__A=  os.path.join(lowerCAmelCase_ ,						config.DATASETDICT_INFOS_FILENAME  )
  									copyfile(lowerCAmelCase_ ,						lowerCAmelCase_  )
  									print(F"""Dataset Infos file saved at {user_dataset_infos_path}"""  )
  
  
  
  