




'''simple docstring'''




import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
from transformers.models.auto import get_values
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


if is_torch_available():
							import torch
							from torch import nn

							from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
							from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from transformers import VivitImageProcessor






class 			UpperCamelCase_   :







						"""simple docstring"""


						def __init__(   self					:				Dict							,       _lowerCamelCase					:				Optional[int]							,       _lowerCamelCase					:				Union[str, Any]=2							,       _lowerCamelCase					:				Optional[Any]=True							,       _lowerCamelCase					:				List[Any]=True							,       _lowerCamelCase					:				List[str]=10							,       _lowerCamelCase					:				List[str]=10							,       _lowerCamelCase					:				Any=8							,       _lowerCamelCase					:				Union[str, Any]=[2, 4, 4]							,       _lowerCamelCase					:				Union[str, Any]=3							,       _lowerCamelCase					:				Union[str, Any]=768							,       _lowerCamelCase					:				List[str]=5							,       _lowerCamelCase					:				Optional[Any]=4							,       _lowerCamelCase					:				List[str]=37							,       _lowerCamelCase					:				Optional[int]="gelu_fast"							,       _lowerCamelCase					:				Optional[Any]=0.0							,       _lowerCamelCase					:				str=0.0							,       _lowerCamelCase					:				List[str]=0.02							,       _lowerCamelCase					:				str=1E-06							,       _lowerCamelCase					:				int=True							,       _lowerCamelCase					:				Tuple=None							,       ):





											"""simple docstring"""







											A_       :   List[Any]       =							parent
											A_       :   Any       =							batch_size
											A_       :   Optional[int]       =							is_training
											A_       :   int       =							use_labels
											A_       :   Optional[Any]       =							num_labels
											A_       :   int       =							image_size
											A_       :   List[Any]       =							num_frames
											A_       :   Union[str, Any]       =							tubelet_size
											A_       :   List[Any]       =							num_channels
											A_       :   Union[str, Any]       =							hidden_size
											A_       :   List[Any]       =							num_hidden_layers
											A_       :   Tuple       =							num_attention_heads
											A_       :   Dict       =							intermediate_size
											A_       :   List[str]       =							hidden_act
											A_       :   Union[str, Any]       =							hidden_dropout_prob
											A_       :   str       =							attention_probs_dropout_prob
											A_       :   Optional[int]       =							initializer_range
											A_       :   int       =							layer_norm_eps
											A_       :   int       =							qkv_bias
											A_       :   Tuple       =							scope

											A_       :   Union[str, Any]       =							(
											    (self.image_size // self.tubelet_size[2])
											    * (self.image_size // self.tubelet_size[1])
											    * (self.num_frames // self.tubelet_size[0])
											) + 1  # CLS token







						def 					_a			(   self					:				Union[str, Any]			):





											"""simple docstring"""







											A_       :   int       =							floats_tensor(
											    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]			)

											A_       :   str       =							None
											if self.use_labels:
																A_       :   List[str]       =							ids_tensor([self.batch_size]							,       self.num_labels			)

											A_       :   str       =							self.get_config()

											return config, pixel_values, labels







						def 					_a			(   self					:				List[Any]			):





											"""simple docstring"""







											A_       :   Union[str, Any]       =							VivitConfig(
											    num_frames=self.num_frames							,       image_size=self.image_size							,       tubelet_size=self.tubelet_size							,       num_channels=self.num_channels							,       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							,       initializer_range=self.initializer_range							,       layer_norm_eps=self.layer_norm_eps							,       qkv_bias=self.qkv_bias							,       )
											A_       :   Optional[Any]       =							self.num_labels
											return config







						def 					_a			(   self					:				Union[str, Any]							,       _lowerCamelCase					:				Optional[int]							,       _lowerCamelCase					:				Dict							,       _lowerCamelCase					:				str			):





											"""simple docstring"""







											A_       :   int       =							VivitModel(config=_lowerCamelCase			)
											model.to(_lowerCamelCase			)
											model.eval()
											A_       :   int       =							model(_lowerCamelCase			)
											self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, self.seq_length, self.hidden_size)			)







						def 					_a			(   self					:				str							,       _lowerCamelCase					:				str							,       _lowerCamelCase					:				List[str]							,       _lowerCamelCase					:				Dict			):





											"""simple docstring"""







											A_       :   str       =							VivitForVideoClassification(_lowerCamelCase			)
											model.to(_lowerCamelCase			)
											model.eval()

											A_       :   Any       =							model(_lowerCamelCase			)

											# verify the logits shape
											A_       :   Any       =							torch.Size((self.batch_size, self.num_labels)			)
											self.parent.assertEqual(result.logits.shape							,       _lowerCamelCase			)







						def 					_a			(   self					:				Optional[Any]			):





											"""simple docstring"""







											A_       :   Tuple       =							self.prepare_config_and_inputs()
											A_       ,A_       ,A_       :   Dict       =							config_and_inputs
											A_       :   Dict       =							{'''pixel_values''': pixel_values}
											return config, inputs_dict






