



import unittest

from transformers import MarkupLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property

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 (
	    MarkupLMForQuestionAnswering,
	    MarkupLMForSequenceClassification,
	    MarkupLMForTokenClassification,
	    MarkupLMModel,
	)

# TODO check dependencies
from transformers import MarkupLMFeatureExtractor, MarkupLMProcessor, MarkupLMTokenizer


class    _lowercase :
				'''simple docstring'''







				def __init__(			self  ,			snake_case__  ,			snake_case__=13  ,			snake_case__=7  ,			snake_case__=True  ,			snake_case__=True  ,			snake_case__=True  ,			snake_case__=True  ,			snake_case__=99  ,			snake_case__=32  ,			snake_case__=5  ,			snake_case__=4  ,			snake_case__=37  ,			snake_case__="gelu"  ,			snake_case__=0.1  ,			snake_case__=0.1  ,			snake_case__=512  ,			snake_case__=16  ,			snake_case__=2  ,			snake_case__=0.02  ,			snake_case__=3  ,			snake_case__=None  ,			snake_case__=20  ,			snake_case__=30  ,			snake_case__=2  ,			snake_case__=2  ,			snake_case__=10  ,			):

									'''simple docstring'''


									UpperCamelCase_			= parent
									UpperCamelCase_			= batch_size
									UpperCamelCase_			= seq_length
									UpperCamelCase_			= is_training
									UpperCamelCase_			= use_input_mask
									UpperCamelCase_			= use_token_type_ids
									UpperCamelCase_			= use_labels
									UpperCamelCase_			= vocab_size
									UpperCamelCase_			= hidden_size
									UpperCamelCase_			= num_hidden_layers
									UpperCamelCase_			= num_attention_heads
									UpperCamelCase_			= intermediate_size
									UpperCamelCase_			= hidden_act
									UpperCamelCase_			= hidden_dropout_prob
									UpperCamelCase_			= attention_probs_dropout_prob
									UpperCamelCase_			= max_position_embeddings
									UpperCamelCase_			= type_vocab_size
									UpperCamelCase_			= type_sequence_label_size
									UpperCamelCase_			= initializer_range
									UpperCamelCase_			= num_labels
									UpperCamelCase_			= scope
									UpperCamelCase_			= max_xpath_tag_unit_embeddings
									UpperCamelCase_			= max_xpath_subs_unit_embeddings
									UpperCamelCase_			= tag_pad_id
									UpperCamelCase_			= subs_pad_id
									UpperCamelCase_			= max_depth

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


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

									UpperCamelCase_			= ids_tensor(
									    [self.batch_size, self.seq_length, self.max_depth]  ,			self.max_xpath_tag_unit_embeddings     )

									UpperCamelCase_			= ids_tensor(
									    [self.batch_size, self.seq_length, self.max_depth]  ,			self.max_xpath_subs_unit_embeddings     )

									UpperCamelCase_			= None
									if self.use_input_mask:
														UpperCamelCase_			= ids_tensor([self.batch_size, self.seq_length]  ,			vocab_size=2     )

									UpperCamelCase_			= None
									if self.use_token_type_ids:
														UpperCamelCase_			= ids_tensor([self.batch_size, self.seq_length]  ,			self.type_vocab_size     )

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

									UpperCamelCase_			= self.get_config()

									return (
									    config,
									    input_ids,
									    xpath_tags_seq,
									    xpath_subs_seq,
									    token_type_ids,
									    input_mask,
									    sequence_labels,
									    token_labels,
									)

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									return MarkupLMConfig(
									    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  ,			max_xpath_tag_unit_embeddings=self.max_xpath_tag_unit_embeddings  ,			max_xpath_subs_unit_embeddings=self.max_xpath_subs_unit_embeddings  ,			tag_pad_id=self.tag_pad_id  ,			subs_pad_id=self.subs_pad_id  ,			max_depth=self.max_depth  ,			)

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			):

									'''simple docstring'''


									UpperCamelCase_			= MarkupLMModel(config=snake_case__     )
									model.to(snake_case__     )
									model.eval()
									print("Configs:"  ,			model.config.tag_pad_id  ,			model.config.subs_pad_id     )
									UpperCamelCase_			= model(snake_case__  ,			attention_mask=snake_case__  ,			token_type_ids=snake_case__     )
									UpperCamelCase_			= model(snake_case__  ,			token_type_ids=snake_case__     )
									UpperCamelCase_			= model(snake_case__     )
									self.parent.assertEqual(result.last_hidden_state.shape  ,			(self.batch_size, self.seq_length, self.hidden_size)     )
									self.parent.assertEqual(result.pooler_output.shape  ,			(self.batch_size, self.hidden_size)     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.num_labels
									UpperCamelCase_			= MarkupLMForSequenceClassification(snake_case__     )
									model.to(snake_case__     )
									model.eval()
									UpperCamelCase_			= model(
									    snake_case__  ,			xpath_tags_seq=snake_case__  ,			xpath_subs_seq=snake_case__  ,			attention_mask=snake_case__  ,			token_type_ids=snake_case__  ,			labels=snake_case__  ,			)
									self.parent.assertEqual(result.logits.shape  ,			(self.batch_size, self.num_labels)     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.num_labels
									UpperCamelCase_			= MarkupLMForTokenClassification(config=snake_case__     )
									model.to(snake_case__     )
									model.eval()
									UpperCamelCase_			= model(
									    snake_case__  ,			xpath_tags_seq=snake_case__  ,			xpath_subs_seq=snake_case__  ,			attention_mask=snake_case__  ,			token_type_ids=snake_case__  ,			labels=snake_case__  ,			)
									self.parent.assertEqual(result.logits.shape  ,			(self.batch_size, self.seq_length, self.num_labels)     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			):

									'''simple docstring'''


									UpperCamelCase_			= MarkupLMForQuestionAnswering(config=snake_case__     )
									model.to(snake_case__     )
									model.eval()
									UpperCamelCase_			= model(
									    snake_case__  ,			xpath_tags_seq=snake_case__  ,			xpath_subs_seq=snake_case__  ,			attention_mask=snake_case__  ,			token_type_ids=snake_case__  ,			start_positions=snake_case__  ,			end_positions=snake_case__  ,			)
									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     ):

									'''simple docstring'''


									UpperCamelCase_			= self.prepare_config_and_inputs()
									(
									    (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     (
									    UpperCamelCase_
									)	,     
									)			= config_and_inputs
									UpperCamelCase_			= {
									    "input_ids": input_ids,
									    "xpath_tags_seq": xpath_tags_seq,
									    "xpath_subs_seq": xpath_subs_seq,
									    "token_type_ids": token_type_ids,
									    "attention_mask": input_mask,
									}
									return config, inputs_dict




@require_torch
class    _lowercase (a_   , a_   , unittest.TestCase   ):
				'''simple docstring'''







				lowercase__     =    (
				    (
				        MarkupLMModel,
				        MarkupLMForSequenceClassification,
				        MarkupLMForTokenClassification,
				        MarkupLMForQuestionAnswering,
				    )
				    if is_torch_available()
				    else None
				)
				lowercase__     =    (
				    {
				        """feature-extraction""": MarkupLMModel,
				        """question-answering""": MarkupLMForQuestionAnswering,
				        """text-classification""": MarkupLMForSequenceClassification,
				        """token-classification""": MarkupLMForTokenClassification,
				        """zero-shot""": MarkupLMForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									return True

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= MarkupLMModelTester(self     )
									UpperCamelCase_			= ConfigTester(self  ,			config_class=snake_case__  ,			hidden_size=37     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									self.config_tester.run_common_tests()

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case__     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_sequence_classification(*snake_case__     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*snake_case__     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_question_answering(*snake_case__     )




def  _lowerCAmelCase     ():
					UpperCamelCase_			= "\n    <!DOCTYPE html>\n    <html>\n    <head>\n    <title>Page Title</title>\n    </head>\n    <body>\n\n    <h1>This is a Heading</h1>\n    <p>This is a paragraph.</p>\n\n    </body>\n    </html>\n    "

					return html_string






@require_torch
class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				@cached_property
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= MarkupLMFeatureExtractor()
									UpperCamelCase_			= MarkupLMTokenizer.from_pretrained("microsoft/markuplm-base"     )

									return MarkupLMProcessor(snake_case__  ,			snake_case__     )

				@slow
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= MarkupLMModel.from_pretrained("microsoft/markuplm-base"     ).to(snake_case__     )

									UpperCamelCase_			= self.default_processor

									UpperCamelCase_			= processor(prepare_html_string()  ,			return_tensors="pt"     )
									UpperCamelCase_			= inputs.to(snake_case__     )

									# forward pass
									with torch.no_grad():
														UpperCamelCase_			= model(**snake_case__     )

									# verify the last hidden states
									UpperCamelCase_			= torch.Size([1, 14, 768]     )
									self.assertEqual(outputs.last_hidden_state.shape  ,			snake_case__     )

									UpperCamelCase_			= torch.tensor(
									    [[0.0_675, -0.0_052, 0.5_001], [-0.2_281, 0.0_802, 0.2_192], [-0.0_583, -0.3_311, 0.1_185]]     ).to(snake_case__     )

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





import unittest

import pytest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    MBartaaTokenizerFast,
    MBartConfig,
    MBartForConditionalGeneration,
    TranslationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch, slow

from .test_pipelines_common import ANY


@is_pipeline_test
class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				lowercase__     =    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
				lowercase__     =    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									if isinstance(model.config  ,			snake_case__     ):
														UpperCamelCase_	,     UpperCamelCase_			= list(tokenizer.lang_code_to_id.keys()     )[:2]
														UpperCamelCase_			= TranslationPipeline(model=snake_case__  ,			tokenizer=snake_case__  ,			src_lang=snake_case__  ,			tgt_lang=snake_case__     )
									else:
														UpperCamelCase_			= TranslationPipeline(model=snake_case__  ,			tokenizer=snake_case__     )
									return translator, ["Some string", "Some other text"]

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_			= translator("Some string"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}]     )

									UpperCamelCase_			= translator(["Some string"]     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}]     )

									UpperCamelCase_			= translator(["Some string", "other string"]     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}, {"translation_text": ANY(snake_case__     )}]     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_ro"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="pt"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide"
									                " Beide Beide"
									            )
									        }
									    ]  ,			)

				@require_tf
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_ro"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="tf"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide"
									                " Beide Beide"
									            )
									        }
									    ]  ,			)

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_de"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="pt"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine"
									                " urine urine urine urine urine urine urine"
									            )
									        }
									    ]  ,			)

				@require_tf
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_de"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="tf"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine"
									                " urine urine urine urine urine urine urine"
									            )
									        }
									    ]  ,			)




