






import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import DonutSwinModel
	from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


class        lowercase__       :

		def __init__(							self						,      __UpperCAmelCase						,      __UpperCAmelCase=13						,      __UpperCAmelCase=32						,      __UpperCAmelCase=2						,      __UpperCAmelCase=3						,      __UpperCAmelCase=16						,      __UpperCAmelCase=[1, 2, 1]						,      __UpperCAmelCase=[2, 2, 4]						,      __UpperCAmelCase=2						,      __UpperCAmelCase=2.0						,      __UpperCAmelCase=True						,      __UpperCAmelCase=0.0						,      __UpperCAmelCase=0.0						,      __UpperCAmelCase=0.1						,      __UpperCAmelCase="gelu"						,      __UpperCAmelCase=False						,      __UpperCAmelCase=True						,      __UpperCAmelCase=0.02						,      __UpperCAmelCase=1E-5						,      __UpperCAmelCase=True						,      __UpperCAmelCase=None						,      __UpperCAmelCase=True						,      __UpperCAmelCase=10						,      __UpperCAmelCase=8						,      )->   Union[str, Any]:







								'''simple docstring'''





								lowerCAmelCase__	 =  parent
								lowerCAmelCase__	 =  batch_size
								lowerCAmelCase__	 =  image_size
								lowerCAmelCase__	 =  patch_size
								lowerCAmelCase__	 =  num_channels
								lowerCAmelCase__	 =  embed_dim
								lowerCAmelCase__	 =  depths
								lowerCAmelCase__	 =  num_heads
								lowerCAmelCase__	 =  window_size
								lowerCAmelCase__	 =  mlp_ratio
								lowerCAmelCase__	 =  qkv_bias
								lowerCAmelCase__	 =  hidden_dropout_prob
								lowerCAmelCase__	 =  attention_probs_dropout_prob
								lowerCAmelCase__	 =  drop_path_rate
								lowerCAmelCase__	 =  hidden_act
								lowerCAmelCase__	 =  use_absolute_embeddings
								lowerCAmelCase__	 =  patch_norm
								lowerCAmelCase__	 =  layer_norm_eps
								lowerCAmelCase__	 =  initializer_range
								lowerCAmelCase__	 =  is_training
								lowerCAmelCase__	 =  scope
								lowerCAmelCase__	 =  use_labels
								lowerCAmelCase__	 =  type_sequence_label_size
								lowerCAmelCase__	 =  encoder_stride

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







								'''simple docstring'''





								lowerCAmelCase__	 =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

								lowerCAmelCase__	 =  self.get_config()

								return config, pixel_values, labels

		def 						UpperCAmelCase					(							self    )->   List[str]:







								'''simple docstring'''





								return DonutSwinConfig(
								    image_size=self.image_size						,      patch_size=self.patch_size						,      num_channels=self.num_channels						,      embed_dim=self.embed_dim						,      depths=self.depths						,      num_heads=self.num_heads						,      window_size=self.window_size						,      mlp_ratio=self.mlp_ratio						,      qkv_bias=self.qkv_bias						,      hidden_dropout_prob=self.hidden_dropout_prob						,      attention_probs_dropout_prob=self.attention_probs_dropout_prob						,      drop_path_rate=self.drop_path_rate						,      hidden_act=self.hidden_act						,      use_absolute_embeddings=self.use_absolute_embeddings						,      path_norm=self.patch_norm						,      layer_norm_eps=self.layer_norm_eps						,      initializer_range=self.initializer_range						,      encoder_stride=self.encoder_stride						,      )

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







								'''simple docstring'''





								lowerCAmelCase__	 =  DonutSwinModel(config=snake_case_    )
								model.to(snake_case_    )
								model.eval()
								lowerCAmelCase__	 =  model(snake_case_    )

								lowerCAmelCase__	 =  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
								lowerCAmelCase__	 =  int(config.embed_dim * 2 ** (len(config.depths    ) - 1)    )

								self.parent.assertEqual(result.last_hidden_state.shape						,      (self.batch_size, expected_seq_len, expected_dim)    )


		def 						UpperCAmelCase					(							self    )->   Dict:







								'''simple docstring'''





								lowerCAmelCase__	 =  self.prepare_config_and_inputs()
								(
								    (
								    lowerCAmelCase__      
								) ,							(
								    lowerCAmelCase__      
								) ,							(
								    lowerCAmelCase__      
								) ,							      
								)	 =  config_and_inputs
								lowerCAmelCase__	 =  {"pixel_values": pixel_values}
								return config, inputs_dict





