


'''simple docstring'''





from __future__ import annotations

import unittest
import warnings

from transformers import AutoTokenizer, MarianConfig, MarianTokenizer, TranslationPipeline, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import TFAutoModelForSeqaSeqLM, TFMarianModel, TFMarianMTModel
@require_tf
class 	a__				:





			'''simple docstring'''

			A	:							List[Any]							= MarianConfig
			A	:							Tuple							= {}
			A	:							Optional[Any]							= '''gelu'''
			def __init__(     self       : str ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : Tuple=13 ,						lowerCAmelCase_       : Optional[Any]=7 ,						lowerCAmelCase_       : Optional[Any]=True ,						lowerCAmelCase_       : Dict=False ,						lowerCAmelCase_       : Optional[int]=99 ,						lowerCAmelCase_       : List[str]=32 ,						lowerCAmelCase_       : int=2 ,						lowerCAmelCase_       : Tuple=4 ,						lowerCAmelCase_       : Any=37 ,						lowerCAmelCase_       : List[Any]=0.1 ,						lowerCAmelCase_       : Tuple=0.1 ,						lowerCAmelCase_       : Tuple=20 ,						lowerCAmelCase_       : Optional[int]=2 ,						lowerCAmelCase_       : Optional[Any]=1 ,						lowerCAmelCase_       : Optional[Any]=0 ,						)			->		Optional[int]:
						__A=  parent
						__A=  batch_size
						__A=  seq_length
						__A=  is_training
						__A=  use_labels
						__A=  vocab_size
						__A=  hidden_size
						__A=  num_hidden_layers
						__A=  num_attention_heads
						__A=  intermediate_size

						__A=  hidden_dropout_prob
						__A=  attention_probs_dropout_prob
						__A=  max_position_embeddings
						__A=  eos_token_id
						__A=  pad_token_id
						__A=  bos_token_id
			def 				lowerCAmelCase    (     self       : List[Any]  )			->		Optional[Any]:
						__A=  ids_tensor([self.batch_size, self.seq_length - 1] ,						self.vocab_size  )
						__A=  tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size  ) ,						1  )
						__A=  tf.concat([input_ids, eos_tensor] ,						axis=1  )

						__A=  ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size  )

						__A=  self.config_cls(
						    vocab_size=self.vocab_size ,						d_model=self.hidden_size ,						encoder_layers=self.num_hidden_layers ,						decoder_layers=self.num_hidden_layers ,						encoder_attention_heads=self.num_attention_heads ,						decoder_attention_heads=self.num_attention_heads ,						encoder_ffn_dim=self.intermediate_size ,						decoder_ffn_dim=self.intermediate_size ,						dropout=self.hidden_dropout_prob ,						attention_dropout=self.attention_probs_dropout_prob ,						max_position_embeddings=self.max_position_embeddings ,						eos_token_ids=[2] ,						bos_token_id=self.bos_token_id ,						pad_token_id=self.pad_token_id ,						decoder_start_token_id=self.pad_token_id ,						**self.config_updates ,						)
						__A=  prepare_marian_inputs_dict(lowercase_ ,						lowercase_ ,						lowercase_  )
						return config, inputs_dict

			def 				lowerCAmelCase    (     self       : List[Any] ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : List[str]  )			->		List[Any]:
						__A=  TFMarianModel(config=lowercase_  ).get_decoder()
						__A=  inputs_dict['''input_ids''']

						__A=  input_ids[:1, :]
						__A=  inputs_dict['''attention_mask'''][:1, :]
						__A=  inputs_dict['''head_mask''']
						__A=  1

						# first forward pass
						__A=  model(lowercase_ ,						attention_mask=lowercase_ ,						head_mask=lowercase_ ,						use_cache=lowercase_  )

						__A=  outputs.to_tuple()

						# create hypothetical next token and extent to next_input_ids
						__A=  ids_tensor((self.batch_size, 3) ,						config.vocab_size  )
						__A=  tf.cast(ids_tensor((self.batch_size, 3) ,						2  ) ,						tf.inta  )

						# append to next input_ids and
						__A=  tf.concat([input_ids, next_tokens] ,						axis=-1  )
						__A=  tf.concat([attention_mask, next_attn_mask] ,						axis=-1  )

						__A=  model(lowercase_ ,						attention_mask=lowercase_  )[0]
						__A=  model(lowercase_ ,						attention_mask=lowercase_ ,						past_key_values=lowercase_  )[0]

						self.parent.assertEqual(next_tokens.shape[1] ,						output_from_past.shape[1]  )

						# select random slice
						__A=  int(ids_tensor((1,) ,						output_from_past.shape[-1]  )  )
						__A=  output_from_no_past[:, -3:, random_slice_idx]
						__A=  output_from_past[:, :, random_slice_idx]

						# test that outputs are equal for slice
						tf.debugging.assert_near(lowercase_ ,						lowercase_ ,						rtol=1E-3  )






