





"""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 				__lowercase			:







					'''simple docstring'''




					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]	,			):
									__a :						Union[str, Any]			       =  parent
									__a :						str			       =  batch_size
									__a :						Dict			       =  num_channels
									__a :						List[Any]			       =  is_training
									__a :						int			       =  use_labels
									__a :						Tuple			       =  hidden_dropout_prob
									__a :						str			       =  attention_probs_dropout_prob
									__a :						Dict			       =  num_labels
									__a :						Union[str, Any]			       =  image_size
									__a :						Union[str, Any]			       =  layer_depths
									__a :						List[Any]			       =  embed_dims







					def  _lowerCamelCase		(						self     ):
									__a :						int			       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

									__a :						Any			       =  None
									if self.use_labels:
													__a :						int			       =  ids_tensor([self.batch_size]	,			self.num_labels     )

									__a :						Tuple			       =  self.get_config()

									return config, pixel_values, labels







					def  _lowerCamelCase		(						self     ):
									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=_UpperCAmelCase	,			layer_scale_init_value=1e-5	,			)







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						List[Any]			       =  SwiftFormerModel(config=_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()
									__a :						List[str]			       =  model(_UpperCAmelCase     )
									self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.embed_dims[-1], 7, 7)     )







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						Union[str, Any]			       =  self.num_labels
									__a :						Dict			       =  SwiftFormerForImageClassification(_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()
									__a :						str			       =  model(_UpperCAmelCase	,			labels=_UpperCAmelCase     )
									self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)     )

									__a :						Optional[int]			       =  SwiftFormerForImageClassification(_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()

									__a :						List[Any]			       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )
									__a :						List[str]			       =  model(_UpperCAmelCase     )
									self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)     )







					def  _lowerCamelCase		(						self     ):
									((__a)       ,						(__a)       ,						(__a)) :						List[Any]			       =  self.prepare_config_and_inputs()
									__a :						int			       =  {'''pixel_values''': pixel_values}
									return config, inputs_dict






@require_torch
class 				__lowercase			(			_UpperCamelCase   ,      _UpperCamelCase   ,      unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
					__lowerCAmelCase  =  (
					    {'''feature-extraction''': SwiftFormerModel, '''image-classification''': SwiftFormerForImageClassification}
					    if is_torch_available()
					    else {}
					)

					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  SwiftFormerModelTester(self     )
									__a :						List[Any]			       =  ConfigTester(
									    self	,			config_class=_UpperCAmelCase	,			has_text_modality=_UpperCAmelCase	,			hidden_size=37	,			num_attention_heads=12	,			num_hidden_layers=12	,			)







					def  _lowerCamelCase		(						self     ):
									self.config_tester.run_common_tests()







					@unittest.skip(reason='''SwiftFormer does not use inputs_embeds'''     )
					def  _lowerCamelCase		(						self     ):
									pass







					def  _lowerCamelCase		(						self     ):
									__a       ,						__a :						Dict			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						List[str]			       =  model_class(_UpperCAmelCase     )
													__a :						int			       =  model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_UpperCAmelCase	,			nn.Linear     )     )







					def  _lowerCamelCase		(						self     ):
									__a       ,						__a :						str			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						int			       =  model_class(_UpperCAmelCase     )
													__a :						Optional[Any]			       =  inspect.signature(model.forward     )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													__a :						Union[str, Any]			       =  [*signature.parameters.keys()]

													__a :						Union[str, Any]			       =  ['''pixel_values''']
													self.assertListEqual(arg_names[:1]	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase     )







					@slow
					def  _lowerCamelCase		(						self     ):
									for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__a :						List[Any]			       =  SwiftFormerModel.from_pretrained(_UpperCAmelCase     )
													self.assertIsNotNone(_UpperCAmelCase     )







					@unittest.skip(reason='''SwiftFormer does not output attentions'''     )
					def  _lowerCamelCase		(						self     ):
									pass







					def  _lowerCamelCase		(						self     ):
									def check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
													__a :						Optional[Any]			       =  model_class(_UpperCAmelCase     )
													model.to(_UpperCAmelCase     )
													model.eval()

													with torch.no_grad():
																	__a :						List[Any]			       =  model(**self._prepare_for_class(_UpperCAmelCase	,			_UpperCAmelCase     )     )

													__a :						List[Any]			       =  outputs.hidden_states

													__a :						Any			       =  8
													self.assertEqual(len(_UpperCAmelCase     )	,			_UpperCAmelCase     )  # 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(_UpperCAmelCase     )     ):
																	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),
																	        ]     )	,			)

									__a       ,						__a :						List[Any]			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						Tuple			       =  True
													check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													__a :						Dict			       =  True

													check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									def _config_zero_init(_UpperCAmelCase     ):
													__a :						Any			       =  copy.deepcopy(_UpperCAmelCase     )
													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(_UpperCAmelCase	,			_UpperCAmelCase	,			1e-1_0     )
																	if isinstance(getattr(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )	,			_UpperCAmelCase     ):
																					__a :						Optional[int]			       =  _config_zero_init(getattr(_UpperCAmelCase	,			_UpperCAmelCase     )     )
																					setattr(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )
													return configs_no_init

									__a       ,						__a :						Union[str, Any]			       =  self.model_tester.prepare_config_and_inputs_for_common()

									__a :						Tuple			       =  _config_zero_init(_UpperCAmelCase     )
									for model_class in self.all_model_classes:
													__a :						List[str]			       =  model_class(config=_UpperCAmelCase     )
													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  _lowerCamelCase		(						self     ):
									pass






def     __A      (			)		->		Union[str, Any]:
				__a :						Optional[Any]			       =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image






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







					'''simple docstring'''




					@cached_property
					def  _lowerCamelCase		(						self     ):
									return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs'''     ) if is_vision_available() else None







					@slow
					def  _lowerCamelCase		(						self     ):
									__a :						int			       =  SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs'''     ).to(_UpperCAmelCase     )

									__a :						List[Any]			       =  self.default_image_processor
									__a :						List[Any]			       =  prepare_img()
									__a :						Optional[Any]			       =  image_processor(images=_UpperCAmelCase	,			return_tensors='''pt'''     ).to(_UpperCAmelCase     )

									# forward pass
									with torch.no_grad():
													__a :						Optional[Any]			       =  model(**_UpperCAmelCase     )

									# verify the logits
									__a :						Any			       =  torch.Size((1, 1000)     )
									self.assertEqual(outputs.logits.shape	,			_UpperCAmelCase     )

									__a :						str			       =  torch.tensor([[-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0]]     ).to(_UpperCAmelCase     )
									self.assertTrue(torch.allclose(outputs.logits[0, :3]	,			_UpperCAmelCase	,			atol=1e-4     )     )






"""simple docstring"""






import html

from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends


if is_bsa_available():
		import bsa
		from bsa import BeautifulSoup


A 			=  logging.get_logger(__name__)




class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					def __init__(						self	,			**_UpperCAmelCase     ):
									requires_backends(self	,			['''bs4''']     )
									super().__init__(**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase     ):
									__a :						Tuple			       =  []
									__a :						Dict			       =  []
									__a :						int			       =  element if element.name else element.parent
									for parent in child.parents:  # type: bs4.element.Tag
													__a :						Dict			       =  parent.find_all(child.name	,			recursive=_UpperCAmelCase     )
													xpath_tags.append(child.name     )
													xpath_subscripts.append(
													    0 if 1 == len(_UpperCAmelCase     ) else next(i for i, s in enumerate(_UpperCAmelCase	,			1     ) if s is child     )     )
													__a :						Any			       =  parent
									xpath_tags.reverse()
									xpath_subscripts.reverse()
									return xpath_tags, xpath_subscripts







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase     ):
									__a :						Dict			       =  BeautifulSoup(_UpperCAmelCase	,			'''html.parser'''     )

									__a :						Any			       =  []
									__a :						Dict			       =  []
									__a :						Optional[int]			       =  []

									for element in html_code.descendants:
													if type(_UpperCAmelCase     ) == bsa.element.NavigableString:
																	if type(element.parent     ) != bsa.element.Tag:
																					continue

																	__a :						Dict			       =  html.unescape(_UpperCAmelCase     ).strip()
																	if not text_in_this_tag:
																					continue

																	all_doc_strings.append(_UpperCAmelCase     )

																	__a       ,						__a :						List[Any]			       =  self.xpath_soup(_UpperCAmelCase     )
																	stringaxtag_seq.append(_UpperCAmelCase     )
																	stringaxsubs_seq.append(_UpperCAmelCase     )

									if len(_UpperCAmelCase     ) != len(_UpperCAmelCase     ):
													raise ValueError('''Number of doc strings and xtags does not correspond'''     )
									if len(_UpperCAmelCase     ) != len(_UpperCAmelCase     ):
													raise ValueError('''Number of doc strings and xsubs does not correspond'''     )

									return all_doc_strings, stringaxtag_seq, stringaxsubs_seq







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						List[str]			       =  ''''''
									for tagname, subs in zip(_UpperCAmelCase	,			_UpperCAmelCase     ):
													xpath += f"""/{tagname}"""
													if subs != 0:
																	xpath += f"""[{subs}]"""
									return xpath







					def __call__(						self	,			_UpperCAmelCase     ):
									__a :						Optional[Any]			       =  False

									# Check that strings has a valid type
									if isinstance(_UpperCAmelCase	,			_UpperCAmelCase     ):
													__a :						str			       =  True
									elif isinstance(_UpperCAmelCase	,			(list, tuple)     ):
													if len(_UpperCAmelCase     ) == 0 or isinstance(html_strings[0]	,			_UpperCAmelCase     ):
																	__a :						Optional[Any]			       =  True

									if not valid_strings:
													raise ValueError(
													    '''HTML strings must of type `str`, `List[str]` (batch of examples), '''
													    f"""but is of type {type(_UpperCAmelCase     )}."""     )

									__a :						List[str]			       =  bool(isinstance(_UpperCAmelCase	,			(list, tuple)     ) and (isinstance(html_strings[0]	,			_UpperCAmelCase     ))     )

									if not is_batched:
													__a :						List[Any]			       =  [html_strings]

									# Get nodes + xpaths
									__a :						Tuple			       =  []
									__a :						int			       =  []
									for html_string in html_strings:
													__a       ,						__a       ,						__a :						Any			       =  self.get_three_from_single(_UpperCAmelCase     )
													nodes.append(_UpperCAmelCase     )
													__a :						List[Any]			       =  []
													for node, tag_list, sub_list in zip(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
																	__a :						Optional[int]			       =  self.construct_xpath(_UpperCAmelCase	,			_UpperCAmelCase     )
																	xpath_strings.append(_UpperCAmelCase     )
													xpaths.append(_UpperCAmelCase     )

									# return as Dict
									__a :						int			       =  {'''nodes''': nodes, '''xpaths''': xpaths}
									__a :						Any			       =  BatchFeature(data=_UpperCAmelCase	,			tensor_type=_UpperCAmelCase     )

									return encoded_inputs