



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 subprocess
from typing import Union

import numpy as np
import requests

from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING

lowerCamelCase   					=  logging.get_logger(__name__)


def 							__lowercase     (	UpperCAmelCase__		,       UpperCAmelCase__   ):

					"""simple docstring"""






					__lowerCAmelCase       =				F"""{sampling_rate}"""
					__lowerCAmelCase       =				'1'
					__lowerCAmelCase       =				'f32le'
					__lowerCAmelCase       =				[
					    'ffmpeg',
					    '-i',
					    'pipe:0',
					    '-ac',
					    ac,
					    '-ar',
					    ar,
					    '-f',
					    format_for_conversion,
					    '-hide_banner',
					    '-loglevel',
					    'quiet',
					    'pipe:1',
					]

					try:
										__lowerCAmelCase       =				subprocess.Popen(UpperCAmelCase__		,       stdin=subprocess.PIPE		,       stdout=subprocess.PIPE   )
					except FileNotFoundError:
										raise ValueError('ffmpeg was not found but is required to load audio files from filename'   )
					__lowerCAmelCase       =				ffmpeg_process.communicate(UpperCAmelCase__   )
					__lowerCAmelCase       =				output_stream[0]

					__lowerCAmelCase       =				np.frombuffer(UpperCAmelCase__		,       np.floataa   )
					if audio.shape[0] == 0:
										raise ValueError('Malformed soundfile'   )
					return audio





@add_end_docstrings(_a				)
class      snake_case_      (					_a				):


							"""simple docstring"""





							def __init__(			self       ,    *_A       ,    **_A				):
												# Default, might be overriden by the model.config.
												__lowerCAmelCase       =				5
												super().__init__(*_A       ,    **_A				)

												if self.framework != "pt":
																	raise ValueError(F"""The {self.__class__} is only available in PyTorch."""				)

												self.check_model_type(_A				)




							def __call__(			self       ,    _A       ,    **_A       ,    ):
												return super().__call__(_A       ,    **_A				)




							def 							A__	(			self       ,    _A=None       ,    **_A				):
												# No parameters on this pipeline right now
												__lowerCAmelCase       =				{}
												if top_k is not None:
																	if top_k > self.model.config.num_labels:
																						__lowerCAmelCase       =				self.model.config.num_labels
																	__lowerCAmelCase       =				top_k
												return {}, {}, postprocess_params




							def 							A__	(			self       ,    _A				):
												if isinstance(_A       ,    _A				):
																	if inputs.startswith('http://'				) or inputs.startswith('https://'				):
																						# We need to actually check for a real protocol, otherwise it's impossible to use a local file
																						# like http_huggingface_co.png
																						__lowerCAmelCase       =				requests.get(_A				).content
																	else:
																						with open(_A       ,    'rb'				) as f:
																											__lowerCAmelCase       =				f.read()

												if isinstance(_A       ,    _A				):
																	__lowerCAmelCase       =				ffmpeg_read(_A       ,    self.feature_extractor.sampling_rate				)

												if isinstance(_A       ,    _A				):
																	# Accepting `"array"` which is the key defined in `datasets` for
																	# better integration
																	if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
																						raise ValueError(
																						    'When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a '
																						    '"raw" key containing the numpy array representing the audio and a "sampling_rate" key, '
																						    'containing the sampling_rate associated with that array'				)

																	__lowerCAmelCase       =				inputs.pop('raw'       ,    _A				)
																	if _inputs is None:
																						# Remove path which will not be used from `datasets`.
																						inputs.pop('path'       ,    _A				)
																						__lowerCAmelCase       =				inputs.pop('array'       ,    _A				)
																	__lowerCAmelCase       =				inputs.pop('sampling_rate'				)
																	__lowerCAmelCase       =				_inputs
																	if in_sampling_rate != self.feature_extractor.sampling_rate:
																						import torch

																						if is_torchaudio_available():
																											from torchaudio import functional as F
																						else:
																											raise ImportError(
																											    'torchaudio is required to resample audio samples in AudioClassificationPipeline. '
																											    'The torchaudio package can be installed through: `pip install torchaudio`.'				)

																						__lowerCAmelCase       =				F.resample(
																						    torch.from_numpy(_A				)       ,    _A       ,    self.feature_extractor.sampling_rate				).numpy()

												if not isinstance(_A       ,    np.ndarray				):
																	raise ValueError('We expect a numpy ndarray as input'				)
												if len(inputs.shape				) != 1:
																	raise ValueError('We expect a single channel audio input for AudioClassificationPipeline'				)

												__lowerCAmelCase       =				self.feature_extractor(
												    _A       ,    sampling_rate=self.feature_extractor.sampling_rate       ,    return_tensors='pt'				)
												return processed




							def 							A__	(			self       ,    _A				):
												__lowerCAmelCase       =				self.model(**_A				)
												return model_outputs




							def 							A__	(			self       ,    _A       ,    _A=5				):
												__lowerCAmelCase       =				model_outputs.logits[0].softmax(-1				)
												__lowerCAmelCase,						__lowerCAmelCase       =				probs.topk(_A				)

												__lowerCAmelCase       =				scores.tolist()
												__lowerCAmelCase       =				ids.tolist()

												__lowerCAmelCase       =				[{'score': score, 'label': self.model.config.idalabel[_id]} for score, _id in zip(_A       ,    _A				)]

												return labels






