






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

	def __init__(							self						,      __UpperCAmelCase						,      __UpperCAmelCase=13						,      __UpperCAmelCase=7						,      __UpperCAmelCase=True						,      __UpperCAmelCase=True						,      __UpperCAmelCase=True						,      __UpperCAmelCase=True						,      __UpperCAmelCase=99						,      __UpperCAmelCase=32						,      __UpperCAmelCase=5						,      __UpperCAmelCase=4						,      __UpperCAmelCase=37						,      __UpperCAmelCase="gelu"						,      __UpperCAmelCase=0.1						,      __UpperCAmelCase=0.1						,      __UpperCAmelCase=512						,      __UpperCAmelCase=16						,      __UpperCAmelCase=2						,      __UpperCAmelCase=0.02						,      __UpperCAmelCase=3						,      __UpperCAmelCase=None						,      __UpperCAmelCase=20						,      __UpperCAmelCase=30						,      __UpperCAmelCase=2						,      __UpperCAmelCase=2						,      __UpperCAmelCase=10						,      )->   Optional[Any]:







							'''simple docstring'''





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

	def 						UpperCAmelCase					(							self    )->   Tuple:







							'''simple docstring'''





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

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

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

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

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

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

							lowerCAmelCase__	 =  self.get_config()

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

	def 						UpperCAmelCase					(							self    )->   int:







							'''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 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      )->   Any:







							'''simple docstring'''





							lowerCAmelCase__	 =  MarkupLMModel(config=__UpperCAmelCase    )
							model.to(__UpperCAmelCase    )
							model.eval()
							print("Configs:"						,      model.config.tag_pad_id						,      model.config.subs_pad_id    )
							lowerCAmelCase__	 =  model(__UpperCAmelCase						,      attention_mask=__UpperCAmelCase						,      token_type_ids=__UpperCAmelCase    )
							lowerCAmelCase__	 =  model(__UpperCAmelCase						,      token_type_ids=__UpperCAmelCase    )
							lowerCAmelCase__	 =  model(__UpperCAmelCase    )
							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 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      )->   Optional[int]:







							'''simple docstring'''





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

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      )->   Dict:







							'''simple docstring'''





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

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      )->   Union[str, Any]:







							'''simple docstring'''





							lowerCAmelCase__	 =  MarkupLMForQuestionAnswering(config=__UpperCAmelCase    )
							model.to(__UpperCAmelCase    )
							model.eval()
							lowerCAmelCase__	 =  model(
							    __UpperCAmelCase						,      xpath_tags_seq=__UpperCAmelCase						,      xpath_subs_seq=__UpperCAmelCase						,      attention_mask=__UpperCAmelCase						,      token_type_ids=__UpperCAmelCase						,      start_positions=__UpperCAmelCase						,      end_positions=__UpperCAmelCase						,      )
							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 						UpperCAmelCase					(							self    )->   Optional[int]:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.prepare_config_and_inputs()
							(
							    (
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							(
							    lowerCAmelCase__
							) ,							
							)	 =  config_and_inputs
							lowerCAmelCase__	 =  {
							    "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__       (     _UpperCAmelCase,   _UpperCAmelCase,   unittest.TestCase		):
	a_             =(
	    (
	        MarkupLMModel,
	        MarkupLMForSequenceClassification,
	        MarkupLMForTokenClassification,
	        MarkupLMForQuestionAnswering,
	    )
	    if is_torch_available()
	    else None
	)
	a_             =(
	    {
	        """feature-extraction""": MarkupLMModel,
	        """question-answering""": MarkupLMForQuestionAnswering,
	        """text-classification""": MarkupLMForSequenceClassification,
	        """token-classification""": MarkupLMForTokenClassification,
	        """zero-shot""": MarkupLMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase						,      __UpperCAmelCase    )->   Union[str, Any]:







							'''simple docstring'''





							return True

	def 						UpperCAmelCase					(							self    )->   Any:







							'''simple docstring'''





							lowerCAmelCase__	 =  MarkupLMModelTester(self    )
							lowerCAmelCase__	 =  ConfigTester(self						,      config_class=__UpperCAmelCase						,      hidden_size=37    )

	def 						UpperCAmelCase					(							self    )->   Any:







							'''simple docstring'''





							self.config_tester.run_common_tests()

	def 						UpperCAmelCase					(							self    )->   Tuple:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCAmelCase    )

	def 						UpperCAmelCase					(							self    )->   Any:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase    )

	def 						UpperCAmelCase					(							self    )->   str:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase    )


	def 						UpperCAmelCase					(							self    )->   str:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase    )





def     _a					(       )	->				Dict:
						"""simple docstring"""







						lowerCAmelCase__	 =  "\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		):

	@cached_property
	def 						UpperCAmelCase					(							self    )->   Optional[Any]:







							'''simple docstring'''





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

							return MarkupLMProcessor(__UpperCAmelCase						,      __UpperCAmelCase    )


	@slow
	def 						UpperCAmelCase					(							self    )->   Optional[int]:







							'''simple docstring'''





							lowerCAmelCase__	 =  MarkupLMModel.from_pretrained("microsoft/markuplm-base"    ).to(__UpperCAmelCase    )

							lowerCAmelCase__	 =  self.default_processor

							lowerCAmelCase__	 =  processor(prepare_html_string()						,      return_tensors="pt"    )
							lowerCAmelCase__	 =  inputs.to(__UpperCAmelCase    )

							# forward pass
							with torch.no_grad():
													lowerCAmelCase__	 =  model(**__UpperCAmelCase    )

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

							lowerCAmelCase__	 =  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(__UpperCAmelCase    )

							self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]						,      __UpperCAmelCase						,      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

a_							=      logging.get_logger(__name__)


def     _a					(       UpperCamelCase_   :			bytes      ,				UpperCamelCase_   :			int				)	->				np.array:
						"""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(_UpperCAmelCase		)
class        lowercase__       (     _UpperCAmelCase		):

	def __init__(							self						,      *__UpperCAmelCase						,      **__UpperCAmelCase    )->   Any:







							'''simple docstring'''





							lowerCAmelCase__	 =  5
							super().__init__(*__UpperCAmelCase						,      **__UpperCAmelCase    )

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

							self.check_model_type(__UpperCAmelCase    )

	def __call__(							self						,      __UpperCAmelCase						,      **__UpperCAmelCase						,      )->   List[str]:







							'''simple docstring'''





							return super().__call__(__UpperCAmelCase						,      **__UpperCAmelCase    )

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase=None						,      **__UpperCAmelCase    )->   Dict:







							'''simple docstring'''





							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 						UpperCAmelCase					(							self						,      __UpperCAmelCase    )->   str:







							'''simple docstring'''





							if isinstance(__UpperCAmelCase						,      __UpperCAmelCase    ):
													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(__UpperCAmelCase    ).content
													else:
																			with open(__UpperCAmelCase						,      "rb"    ) as f:
																									lowerCAmelCase__	 =  f.read()

							if isinstance(__UpperCAmelCase						,      __UpperCAmelCase    ):
													lowerCAmelCase__	 =  ffmpeg_read(__UpperCAmelCase						,      self.feature_extractor.sampling_rate    )

							if isinstance(__UpperCAmelCase						,      __UpperCAmelCase    ):
													# 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"						,      __UpperCAmelCase    )
													if _inputs is None:
																			# Remove path which will not be used from `datasets`.
																			inputs.pop("path"						,      __UpperCAmelCase    )
																			lowerCAmelCase__	 =  inputs.pop("array"						,      __UpperCAmelCase    )
													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(__UpperCAmelCase    )						,      __UpperCAmelCase						,      self.feature_extractor.sampling_rate    ).numpy()

							if not isinstance(__UpperCAmelCase						,      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(
							    __UpperCAmelCase						,      sampling_rate=self.feature_extractor.sampling_rate						,      return_tensors="pt"    )
							return processed

	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase    )->   Tuple:







							'''simple docstring'''





							lowerCAmelCase__	 =  self.model(**__UpperCAmelCase    )
							return model_outputs


	def 						UpperCAmelCase					(							self						,      __UpperCAmelCase						,      __UpperCAmelCase=5    )->   int:







							'''simple docstring'''





							lowerCAmelCase__	 =  model_outputs.logits[0].softmax(-1    )
							lowerCAmelCase__ ,							lowerCAmelCase__	 =  probs.topk(__UpperCAmelCase    )

							lowerCAmelCase__	 =  scores.tolist()
							lowerCAmelCase__	 =  ids.tolist()

							lowerCAmelCase__	 =  [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__UpperCAmelCase						,      __UpperCAmelCase    )]

							return labels