def 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   List[Any],_SCREAMING_SNAKE_CASE				:   Tuple,_SCREAMING_SNAKE_CASE				:   Tuple,_SCREAMING_SNAKE_CASE				:   Optional[int]=None,_SCREAMING_SNAKE_CASE				:   str=None,_SCREAMING_SNAKE_CASE				:   Optional[Any]=None,_SCREAMING_SNAKE_CASE				:   str=None,_SCREAMING_SNAKE_CASE				:   Tuple=None,):






			"""simple docstring"""




			if attention_mask is None:
						__A=  tf.cast(tf.math.not_equal(lowercase_,config.pad_token_id   ),tf.inta   )
			if decoder_attention_mask is None:
						__A=  tf.concat(
						    [
						        tf.ones(decoder_input_ids[:, :1].shape,dtype=tf.inta   ),
						        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],config.pad_token_id   ),tf.inta   ),
						    ],axis=-1,)
			if head_mask is None:
						__A=  tf.ones((config.encoder_layers, config.encoder_attention_heads)   )
			if decoder_head_mask is None:
						__A=  tf.ones((config.decoder_layers, config.decoder_attention_heads)   )
			if cross_attn_head_mask is None:
						__A=  tf.ones((config.decoder_layers, config.decoder_attention_heads)   )
			return {
			    "input_ids": input_ids,
			    "decoder_input_ids": decoder_input_ids,
			    "attention_mask": attention_mask,
			    "decoder_attention_mask": decoder_attention_mask,
			    "head_mask": head_mask,
			    "decoder_head_mask": decoder_head_mask,
			    "cross_attn_head_mask": cross_attn_head_mask,
			}
@require_tf
class 	a__				(				__UpperCAmelCase			,     __UpperCAmelCase			,     unittest.TestCase      ):





			'''simple docstring'''

			A	:							Any							= (TFMarianMTModel, TFMarianModel) if is_tf_available() else ()
			A	:							Optional[Any]							= (TFMarianMTModel,) if is_tf_available() else ()
			A	:							List[Any]							= (
			    {
			        '''conversational''': TFMarianMTModel,
			        '''feature-extraction''': TFMarianModel,
			        '''summarization''': TFMarianMTModel,
			        '''text2text-generation''': TFMarianMTModel,
			        '''translation''': TFMarianMTModel,
			    }
			    if is_tf_available()
			    else {}
			)
			A	:							Union[str, Any]							= True
			A	:							str							= False
			A	:							Optional[Any]							= False
			def 				lowerCAmelCase    (     self       : Dict  )			->		List[str]:
						__A=  TFMarianModelTester(self  )
						__A=  ConfigTester(self ,						config_class=lowercase_  )
			def 				lowerCAmelCase    (     self       : Optional[Any]  )			->		Any:
						self.config_tester.run_common_tests()

			def 				lowerCAmelCase    (     self       : str  )			->		Any:
						__A=  self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_decoder_model_past_large_inputs(*lowercase_  )



