
import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_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 SwinaSRForImageSuperResolution, SwinaSRModel
							from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
							from PIL import Image

							from transformers import SwinaSRImageProcessor



class       a_   :






			def __init__(			self							, __UpperCamelCase							, __UpperCamelCase=13							, __UpperCamelCase=32							, __UpperCamelCase=1							, __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=False							, __UpperCamelCase=2							, ):
									_lowercase									=				parent
									_lowercase									=				batch_size
									_lowercase									=				image_size
									_lowercase									=				patch_size
									_lowercase									=				num_channels
									_lowercase									=				embed_dim
									_lowercase									=				depths
									_lowercase									=				num_heads
									_lowercase									=				window_size
									_lowercase									=				mlp_ratio
									_lowercase									=				qkv_bias
									_lowercase									=				hidden_dropout_prob
									_lowercase									=				attention_probs_dropout_prob
									_lowercase									=				drop_path_rate
									_lowercase									=				hidden_act
									_lowercase									=				use_absolute_embeddings
									_lowercase									=				patch_norm
									_lowercase									=				layer_norm_eps
									_lowercase									=				initializer_range
									_lowercase									=				is_training
									_lowercase									=				scope
									_lowercase									=				use_labels
									_lowercase									=				upscale

									# here we set some attributes to make tests pass
									_lowercase									=				len(__UpperCamelCase     )
									_lowercase									=				embed_dim
									_lowercase									=				(image_size // patch_size) ** 2






			def       UpperCamelCase_							(			self     ):
									_lowercase									=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

									_lowercase									=				self.get_config()

									return config, pixel_values, labels






			def       UpperCamelCase_							(			self     ):
									return SwinaSRConfig(
									    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							, upscale=self.upscale							, )






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase							, __UpperCamelCase     ):
									_lowercase									=				SwinaSRModel(config=__UpperCamelCase     )
									model.to(__UpperCamelCase     )
									model.eval()
									_lowercase									=				model(__UpperCamelCase     )

									self.parent.assertEqual(
									    result.last_hidden_state.shape							, (self.batch_size, self.embed_dim, self.image_size, self.image_size)     )






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase							, __UpperCamelCase     ):
									_lowercase									=				SwinaSRForImageSuperResolution(__UpperCamelCase     )
									model.to(__UpperCamelCase     )
									model.eval()
									_lowercase									=				model(__UpperCamelCase     )

									_lowercase									=				self.image_size * self.upscale
									self.parent.assertEqual(
									    result.reconstruction.shape							, (self.batch_size, self.num_channels, expected_image_size, expected_image_size)     )






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