@require_torch
class        lowercase__       (     A__,   A__,   unittest.TestCase		):
		a_             =(DonutSwinModel,) if is_torch_available() else ()
		a_             ={"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
		a_             =True

		a_             =False
		a_             =False
		a_             =False

		def 						UpperCAmelCase					(							self    )->   List[Any]:







								'''simple docstring'''





								lowerCAmelCase__	 =  DonutSwinModelTester(self    )
								lowerCAmelCase__	 =  ConfigTester(self						,      config_class=snake_case_						,      embed_dim=37    )

		def 						UpperCAmelCase					(							self    )->   str:







								'''simple docstring'''





								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()

		def 						UpperCAmelCase					(							self    )->   Dict:







								'''simple docstring'''





								return

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







								'''simple docstring'''





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

		def 						UpperCAmelCase					(							self    )->   List[str]:







								'''simple docstring'''





								pass

		def 						UpperCAmelCase					(							self    )->   str:







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  model_class(snake_case_    )
														self.assertIsInstance(model.get_input_embeddings()						,      (nn.Module)    )
														lowerCAmelCase__	 =  model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(snake_case_						,      nn.Linear    )    )

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







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  model_class(snake_case_    )
														lowerCAmelCase__	 =  inspect.signature(model.forward    )
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														lowerCAmelCase__	 =  [*signature.parameters.keys()]

														lowerCAmelCase__	 =  ["pixel_values"]
														self.assertListEqual(arg_names[:1]						,      snake_case_    )

		def 						UpperCAmelCase					(							self    )->   Tuple:







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()
								lowerCAmelCase__	 =  True

								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  True
														lowerCAmelCase__	 =  False
														lowerCAmelCase__	 =  True
														lowerCAmelCase__	 =  model_class(snake_case_    )
														model.to(snake_case_    )
														model.eval()
														with torch.no_grad():
																				lowerCAmelCase__	 =  model(**self._prepare_for_class(snake_case_						,      snake_case_    )    )
														lowerCAmelCase__	 =  outputs.attentions
														lowerCAmelCase__	 =  len(self.model_tester.depths    )
														self.assertEqual(len(snake_case_    )						,      snake_case_    )

														# check that output_attentions also work using config
														del inputs_dict["output_attentions"]
														lowerCAmelCase__	 =  True
														lowerCAmelCase__	 =  config.window_size**2
														lowerCAmelCase__	 =  model_class(snake_case_    )
														model.to(snake_case_    )
														model.eval()
														with torch.no_grad():
																				lowerCAmelCase__	 =  model(**self._prepare_for_class(snake_case_						,      snake_case_    )    )
														lowerCAmelCase__	 =  outputs.attentions
														self.assertEqual(len(snake_case_    )						,      snake_case_    )

														self.assertListEqual(
														    list(attentions[0].shape[-3:]    )						,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,      )
														lowerCAmelCase__	 =  len(snake_case_    )

														# Check attention is always last and order is fine
														lowerCAmelCase__	 =  True
														lowerCAmelCase__	 =  True
														lowerCAmelCase__	 =  model_class(snake_case_    )
														model.to(snake_case_    )
														model.eval()
														with torch.no_grad():
																				lowerCAmelCase__	 =  model(**self._prepare_for_class(snake_case_						,      snake_case_    )    )

														if hasattr(self.model_tester						,      "num_hidden_states_types"    ):
																				lowerCAmelCase__	 =  self.model_tester.num_hidden_states_types
														else:
																				# also another +1 for reshaped_hidden_states
																				lowerCAmelCase__	 =  2
														self.assertEqual(out_len + added_hidden_states						,      len(snake_case_    )    )

														lowerCAmelCase__	 =  outputs.attentions

														self.assertEqual(len(snake_case_    )						,      snake_case_    )

														self.assertListEqual(
														    list(self_attentions[0].shape[-3:]    )						,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,      )

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







								'''simple docstring'''





								lowerCAmelCase__	 =  model_class(snake_case_    )
								model.to(snake_case_    )
								model.eval()

								with torch.no_grad():
														lowerCAmelCase__	 =  model(**self._prepare_for_class(snake_case_						,      snake_case_    )    )

								lowerCAmelCase__	 =  outputs.hidden_states

								lowerCAmelCase__	 =  getattr(
								    self.model_tester						,      "expected_num_hidden_layers"						,      len(self.model_tester.depths    ) + 1    )
								self.assertEqual(len(snake_case_    )						,      snake_case_    )

								# DonutSwin has a different seq_length
								lowerCAmelCase__	 =  (
								    config.patch_size
								    if isinstance(config.patch_size						,      collections.abc.Iterable    )
								    else (config.patch_size, config.patch_size)
								)

								lowerCAmelCase__	 =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]    )						,      [num_patches, self.model_tester.embed_dim]						,      )

								lowerCAmelCase__	 =  outputs.reshaped_hidden_states
								self.assertEqual(len(snake_case_    )						,      snake_case_    )

								lowerCAmelCase__ ,							lowerCAmelCase__ ,							lowerCAmelCase__ ,							lowerCAmelCase__	 =  reshaped_hidden_states[0].shape
								lowerCAmelCase__	 =  (
								    reshaped_hidden_states[0].view(snake_case_						,      snake_case_						,      height * width    ).permute(0						,      2						,      1    )
								)
								self.assertListEqual(
								    list(reshaped_hidden_states.shape[-2:]    )						,      [num_patches, self.model_tester.embed_dim]						,      )

		def 						UpperCAmelCase					(							self    )->   List[Any]:







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()

								lowerCAmelCase__	 =  (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size						,      collections.abc.Iterable    )
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)

								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  True
														self.check_hidden_states_output(snake_case_						,      snake_case_						,      snake_case_						,      snake_case_    )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowerCAmelCase__	 =  True

														self.check_hidden_states_output(snake_case_						,      snake_case_						,      snake_case_						,      snake_case_    )

		def 						UpperCAmelCase					(							self    )->   str:







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()
								lowerCAmelCase__	 =  3

								lowerCAmelCase__	 =  (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size						,      collections.abc.Iterable    )
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)
								lowerCAmelCase__	 =  (
								    config.patch_size
								    if isinstance(config.patch_size						,      collections.abc.Iterable    )
								    else (config.patch_size, config.patch_size)
								)

								lowerCAmelCase__	 =  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								lowerCAmelCase__	 =  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  True
														self.check_hidden_states_output(snake_case_						,      snake_case_						,      snake_case_						,      (padded_height, padded_width)    )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowerCAmelCase__	 =  True
														self.check_hidden_states_output(snake_case_						,      snake_case_						,      snake_case_						,      (padded_height, padded_width)    )

		@slow
		def 						UpperCAmelCase					(							self    )->   str:







								'''simple docstring'''





								for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCAmelCase__	 =  DonutSwinModel.from_pretrained(snake_case_    )
														self.assertIsNotNone(snake_case_    )


		def 						UpperCAmelCase					(							self    )->   int:







								'''simple docstring'''





								lowerCAmelCase__ ,							lowerCAmelCase__	 =  self.model_tester.prepare_config_and_inputs_for_common()

								lowerCAmelCase__	 =  _config_zero_init(snake_case_    )
								for model_class in self.all_model_classes:
														lowerCAmelCase__	 =  model_class(config=snake_case_    )
														for name, param in model.named_parameters():
																				if "embeddings" not in name and param.requires_grad:
																										self.assertIn(
																										    ((param.data.mean() * 1E9).round() / 1E9).item()						,      [0.0, 1.0]						,      msg=F"Parameter {name} of model {model_class} seems not properly initialized"						,      )














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