@require_tf
class 	a__				(				unittest.TestCase      ):





			'''simple docstring'''

			A	:							Any							= 1000  # show more chars for failing integration tests
			@classmethod
			def 				lowerCAmelCase    (     cls       : List[Any]  )			->		None:
						__A=  F"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
						return cls
			@cached_property
			def 				lowerCAmelCase    (     self       : Union[str, Any]  )			->		MarianTokenizer:
						return AutoTokenizer.from_pretrained(self.model_name  )
			@property
			def 				lowerCAmelCase    (     self       : int  )			->		int:
						return self.tokenizer.eos_token_id
			@cached_property
			def 				lowerCAmelCase    (     self       : str  )			->		List[str]:
						warnings.simplefilter('error'  )
						__A=  TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name  )
						assert isinstance(lowercase_ ,						lowercase_  )
						__A=  model.config
						self.assertListEqual(c.bad_words_ids ,						[[c.pad_token_id]]  )
						self.assertEqual(c.max_length ,						512  )
						self.assertEqual(c.decoder_start_token_id ,						c.pad_token_id  )
						return model
			def 				lowerCAmelCase    (     self       : Any ,						**lowerCAmelCase_       : List[str]  )			->		List[Any]:
						__A=  self.translate_src_text(**lowercase_  )
						self.assertListEqual(self.expected_text ,						lowercase_  )

			def 				lowerCAmelCase    (     self       : int ,						**lowerCAmelCase_       : Union[str, Any]  )			->		int:
						__A=  self.tokenizer(self.src_text ,						**lowercase_ ,						padding=lowercase_ ,						return_tensors='tf'  )
						__A=  self.model.generate(
						    model_inputs.input_ids ,						attention_mask=model_inputs.attention_mask ,						num_beams=2 ,						max_length=128  )
						__A=  self.tokenizer.batch_decode(generated_ids.numpy() ,						skip_special_tokens=lowercase_  )
						return generated_words



@require_sentencepiece
@require_tokenizers
@require_tf
class 	a__				(				__UpperCAmelCase      ):





			'''simple docstring'''

			A	:							Dict							= '''mt'''
			A	:							List[Any]							= '''en'''
			A	:							str							= ['''Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.''']
			A	:							int							= ['''Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.''']
			@unittest.skip('Skipping until #12647 is resolved.'  )
			@slow
			def 				lowerCAmelCase    (     self       : Optional[Any]  )			->		str:
						self._assert_generated_batch_equal_expected()



@require_sentencepiece
@require_tokenizers
@require_tf
class 	a__				(				__UpperCAmelCase      ):





			'''simple docstring'''

			A	:							List[Any]							= '''en'''
			A	:							List[Any]							= '''zh'''
			A	:							str							= ['''My name is Wolfgang and I live in Berlin''']
			A	:							str							= ['''我叫沃尔夫冈 我住在柏林''']
			@unittest.skip('Skipping until #12647 is resolved.'  )
			@slow
			def 				lowerCAmelCase    (     self       : Optional[int]  )			->		Any:
						self._assert_generated_batch_equal_expected()



@require_sentencepiece
@require_tokenizers
@require_tf
class 	a__				(				__UpperCAmelCase      ):





			'''simple docstring'''

			A	:							List[str]							= '''en'''
			A	:							int							= '''ROMANCE'''
			A	:							str							= [
			    '''>>fr<< Don\'t spend so much time watching TV.''',
			    '''>>pt<< Your message has been sent.''',
			    '''>>es<< He\'s two years older than me.''',
			]
			A	:							Tuple							= [
			    '''Ne passez pas autant de temps à regarder la télé.''',
			    '''A sua mensagem foi enviada.''',
			    '''Es dos años más viejo que yo.''',
			]
			@unittest.skip('Skipping until #12647 is resolved.'  )
			@slow
			def 				lowerCAmelCase    (     self       : List[str]  )			->		Union[str, Any]:
						self._assert_generated_batch_equal_expected()

			@unittest.skip('Skipping until #12647 is resolved.'  )
			@slow
			def 				lowerCAmelCase    (     self       : Tuple  )			->		Tuple:
						__A=  TranslationPipeline(self.model ,						self.tokenizer ,						framework='tf'  )
						__A=  pipeline(self.src_text  )
						self.assertEqual(self.expected_text ,						[x['translation_text'] for x in output]  )







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