@require_torch
class 			UpperCamelCase_   (a__,					unittest.TestCase   ):







						"""simple docstring"""


						_lowerCAmelCase			  =    (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

						_lowerCAmelCase			  =    False
						_lowerCAmelCase			  =    False
						_lowerCAmelCase			  =    False
						_lowerCAmelCase			  =    False







						def 					_a			(   self					:				Union[str, Any]			):





											"""simple docstring"""







											A_       :   Optional[Any]       =							VivitModelTester(self			)
											A_       :   int       =							ConfigTester(self							,       config_class=_lowerCamelCase							,       has_text_modality=_lowerCamelCase							,       hidden_size=37			)







						def 					_a			(   self					:				Tuple							,       _lowerCamelCase					:				Any							,       _lowerCamelCase					:				Any							,       _lowerCamelCase					:				Any=False			):





											"""simple docstring"""







											A_       :   Union[str, Any]       =							copy.deepcopy(_lowerCamelCase			)

											if return_labels:
																if model_class in get_values(_lowerCamelCase			):
																					A_       :   Tuple       =							torch.zeros(
																					    self.model_tester.batch_size							,       dtype=torch.long							,       device=_lowerCamelCase			)

											return inputs_dict







						def 					_a			(   self					:				str			):





											"""simple docstring"""







											self.config_tester.run_common_tests()







						@unittest.skip(reason='''Vivit does not use inputs_embeds'''			)
						def 					_a			(   self					:				Dict			):





											"""simple docstring"""







											pass







						def 					_a			(   self					:				List[Any]			):





											"""simple docstring"""







											A_       ,A_       :   List[str]       =							self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																A_       :   List[str]       =							model_class(_lowerCamelCase			)
																self.assertIsInstance(model.get_input_embeddings()							,       (nn.Module)			)
																A_       :   List[Any]       =							model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(_lowerCamelCase							,       nn.Linear			)			)







						def 					_a			(   self					:				str			):





											"""simple docstring"""







											A_       ,A_       :   Tuple       =							self.model_tester.prepare_config_and_inputs_for_common()

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

																A_       :   List[Any]       =							['''pixel_values''', '''head_mask''']
																self.assertListEqual(arg_names[:2]							,       _lowerCamelCase			)







						def 					_a			(   self					:				Dict			):





											"""simple docstring"""







											A_       :   int       =							self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCamelCase			)







						def 					_a			(   self					:				str			):





											"""simple docstring"""







											A_       :   Dict       =							self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_video_classification(*_lowerCamelCase			)







						@slow
						def 					_a			(   self					:				Any			):





											"""simple docstring"""







											for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																A_       :   Optional[Any]       =							VivitModel.from_pretrained(_lowerCamelCase			)
																self.assertIsNotNone(_lowerCamelCase			)







						def 					_a			(   self					:				int			):





											"""simple docstring"""







											A_       ,A_       :   Union[str, Any]       =							self.model_tester.prepare_config_and_inputs_for_common()
											A_       :   Dict       =							True

											for model_class in self.all_model_classes:
																A_       :   Tuple       =							self.model_tester.seq_length

																A_       :   str       =							True
																A_       :   Any       =							False
																A_       :   Tuple       =							True
																A_       :   Any       =							model_class(_lowerCamelCase			)
																model.to(_lowerCamelCase			)
																model.eval()
																with torch.no_grad():
																					A_       :   List[Any]       =							model(**self._prepare_for_class(_lowerCamelCase							,       _lowerCamelCase			)			)
																A_       :   Tuple       =							outputs.attentions
																self.assertEqual(len(_lowerCamelCase			)							,       self.model_tester.num_hidden_layers			)

																# check that output_attentions also work using config
																del inputs_dict["output_attentions"]
																A_       :   Optional[int]       =							True
																A_       :   Dict       =							model_class(_lowerCamelCase			)
																model.to(_lowerCamelCase			)
																model.eval()
																with torch.no_grad():
																					A_       :   Optional[Any]       =							model(**self._prepare_for_class(_lowerCamelCase							,       _lowerCamelCase			)			)
																A_       :   Optional[int]       =							outputs.attentions
																self.assertEqual(len(_lowerCamelCase			)							,       self.model_tester.num_hidden_layers			)

																self.assertListEqual(
																    list(attentions[0].shape[-3:]			)							,       [self.model_tester.num_attention_heads, seq_len, seq_len]							,       )
																A_       :   Union[str, Any]       =							len(_lowerCamelCase			)

																# Check attention is always last and order is fine
																A_       :   str       =							True
																A_       :   Optional[Any]       =							True
																A_       :   Tuple       =							model_class(_lowerCamelCase			)
																model.to(_lowerCamelCase			)
																model.eval()
																with torch.no_grad():
																					A_       :   List[Any]       =							model(**self._prepare_for_class(_lowerCamelCase							,       _lowerCamelCase			)			)

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

																A_       :   Optional[Any]       =							outputs.attentions

																self.assertEqual(len(_lowerCamelCase			)							,       self.model_tester.num_hidden_layers			)

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







						def 					_a			(   self					:				str			):





											"""simple docstring"""







											def check_hidden_states_output(_lowerCamelCase					:				Dict							,       _lowerCamelCase					:				Any							,       _lowerCamelCase					:				List[Any]			):
																A_       :   int       =							model_class(_lowerCamelCase			)
																model.to(_lowerCamelCase			)
																model.eval()

																with torch.no_grad():
																					A_       :   Tuple       =							model(**self._prepare_for_class(_lowerCamelCase							,       _lowerCamelCase			)			)

																A_       :   str       =							outputs.hidden_states
																A_       :   int       =							self.model_tester.num_hidden_layers + 1
																self.assertEqual(len(_lowerCamelCase			)							,       _lowerCamelCase			)

																A_       :   str       =							self.model_tester.seq_length

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

											A_       ,A_       :   Dict       =							self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																A_       :   int       =							True
																check_hidden_states_output(_lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase			)

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																A_       :   Union[str, Any]       =							True

																check_hidden_states_output(_lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase			)







						@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
						def 					_a			(   self					:				List[Any]			):





											"""simple docstring"""







											pass






