



'''simple docstring'''



import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
	import torch
	from torch import nn

	from transformers import SwiftFormerForImageClassification, SwiftFormerModel
	from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import ViTImageProcessor






class 					UpperCAmelCase__	:



					def __init__(    self			,				UpperCamelCase			,				UpperCamelCase=13			,				UpperCamelCase=3			,				UpperCamelCase=True			,				UpperCamelCase=True			,				UpperCamelCase=0.1			,				UpperCamelCase=0.1			,				UpperCamelCase=224			,				UpperCamelCase=1000			,				UpperCamelCase=[3, 3, 6, 4]			,				UpperCamelCase=[48, 56, 112, 220]			,				)     ->			Any:
						__lowerCAmelCase												=  parent
						__lowerCAmelCase												=  batch_size
						__lowerCAmelCase												=  num_channels
						__lowerCAmelCase												=  is_training
						__lowerCAmelCase												=  use_labels
						__lowerCAmelCase												=  hidden_dropout_prob
						__lowerCAmelCase												=  attention_probs_dropout_prob
						__lowerCAmelCase												=  num_labels
						__lowerCAmelCase												=  image_size
						__lowerCAmelCase												=  layer_depths
						__lowerCAmelCase												=  embed_dims



					def        UpperCAmelCase_ (    self     )     ->			Optional[int]:
						__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.num_labels     )

						__lowerCAmelCase												=  self.get_config()

						return config, pixel_values, labels



					def        UpperCAmelCase_ (    self     )     ->			Dict:
						return SwiftFormerConfig(
						    depths=self.layer_depths			,				embed_dims=self.embed_dims			,				mlp_ratio=4			,				downsamples=[True, True, True, True]			,				hidden_act="gelu"			,				num_labels=self.num_labels			,				down_patch_size=3			,				down_stride=2			,				down_pad=1			,				drop_rate=0.0			,				drop_path_rate=0.0			,				use_layer_scale=lowerCAmelCase_			,				layer_scale_init_value=1E-5			,				)



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )     ->			Tuple:
						__lowerCAmelCase												=  SwiftFormerModel(config=lowerCAmelCase_     )
						model.to(lowerCAmelCase_     )
						model.eval()
						__lowerCAmelCase												=  model(lowerCAmelCase_     )
						self.parent.assertEqual(result.last_hidden_state.shape			,				(self.batch_size, self.embed_dims[-1], 7, 7)     )



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )     ->			Any:
						__lowerCAmelCase												=  self.num_labels
						__lowerCAmelCase												=  SwiftFormerForImageClassification(lowerCAmelCase_     )
						model.to(lowerCAmelCase_     )
						model.eval()
						__lowerCAmelCase												=  model(lowerCAmelCase_			,				labels=lowerCAmelCase_     )
						self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels)     )

						__lowerCAmelCase												=  SwiftFormerForImageClassification(lowerCAmelCase_     )
						model.to(lowerCAmelCase_     )
						model.eval()

						__lowerCAmelCase												=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )
						__lowerCAmelCase												=  model(lowerCAmelCase_     )
						self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels)     )



					def        UpperCAmelCase_ (    self     )     ->			str:
						((__lowerCAmelCase)							,       (__lowerCAmelCase)							,       (__lowerCAmelCase))												=  self.prepare_config_and_inputs()
						__lowerCAmelCase												=  {"pixel_values": pixel_values}
						return config, inputs_dict






