






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 				_UpperCAmelCase :

				"""simple docstring"""




				def __init__(					self						:   Dict,  lowerCamelCase						:   str,  lowerCamelCase						:   List[str]=13,  lowerCamelCase						:   Union[str, Any]=7,  lowerCamelCase						:   Any=True,  lowerCamelCase						:   str=True,  lowerCamelCase						:   int=True,  lowerCamelCase						:   Optional[Any]=99,  lowerCamelCase						:   Optional[int]=32,  lowerCamelCase						:   int=5,  lowerCamelCase						:   List[Any]=4,  lowerCamelCase						:   Optional[Any]=37,  lowerCamelCase						:   Optional[Any]="gelu",  lowerCamelCase						:   Any=0.1,  lowerCamelCase						:   Union[str, Any]=0.1,  lowerCamelCase						:   Any=512,  lowerCamelCase						:   Union[str, Any]=16,  lowerCamelCase						:   List[Any]=2,  lowerCamelCase						:   Dict=0.02,  lowerCamelCase						:   int=3,  lowerCamelCase						:   Optional[Any]=4,  lowerCamelCase						:   Optional[Any]=None,  ):

								'''simple docstring'''
								lowercase__       			=      parent
								lowercase__       			=      batch_size
								lowercase__       			=      seq_length
								lowercase__       			=      is_training
								lowercase__       			=      use_input_mask
								lowercase__       			=      use_labels
								lowercase__       			=      vocab_size
								lowercase__       			=      hidden_size
								lowercase__       			=      num_hidden_layers
								lowercase__       			=      num_attention_heads
								lowercase__       			=      intermediate_size
								lowercase__       			=      hidden_act
								lowercase__       			=      hidden_dropout_prob
								lowercase__       			=      attention_probs_dropout_prob
								lowercase__       			=      max_position_embeddings
								lowercase__       			=      type_vocab_size
								lowercase__       			=      type_sequence_label_size
								lowercase__       			=      initializer_range
								lowercase__       			=      num_labels
								lowercase__       			=      num_choices
								lowercase__       			=      scope




				def     lowercase__       (					self						:   List[str]  ):

								'''simple docstring'''
								lowercase__       			=      ids_tensor([self.batch_size, self.seq_length],  self.vocab_size  )

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

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

								lowercase__       			=      self.get_config()

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




				def     lowercase__       (					self						:   Union[str, Any]  ):

								'''simple docstring'''
								lowercase__       			=      ids_tensor([self.batch_size, self.seq_length],  self.vocab_size  )

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

								return config, input_ids, input_mask




				def     lowercase__       (					self						:   Optional[Any]  ):

								'''simple docstring'''
								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     lowercase__       (					self						:   str,  lowerCamelCase						:   Optional[int],  lowerCamelCase						:   List[Any],  lowerCamelCase						:   str,  lowerCamelCase						:   int,  lowerCamelCase						:   List[Any],  lowerCamelCase						:   List[Any]  ):

								'''simple docstring'''
								lowercase__       			=      ErnieMModel(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__       			=      model(lowerCamelCase,  return_dict=lowerCamelCase  )
								self.parent.assertEqual(result.last_hidden_state.shape,  (self.batch_size, self.seq_length, self.hidden_size)  )




				def     lowercase__       (					self						:   int,  lowerCamelCase						:   int,  lowerCamelCase						:   Any,  lowerCamelCase						:   Any,  lowerCamelCase						:   Optional[int],  lowerCamelCase						:   Union[str, Any],  lowerCamelCase						:   List[Any]  ):

								'''simple docstring'''
								lowercase__       			=      ErnieMForQuestionAnswering(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__       			=      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     lowercase__       (					self						:   int,  lowerCamelCase						:   List[Any],  lowerCamelCase						:   str,  lowerCamelCase						:   Any,  lowerCamelCase						:   Dict,  lowerCamelCase						:   List[Any],  lowerCamelCase						:   Union[str, Any]  ):

								'''simple docstring'''
								lowercase__       			=      ErnieMForInformationExtraction(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__       			=      torch.ones_like(lowerCamelCase,  dtype=torch.floataa  )
								lowercase__       			=      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     lowercase__       (					self						:   List[str],  lowerCamelCase						:   int,  lowerCamelCase						:   Dict,  lowerCamelCase						:   Dict,  lowerCamelCase						:   Tuple,  lowerCamelCase						:   Dict,  lowerCamelCase						:   Optional[Any]  ):

								'''simple docstring'''
								lowercase__       			=      self.num_labels
								lowercase__       			=      ErnieMForSequenceClassification(lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__       			=      model(lowerCamelCase,  attention_mask=lowerCamelCase,  labels=lowerCamelCase  )
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_labels)  )




				def     lowercase__       (					self						:   List[Any],  lowerCamelCase						:   Union[str, Any],  lowerCamelCase						:   List[str],  lowerCamelCase						:   Dict,  lowerCamelCase						:   List[Any],  lowerCamelCase						:   Tuple,  lowerCamelCase						:   Dict  ):

								'''simple docstring'''
								lowercase__       			=      self.num_labels
								lowercase__       			=      ErnieMForTokenClassification(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								input_ids.to(lowerCamelCase  )
								input_mask.to(lowerCamelCase  )
								token_labels.to(lowerCamelCase  )

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

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




				def     lowercase__       (					self						:   Optional[int],  lowerCamelCase						:   int,  lowerCamelCase						:   Optional[int],  lowerCamelCase						:   int,  lowerCamelCase						:   List[Any],  lowerCamelCase						:   Tuple,  lowerCamelCase						:   Optional[Any]  ):

								'''simple docstring'''
								lowercase__       			=      self.num_choices
								lowercase__       			=      ErnieMForMultipleChoice(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__       			=      input_ids.unsqueeze(1  ).expand(-1,  self.num_choices,  -1  ).contiguous()
								lowercase__       			=      input_mask.unsqueeze(1  ).expand(-1,  self.num_choices,  -1  ).contiguous()
								lowercase__       			=      model(
								    lowerCamelCase,  attention_mask=lowerCamelCase,  labels=lowerCamelCase,  )
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_choices)  )




				def     lowercase__       (					self						:   str  ):

								'''simple docstring'''
								lowercase__       			=      self.prepare_config_and_inputs()
								(
								    (
								    lowercase__   
								)			,						(
								    lowercase__   
								)			,						(
								    lowercase__   
								)			,						(
								    lowercase__   
								)			,						(
								    lowercase__   
								)			,						(
								    lowercase__   
								)			,						   
								)       			=      config_and_inputs
								lowercase__       			=      {'''input_ids''': input_ids, '''attention_mask''': input_mask}
								return config, inputs_dict



@require_torch
class 				_UpperCAmelCase (	A__		,A__		,unittest.TestCase     ):

				"""simple docstring"""




				lowercase__    							=	(
				    (
				        ErnieMModel,
				        ErnieMForMultipleChoice,
				        ErnieMForQuestionAnswering,
				        ErnieMForSequenceClassification,
				        ErnieMForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				lowercase__    							=	()
				lowercase__    							=	(
				    {
				        'feature-extraction': ErnieMModel,
				        'question-answering': ErnieMForQuestionAnswering,
				        'text-classification': ErnieMForSequenceClassification,
				        'token-classification': ErnieMForTokenClassification,
				        'zero-shot': ErnieMForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				lowercase__    							=	False




				def     lowercase__       (					self						:   List[str],  lowerCamelCase						:   Tuple,  lowerCamelCase						:   List[str],  lowerCamelCase						:   Optional[Any],  lowerCamelCase						:   List[str],  lowerCamelCase						:   Tuple  ):

								'''simple docstring'''



								if pipeline_test_casse_name == "QAPipelineTests":
												return True

								return False




				def     lowercase__       (					self						:   Tuple  ):

								'''simple docstring'''
								lowercase__       			=      ErnieMModelTester(self  )
								lowercase__       			=      ConfigTester(self,  config_class=lowerCamelCase,  hidden_size=37  )




				def     lowercase__       (					self						:   Union[str, Any]  ):

								'''simple docstring'''
								self.config_tester.run_common_tests()




				def     lowercase__       (					self						:   int  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase  )




				def     lowercase__       (					self						:   Optional[int]  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
												lowercase__       			=      type
												self.model_tester.create_and_check_model(*lowerCamelCase  )




				def     lowercase__       (					self						:   Any  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase  )




				def     lowercase__       (					self						:   List[str]  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*lowerCamelCase  )




				def     lowercase__       (					self						:   List[Any]  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase  )




				def     lowercase__       (					self						:   Tuple  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_information_extraction(*lowerCamelCase  )




				def     lowercase__       (					self						:   Optional[int]  ):

								'''simple docstring'''
								lowercase__       			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*lowerCamelCase  )




				@slow
				def     lowercase__       (					self						:   List[str]  ):

								'''simple docstring'''



								for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												lowercase__       			=      ErnieMModel.from_pretrained(lowerCamelCase  )
												self.assertIsNotNone(lowerCamelCase  )



@require_torch
class 				_UpperCAmelCase (	unittest.TestCase     ):

				"""simple docstring"""




				@slow
				def     lowercase__       (					self						:   str  ):

								'''simple docstring'''
								lowercase__       			=      ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''  )
								model.eval()
								lowercase__       			=      torch.tensor([[0, 1, 2, 3, 4, 5]]  )
								lowercase__       			=      model(lowerCamelCase  )[0]

								# TODO Replace vocab size
								lowercase__       			=      768

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

								lowercase__       			=      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  )  )







import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Image
from datasets.packaged_modules.text.text import Text

from ..utils import require_pil






@pytest.fixture
def   a      (						lowerCamelCase_    ):






				'''simple docstring'''
				lowercase__       			=      tmp_path / '''text.txt'''
				lowercase__       			=      textwrap.dedent(
				    '''\
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Second paragraph:
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        '''    )
				with open(lowerCamelCase_		,       '''w'''		,       encoding='''utf-8'''    ) as f:
								f.write(lowerCamelCase_    )
				return str(lowerCamelCase_    )






@pytest.fixture
def   a      (						lowerCamelCase_		,       lowerCamelCase_    ):






				'''simple docstring'''
				lowercase__       			=      tmp_path / '''text_with_image.txt'''
				with open(lowerCamelCase_		,       '''w'''		,       encoding='''utf-8'''    ) as f:
								f.write(lowerCamelCase_    )
				return str(lowerCamelCase_    )






@pytest.mark.parametrize('''keep_linebreaks'''		,       [True, False]    )
def   a      (						lowerCamelCase_		,       lowerCamelCase_    ):






				'''simple docstring'''
				with open(lowerCamelCase_		,       encoding='''utf-8'''    ) as f:
								lowercase__       			=      f.read().splitlines(keepends=lowerCamelCase_    )
				lowercase__       			=      Text(keep_linebreaks=lowerCamelCase_		,       encoding='''utf-8'''    )
				lowercase__       			=      text._generate_tables([[text_file]]    )
				lowercase__       			=      pa.concat_tables([table for _, table in generator]    ).to_pydict()['''text''']
				assert generated_content == expected_content






@require_pil
def   a      (						lowerCamelCase_    ):






				'''simple docstring'''
				with open(lowerCamelCase_		,       encoding='''utf-8'''    ) as f:
								lowercase__       			=      f.read().splitlines()[0]
				lowercase__       			=      Text(encoding='''utf-8'''		,       features=Features({'''image''': Image()}    )    )
				lowercase__       			=      text._generate_tables([[text_file_with_image]]    )
				lowercase__       			=      pa.concat_tables([table for _, table in generator]    )
				assert pa_table.schema.field('''image'''    ).type == Image()()
				lowercase__       			=      pa_table.to_pydict()['''image''']
				assert generated_content == [{"path": image_file, "bytes": None}]






@pytest.mark.parametrize('''sample_by'''		,       ['''line''', '''paragraph''', '''document''']    )
def   a      (						lowerCamelCase_		,       lowerCamelCase_    ):






				'''simple docstring'''
				with open(lowerCamelCase_		,       encoding='''utf-8'''    ) as f:
								lowercase__       			=      f.read()
				if sample_by == "line":
								lowercase__       			=      expected_content.splitlines()
				elif sample_by == "paragraph":
								lowercase__       			=      expected_content.split('''\n\n'''    )
				elif sample_by == "document":
								lowercase__       			=      [expected_content]
				lowercase__       			=      Text(sample_by=lowerCamelCase_		,       encoding='''utf-8'''		,       chunksize=100    )
				lowercase__       			=      text._generate_tables([[text_file]]    )
				lowercase__       			=      pa.concat_tables([table for _, table in generator]    ).to_pydict()['''text''']
				assert generated_content == expected_content