def   snake_case__			(       )      ->      Tuple:
					A_       :   int       =							hf_hub_download(
					    repo_id='''hf-internal-testing/spaghetti-video'''	,						filename='''eating_spaghetti_32_frames.npy'''	,						repo_type='''dataset'''	)
					A_       :   List[str]       =							np.load(_snake_case	)
					return list(_snake_case	)






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







						"""simple docstring"""


						@cached_property
						def 					_a			(   self					:				str			):





											"""simple docstring"""







											return VivitImageProcessor() if is_vision_available() else None







						@slow
						def 					_a			(   self					:				Optional[int]			):





											"""simple docstring"""







											A_       :   Dict       =							VivitForVideoClassification.from_pretrained('''google/vivit-b-16x2-kinetics400'''			).to(_lowerCamelCase			)

											A_       :   int       =							self.default_image_processor
											A_       :   Optional[int]       =							prepare_video()
											A_       :   Optional[Any]       =							image_processor(_lowerCamelCase							,       return_tensors='''pt'''			).to(_lowerCamelCase			)

											# forward pass
											with torch.no_grad():
																A_       :   List[Any]       =							model(**_lowerCamelCase			)

											# verify the logits
											A_       :   Any       =							torch.Size((1, 400)			)
											self.assertEqual(outputs.logits.shape							,       _lowerCamelCase			)

											# taken from original model
											A_       :   List[str]       =							torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]			).to(_lowerCamelCase			)

											self.assertTrue(torch.allclose(outputs.logits[0, :5]							,       _lowerCamelCase							,       atol=1E-4			)			)











"""simple docstring"""







from urllib.error import HTTPError

from bsa import BeautifulSoup
from requests import exceptions, get

_UpperCamelCase     			=  """https://www.wellrx.com/prescriptions/{0}/{1}/?freshSearch=true"""

def _a (		_snake_case      ,       _snake_case							):







      """simple docstring"""






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

            UpperCAmelCase							=       BASE_URL.format(_snake_case      ,       _snake_case							)
            UpperCAmelCase							=       get(_snake_case							)

            # Is the response ok?
            response.raise_for_status()

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

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

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

                        # Get price of the drug.
                        UpperCAmelCase							=       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
  _UpperCamelCase     			=  input("""Enter drug name: """).strip()
  _UpperCamelCase     			=  input("""Enter zip code: """).strip()

  _UpperCamelCase     			=  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:
      _UpperCamelCase     			=  pharmacy_price["""pharmacy_name"""]
      _UpperCamelCase     			=  pharmacy_price["""price"""]

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