@require_torch
class 					UpperCAmelCase__	(		__a							,       __a							,       unittest.TestCase ):
					a      :     Any        =							(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
					a      :     List[Any]        =							(
					    {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
					    if is_torch_available()
					    else {}
					)

					a      :     Union[str, Any]        =							False
					a      :     List[Any]        =							False
					a      :     int        =							False
					a      :     List[str]        =							False
					a      :     List[Any]        =							False



					def        UpperCAmelCase_ (    self     )     ->			int:
						__lowerCAmelCase												=  SwiftFormerModelTester(self     )
						__lowerCAmelCase												=  ConfigTester(
						    self			,				config_class=lowerCAmelCase_			,				has_text_modality=lowerCAmelCase_			,				hidden_size=37			,				num_attention_heads=12			,				num_hidden_layers=12			,				)



					def        UpperCAmelCase_ (    self     )     ->			List[str]:
						self.config_tester.run_common_tests()



					@unittest.skip(reason="SwiftFormer does not use inputs_embeds"     )
					def        UpperCAmelCase_ (    self     )     ->			Optional[Any]:
						pass



					def        UpperCAmelCase_ (    self     )     ->			Dict:
						__lowerCAmelCase							,       __lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							__lowerCAmelCase												=  model_class(lowerCAmelCase_     )
							__lowerCAmelCase												=  model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(lowerCAmelCase_			,				nn.Linear     )     )



					def        UpperCAmelCase_ (    self     )     ->			Tuple:
						__lowerCAmelCase							,       __lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							__lowerCAmelCase												=  model_class(lowerCAmelCase_     )
							__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]			,				lowerCAmelCase_     )



					def        UpperCAmelCase_ (    self     )     ->			Any:
						__lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase_     )



					def        UpperCAmelCase_ (    self     )     ->			Optional[Any]:
						__lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_     )



					@slow
					def        UpperCAmelCase_ (    self     )     ->			List[str]:







						for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowerCAmelCase												=  SwiftFormerModel.from_pretrained(lowerCAmelCase_     )
							self.assertIsNotNone(lowerCAmelCase_     )



					@unittest.skip(reason="SwiftFormer does not output attentions"     )
					def        UpperCAmelCase_ (    self     )     ->			Any:
						pass



					def        UpperCAmelCase_ (    self     )     ->			str:







						def check_hidden_states_output(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     ):
							__lowerCAmelCase												=  model_class(lowerCAmelCase_     )
							model.to(lowerCAmelCase_     )
							model.eval()

							with torch.no_grad():
								__lowerCAmelCase												=  model(**self._prepare_for_class(lowerCAmelCase_			,				lowerCAmelCase_     )     )

							__lowerCAmelCase												=  outputs.hidden_states

							__lowerCAmelCase												=  8
							self.assertEqual(len(lowerCAmelCase_     )			,				lowerCAmelCase_     )  # TODO

							# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
							# with the width and height being successively divided by 2, after every 2 blocks
							for i in range(len(lowerCAmelCase_     )     ):
								self.assertEqual(
								    hidden_states[i].shape			,				torch.Size(
								        [
								            self.model_tester.batch_size,
								            self.model_tester.embed_dims[i // 2],
								            (self.model_tester.image_size // 4) // 2 ** (i // 2),
								            (self.model_tester.image_size // 4) // 2 ** (i // 2),
								        ]     )			,				)

						__lowerCAmelCase							,       __lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							__lowerCAmelCase												=  True
							check_hidden_states_output(lowerCAmelCase_			,				lowerCAmelCase_			,				lowerCAmelCase_     )

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

							check_hidden_states_output(lowerCAmelCase_			,				lowerCAmelCase_			,				lowerCAmelCase_     )



					def        UpperCAmelCase_ (    self     )     ->			str:







						def _config_zero_init(UpperCamelCase     ):
							__lowerCAmelCase												=  copy.deepcopy(lowerCAmelCase_     )
							for key in configs_no_init.__dict__.keys():
								if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
									setattr(lowerCAmelCase_			,				lowerCAmelCase_			,				1E-10     )
								if isinstance(getattr(lowerCAmelCase_			,				lowerCAmelCase_			,				lowerCAmelCase_     )			,				lowerCAmelCase_     ):
									__lowerCAmelCase												=  _config_zero_init(getattr(lowerCAmelCase_			,				lowerCAmelCase_     )     )
									setattr(lowerCAmelCase_			,				lowerCAmelCase_			,				lowerCAmelCase_     )
							return configs_no_init

						__lowerCAmelCase							,       __lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs_for_common()

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



					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."     )
					def        UpperCAmelCase_ (    self     )     ->			Optional[int]:
						pass



def   __lowerCAmelCase					(							):






	'''simple docstring'''




	__lowerCAmelCase												=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
	return image






@require_torch
@require_vision
class 					UpperCAmelCase__	(		unittest.TestCase ):



					@cached_property
					def        UpperCAmelCase_ (    self     )     ->			Union[str, Any]:
						return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs"     ) if is_vision_available() else None



					@slow
					def        UpperCAmelCase_ (    self     )     ->			str:
						__lowerCAmelCase												=  SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs"     ).to(lowerCAmelCase_     )

						__lowerCAmelCase												=  self.default_image_processor
						__lowerCAmelCase												=  prepare_img()
						__lowerCAmelCase												=  image_processor(images=lowerCAmelCase_			,				return_tensors="pt"     ).to(lowerCAmelCase_     )

						# forward pass
						with torch.no_grad():
							__lowerCAmelCase												=  model(**lowerCAmelCase_     )

						# verify the logits
						__lowerCAmelCase												=  torch.Size((1, 1000)     )
						self.assertEqual(outputs.logits.shape			,				lowerCAmelCase_     )

						__lowerCAmelCase												=  torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]]     ).to(lowerCAmelCase_     )
						self.assertTrue(torch.allclose(outputs.logits[0, :3]			,				lowerCAmelCase_			,				atol=1E-4     )     )