class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				@require_torch
				@slow
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									with self.assertRaises(snake_case__     ):
														pipeline(task="translation_cn_to_ar"     )

									# but we do for this one
									UpperCamelCase_			= pipeline(task="translation_en_to_de"     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"en"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"de"     )

				@require_torch
				@slow
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt"     )
									UpperCamelCase_			= MBartaaTokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt"     )

									UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__  ,			tokenizer=snake_case__     )
									# Missing src_lang, tgt_lang
									with self.assertRaises(snake_case__     ):
														translator("This is a test"     )

									UpperCamelCase_			= translator("This is a test"  ,			src_lang="en_XX"  ,			tgt_lang="ar_AR"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "هذا إختبار"}]     )

									UpperCamelCase_			= translator("This is a test"  ,			src_lang="en_XX"  ,			tgt_lang="hi_IN"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "यह एक परीक्षण है"}]     )

									# src_lang, tgt_lang can be defined at pipeline call time
									UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__  ,			tokenizer=snake_case__  ,			src_lang="en_XX"  ,			tgt_lang="ar_AR"     )
									UpperCamelCase_			= translator("This is a test"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "هذا إختبار"}]     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= "patrickvonplaten/t5-tiny-random"
									UpperCamelCase_			= pipeline(task="translation_cn_to_ar"  ,			model=snake_case__     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"cn"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"ar"     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= "patrickvonplaten/t5-tiny-random"
									with pytest.warns(snake_case__  ,			match=R".*translation_en_to_de.*"     ):
														UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__     )
									self.assertEqual(translator.task  ,			"translation_en_to_de"     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"en"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"de"     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									with self.assertRaises(snake_case__     ):
														pipeline(task="translation"     )