@require_torch
class       a_   ( _a				, _a				, unittest.TestCase						):
			a  : Optional[int]				      =       (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
			a  : Dict				      =       {'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

			a  : Tuple				      =       False
			a  : int				      =       False
			a  : Optional[Any]				      =       False
			a  : Any				      =       False
			a  : List[str]				      =       False






			def       UpperCamelCase_							(			self     ):
									_lowercase									=				SwinaSRModelTester(self     )
									_lowercase									=				ConfigTester(self							, config_class=__UpperCamelCase							, embed_dim=37     )






			def       UpperCamelCase_							(			self     ):
									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     ):
									_lowercase									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__UpperCamelCase     )






			def       UpperCamelCase_							(			self     ):
									_lowercase									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_super_resolution(*__UpperCamelCase     )






			@unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""     )
			def       UpperCamelCase_							(			self     ):
									pass






			@unittest.skip(reason="""Swin2SR does not use inputs_embeds"""     )
			def       UpperCamelCase_							(			self     ):
									pass






			@unittest.skip(reason="""Swin2SR does not support training yet"""     )
			def       UpperCamelCase_							(			self     ):
									pass






			@unittest.skip(reason="""Swin2SR does not support training yet"""     )
			def       UpperCamelCase_							(			self     ):
									pass






			def       UpperCamelCase_							(			self     ):
									_lowercase					,	_lowercase									=				self.model_tester.prepare_config_and_inputs_for_common()

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






			def       UpperCamelCase_							(			self     ):
									_lowercase					,	_lowercase									=				self.model_tester.prepare_config_and_inputs_for_common()

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

															_lowercase									=				["""pixel_values"""]
															self.assertListEqual(arg_names[:1]							, __UpperCamelCase     )






			@slow
			def       UpperCamelCase_							(			self     ):
									for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_lowercase									=				SwinaSRModel.from_pretrained(__UpperCamelCase     )
															self.assertIsNotNone(__UpperCamelCase     )






			def       UpperCamelCase_							(			self     ):
									_lowercase					,	_lowercase									=				self.model_tester.prepare_config_and_inputs_for_common()

									_lowercase									=				_config_zero_init(__UpperCamelCase     )
									for model_class in self.all_model_classes:
															_lowercase									=				model_class(config=__UpperCamelCase     )
															for name, param in model.named_parameters():
																					if "logit_scale" in name:
																											continue
																					if 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"""							, )






			def       UpperCamelCase_							(			self     ):
									_lowercase					,	_lowercase									=				self.model_tester.prepare_config_and_inputs_for_common()
									_lowercase									=				True

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

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

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

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

															self.assertEqual(out_len + 1							, len(__UpperCamelCase     )     )

															_lowercase									=				outputs.attentions

															self.assertEqual(len(__UpperCamelCase     )							, __UpperCamelCase     )

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







@require_vision
@require_torch
@slow
class       a_   ( unittest.TestCase						):






			def       UpperCamelCase_							(			self     ):
									_lowercase									=				SwinaSRImageProcessor()
									_lowercase									=				SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""     ).to(__UpperCamelCase     )

									_lowercase									=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
									_lowercase									=				processor(images=__UpperCamelCase							, return_tensors="""pt"""     ).to(__UpperCamelCase     )

									# forward pass
									with torch.no_grad():
															_lowercase									=				model(**__UpperCamelCase     )

									# verify the logits
									_lowercase									=				torch.Size([1, 3, 976, 1_296]     )
									self.assertEqual(outputs.reconstruction.shape							, __UpperCamelCase     )
									_lowercase									=				torch.tensor(
									    [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]     ).to(__UpperCamelCase     )
									self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]							, __UpperCamelCase							, atol=1E-4     )     )

from urllib.error import HTTPError

from bsa import BeautifulSoup
from requests import exceptions, get

A		:   Union[str, Any]         =    '''https://www.wellrx.com/prescriptions/{0}/{1}/?freshSearch=true'''




def   UpperCamelCase__     (    SCREAMING_SNAKE_CASE_  :  str		,      SCREAMING_SNAKE_CASE_  :  str					)     ->    list | None:

						try:
												# Has user provided both inputs?
												if not drug_name or not zip_code:
																		return None

												_lowercase									=				BASE_URL.format(SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_					)
												_lowercase									=				get(SCREAMING_SNAKE_CASE_					)

												# Is the response ok?
												response.raise_for_status()

												# Scrape the data using bs4
												_lowercase									=				BeautifulSoup(response.text		,      """html.parser"""					)

												# This list will store the name and price.
												_lowercase									=				[]

												# Fetch all the grids that contains the items.
												_lowercase									=				soup.find_all("""div"""		,      {"""class""": """grid-x pharmCard"""}					)
												if grid_list and len(SCREAMING_SNAKE_CASE_					) > 0:
																		for grid in grid_list:
																								# Get the pharmacy price.
																								_lowercase									=				grid.find("""p"""		,      {"""class""": """list-title"""}					).text

																								# Get price of the drug.
																								_lowercase									=				grid.find("""span"""		,      {"""p""", """price price-large"""}					).text

																								pharmacy_price_list.append(
																								    {
																								        """pharmacy_name""": pharmacy_name,
																								        """price""": price,
																								    }					)

												return pharmacy_price_list

						except (HTTPError, exceptions.RequestException, ValueError):
												return None


if __name__ == "__main__":
		# Enter a drug name and a zip code
		A		:   Union[str, Any]         =    input('''Enter drug name: ''').strip()
		A		:   Dict         =    input('''Enter zip code: ''').strip()

		A		:   list | None         =    fetch_pharmacy_and_price_list(
		    drug_name, zip_code
		)

		if pharmacy_price_list:
				print(F'\nSearch results for {drug_name} at location {zip_code}:')
				for pharmacy_price in pharmacy_price_list:
						A		:   List[str]         =    pharmacy_price['''pharmacy_name''']
						A		:   Dict         =    pharmacy_price['''price''']

						print(F'Pharmacy: {name} Price: {price}')
		else:
				print(F'No results found for {drug_name}')