'''simple docstring'''



import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np



def   __lowerCAmelCase					(							lowerCamelCase   :						bytes				,		lowerCamelCase   :						int					):






	'''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:
		with subprocess.Popen(lowerCamelCase				,		stdin=subprocess.PIPE				,		stdout=subprocess.PIPE					) as ffmpeg_process:
			__lowerCAmelCase												=  ffmpeg_process.communicate(lowerCamelCase					)
	except FileNotFoundError as error:
		raise ValueError("ffmpeg was not found but is required to load audio files from filename"					) from error
	__lowerCAmelCase												=  output_stream[0]
	__lowerCAmelCase												=  np.frombuffer(lowerCamelCase				,		np.floataa					)
	if audio.shape[0] == 0:
		raise ValueError("Malformed soundfile"					)
	return audio



def   __lowerCAmelCase					(							lowerCamelCase   :						int				,		lowerCamelCase   :						float				,		lowerCamelCase   :						str = "f32le"				,		):






	'''simple docstring'''




	__lowerCAmelCase												=  f'''{sampling_rate}'''
	__lowerCAmelCase												=  "1"
	if format_for_conversion == "s16le":
		__lowerCAmelCase												=  2
	elif format_for_conversion == "f32le":
		__lowerCAmelCase												=  4
	else:
		raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''					)

	__lowerCAmelCase												=  platform.system()
	if system == "Linux":
		__lowerCAmelCase												=  "alsa"
		__lowerCAmelCase												=  "default"
	elif system == "Darwin":
		__lowerCAmelCase												=  "avfoundation"
		__lowerCAmelCase												=  ":0"
	elif system == "Windows":
		__lowerCAmelCase												=  "dshow"
		__lowerCAmelCase												=  "default"

	__lowerCAmelCase												=  [
	    "ffmpeg",
	    "-f",
	    format_,
	    "-i",
	    input_,
	    "-ac",
	    ac,
	    "-ar",
	    ar,
	    "-f",
	    format_for_conversion,
	    "-fflags",
	    "nobuffer",
	    "-hide_banner",
	    "-loglevel",
	    "quiet",
	    "pipe:1",
	]
	__lowerCAmelCase												=  int(round(sampling_rate * chunk_length_s					)					) * size_of_sample
	__lowerCAmelCase												=  _ffmpeg_stream(lowerCamelCase				,		lowerCamelCase					)
	for item in iterator:
		yield item



def   __lowerCAmelCase					(							lowerCamelCase   :						int				,		lowerCamelCase   :						float				,		lowerCamelCase   :						Optional[int] = None				,		lowerCamelCase   :						Optional[Union[Tuple[float, float], float]] = None				,		lowerCamelCase   :						str = "f32le"				,		):






	'''simple docstring'''




	if stream_chunk_s is not None:
		__lowerCAmelCase												=  stream_chunk_s
	else:
		__lowerCAmelCase												=  chunk_length_s

	__lowerCAmelCase												=  ffmpeg_microphone(lowerCamelCase				,		lowerCamelCase				,		format_for_conversion=lowerCamelCase					)
	if format_for_conversion == "s16le":
		__lowerCAmelCase												=  np.intaa
		__lowerCAmelCase												=  2
	elif format_for_conversion == "f32le":
		__lowerCAmelCase												=  np.floataa
		__lowerCAmelCase												=  4
	else:
		raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''					)

	if stride_length_s is None:
		__lowerCAmelCase												=  chunk_length_s / 6
	__lowerCAmelCase												=  int(round(sampling_rate * chunk_length_s					)					) * size_of_sample
	if isinstance(lowerCamelCase				,		(int, float)					):
		__lowerCAmelCase												=  [stride_length_s, stride_length_s]

	__lowerCAmelCase												=  int(round(sampling_rate * stride_length_s[0]					)					) * size_of_sample
	__lowerCAmelCase												=  int(round(sampling_rate * stride_length_s[1]					)					) * size_of_sample
	__lowerCAmelCase												=  datetime.datetime.now()
	__lowerCAmelCase												=  datetime.timedelta(seconds=lowerCamelCase					)
	for item in chunk_bytes_iter(lowerCamelCase				,		lowerCamelCase				,		stride=(stride_left, stride_right)				,		stream=lowerCamelCase					):
		# Put everything back in numpy scale
		__lowerCAmelCase												=  np.frombuffer(item["raw"]				,		dtype=lowerCamelCase					)
		__lowerCAmelCase												=  (
		    item["stride"][0] // size_of_sample,
		    item["stride"][1] // size_of_sample,
		)
		__lowerCAmelCase												=  sampling_rate
		audio_time += delta
		if datetime.datetime.now() > audio_time + 10 * delta:
			# We're late !! SKIP
			continue
		yield item



def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[Any]				,		lowerCamelCase   :						int				,		lowerCamelCase   :						Tuple[int, int]				,		lowerCamelCase   :						bool = False					):






	'''simple docstring'''




	__lowerCAmelCase												=  B""
	__lowerCAmelCase							,       __lowerCAmelCase												=  stride
	if stride_left + stride_right >= chunk_len:
		raise ValueError(
		    f'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}'''					)
	__lowerCAmelCase												=  0
	for raw in iterator:
		acc += raw
		if stream and len(lowerCamelCase					) < chunk_len:
			__lowerCAmelCase												=  (_stride_left, 0)
			yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
		else:
			while len(lowerCamelCase					) >= chunk_len:
				# We are flushing the accumulator
				__lowerCAmelCase												=  (_stride_left, stride_right)
				__lowerCAmelCase												=  {"raw": acc[:chunk_len], "stride": stride}
				if stream:
					__lowerCAmelCase												=  False
				yield item
				__lowerCAmelCase												=  stride_left
				__lowerCAmelCase												=  acc[chunk_len - stride_left - stride_right :]
    # Last chunk
	if len(lowerCamelCase					) > stride_left:
		__lowerCAmelCase												=  {"raw": acc, "stride": (_stride_left, 0)}
		if stream:
			__lowerCAmelCase												=  False
		yield item




def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[int]				,		lowerCamelCase   :						int					):






	'''simple docstring'''




	__lowerCAmelCase												=  2**24  # 16Mo
	try:
		with subprocess.Popen(lowerCamelCase				,		stdout=subprocess.PIPE				,		bufsize=lowerCamelCase					) as ffmpeg_process:
			while True:
				__lowerCAmelCase												=  ffmpeg_process.stdout.read(lowerCamelCase					)
				if raw == b"":
					break
				yield raw
	except FileNotFoundError as error:
		raise ValueError("ffmpeg was not found but is required to stream audio files from filename"					) from error