






'''simple docstring'''
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     _UpperCAmelCase  :




    def __init__(     self					:    int					,       a					:    List[Any]					,       a					:    List[Any]=1_3					,       a					:    List[str]=3_2					,       a					:    Optional[int]=2					,       a					:    Optional[int]=3					,       a					:    List[Any]=1_6					,       a					:    Union[str, Any]=[1, 2, 1]					,       a					:    int=[2, 2, 4]					,       a					:    List[str]=2					,       a					:    Optional[int]=2.0					,       a					:    Dict=True					,       a					:    str=0.0					,       a					:    int=0.0					,       a					:    Optional[Any]=0.1					,       a					:    List[str]="gelu"					,       a					:    Tuple=False					,       a					:    Optional[int]=True					,       a					:    Optional[Any]=0.02					,       a					:    Any=1e-5					,       a					:    Union[str, Any]=True					,       a					:    int=None					,       a					:    Union[str, Any]=True					,       a					:    Tuple=1_0					,       a					:    Optional[Any]=8					,       ):






       '''simple docstring'''






       lowercase_		:      Dict          =       parent
       lowercase_		:      List[str]          =       batch_size
       lowercase_		:      List[Any]          =       image_size
       lowercase_		:      Any          =       patch_size
       lowercase_		:      int          =       num_channels
       lowercase_		:      List[Any]          =       embed_dim
       lowercase_		:      Dict          =       depths
       lowercase_		:      Dict          =       num_heads
       lowercase_		:      Tuple          =       window_size
       lowercase_		:      Optional[int]          =       mlp_ratio
       lowercase_		:      int          =       qkv_bias
       lowercase_		:      str          =       hidden_dropout_prob
       lowercase_		:      str          =       attention_probs_dropout_prob
       lowercase_		:      Any          =       drop_path_rate
       lowercase_		:      str          =       hidden_act
       lowercase_		:      List[str]          =       use_absolute_embeddings
       lowercase_		:      int          =       patch_norm
       lowercase_		:      Any          =       layer_norm_eps
       lowercase_		:      Union[str, Any]          =       initializer_range
       lowercase_		:      Tuple          =       is_training
       lowercase_		:      List[str]          =       scope
       lowercase_		:      int          =       use_labels
       lowercase_		:      List[Any]          =       type_sequence_label_size
       lowercase_		:      Tuple          =       encoder_stride




    def 			lowerCAmelCase__			(     self					:    Tuple     ):






       '''simple docstring'''






       lowercase_		:      Dict          =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

       lowercase_		:      List[Any]          =       None
       if self.use_labels:
          lowercase_		:      List[Any]          =       ids_tensor([self.batch_size]					,       self.type_sequence_label_size     )

       lowercase_		:      Dict          =       self.get_config()

       return config, pixel_values, labels




    def 			lowerCAmelCase__			(     self					:    int     ):






       '''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 			lowerCAmelCase__			(     self					:    str					,       a					:    Union[str, Any]					,       a					:    Union[str, Any]					,       a					:    List[str]     ):






       '''simple docstring'''






       lowercase_		:      List[Any]          =       DonutSwinModel(config=a     )
       model.to(a     )
       model.eval()
       lowercase_		:      List[str]          =       model(a     )

       lowercase_		:      Tuple          =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths     ) - 1))
       lowercase_		:      List[Any]          =       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 			lowerCAmelCase__			(     self					:    int     ):






       '''simple docstring'''






       lowercase_		:      List[str]          =       self.prepare_config_and_inputs()
       (
           (
           lowercase_
       )      ,						(
           lowercase_
       )      ,						(
           lowercase_
       )      ,						
       )		:      Tuple          =       config_and_inputs
       lowercase_		:      Optional[int]          =       {"pixel_values": pixel_values}
       return config, inputs_dict


@require_torch
class     _UpperCAmelCase  (						snake_case			,   snake_case			,   unittest.TestCase     ):
    __lowerCamelCase:				Optional[int]						    =      (DonutSwinModel,) if is_torch_available() else ()
    __lowerCamelCase:				str						    =      {'feature-extraction': DonutSwinModel} if is_torch_available() else {}
    __lowerCamelCase:				Optional[int]						    =      True

    __lowerCamelCase:				Optional[int]						    =      False
    __lowerCamelCase:				Optional[int]						    =      False
    __lowerCamelCase:				Dict						    =      False




    def 			lowerCAmelCase__			(     self					:    List[Any]     ):






       '''simple docstring'''






       lowercase_		:      List[Any]          =       DonutSwinModelTester(self     )
       lowercase_		:      Union[str, Any]          =       ConfigTester(self					,       config_class=a					,       embed_dim=3_7     )




    def 			lowerCAmelCase__			(     self					:    int     ):






       '''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 			lowerCAmelCase__			(     self					:    Tuple     ):






       '''simple docstring'''






       return




    def 			lowerCAmelCase__			(     self					:    List[Any]     ):






       '''simple docstring'''






       lowercase_		:      Optional[Any]          =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a     )




    def 			lowerCAmelCase__			(     self					:    List[str]     ):






       '''simple docstring'''






       pass




    def 			lowerCAmelCase__			(     self					:    Dict     ):






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      Optional[int]          =       self.model_tester.prepare_config_and_inputs_for_common()

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




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






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      str          =       self.model_tester.prepare_config_and_inputs_for_common()

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

          lowercase_		:      List[Any]          =       ["pixel_values"]
          self.assertListEqual(arg_names[:1]					,       a     )




    def 			lowerCAmelCase__			(     self					:    Tuple     ):






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      Any          =       self.model_tester.prepare_config_and_inputs_for_common()
       lowercase_		:      Tuple          =       True

       for model_class in self.all_model_classes:
          lowercase_		:      str          =       True
          lowercase_		:      int          =       False
          lowercase_		:      Any          =       True
          lowercase_		:      Union[str, Any]          =       model_class(a     )
          model.to(a     )
          model.eval()
          with torch.no_grad():
             lowercase_		:      List[str]          =       model(**self._prepare_for_class(a					,       a     )     )
          lowercase_		:      List[str]          =       outputs.attentions
          lowercase_		:      str          =       len(self.model_tester.depths     )
          self.assertEqual(len(a     )					,       a     )

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

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

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

          if hasattr(self.model_tester					,       "num_hidden_states_types"     ):
             lowercase_		:      Union[str, Any]          =       self.model_tester.num_hidden_states_types
          else:
             # also another +1 for reshaped_hidden_states
             lowercase_		:      str          =       2
          self.assertEqual(out_len + added_hidden_states					,       len(a     )     )

          lowercase_		:      Dict          =       outputs.attentions

          self.assertEqual(len(a     )					,       a     )

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




    def 			lowerCAmelCase__			(     self					:    Optional[Any]					,       a					:    Optional[int]					,       a					:    List[Any]					,       a					:    str					,       a					:    List[str]     ):






       '''simple docstring'''






       lowercase_		:      Any          =       model_class(a     )
       model.to(a     )
       model.eval()

       with torch.no_grad():
          lowercase_		:      Optional[int]          =       model(**self._prepare_for_class(a					,       a     )     )

       lowercase_		:      Any          =       outputs.hidden_states

       lowercase_		:      List[str]          =       getattr(
           self.model_tester					,       "expected_num_hidden_layers"					,       len(self.model_tester.depths     ) + 1     )
       self.assertEqual(len(a     )					,       a     )

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

       lowercase_		:      Optional[int]          =       (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]					,       )

       lowercase_		:      Tuple          =       outputs.reshaped_hidden_states
       self.assertEqual(len(a     )					,       a     )

       lowercase_      ,						lowercase_      ,						lowercase_      ,						lowercase_		:      Optional[int]          =       reshaped_hidden_states[0].shape
       lowercase_		:      Tuple          =       (
           reshaped_hidden_states[0].view(a					,       a					,       height * width     ).permute(0					,       2					,       1     )
       )
       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:]     )					,       [num_patches, self.model_tester.embed_dim]					,       )




    def 			lowerCAmelCase__			(     self					:    Dict     ):






       '''simple docstring'''






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

       lowercase_		:      Optional[int]          =       (
           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:
          lowercase_		:      Any          =       True
          self.check_hidden_states_output(a					,       a					,       a					,       a     )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowercase_		:      Optional[Any]          =       True

          self.check_hidden_states_output(a					,       a					,       a					,       a     )




    def 			lowerCAmelCase__			(     self					:    int     ):






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      int          =       self.model_tester.prepare_config_and_inputs_for_common()
       lowercase_		:      Any          =       3

       lowercase_		:      int          =       (
           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)
       )
       lowercase_		:      int          =       (
           config.patch_size
           if isinstance(config.patch_size					,       collections.abc.Iterable     )
           else (config.patch_size, config.patch_size)
       )

       lowercase_		:      str          =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       lowercase_		:      List[str]          =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
          lowercase_		:      Any          =       True
          self.check_hidden_states_output(a					,       a					,       a					,       (padded_height, padded_width)     )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowercase_		:      List[Any]          =       True
          self.check_hidden_states_output(a					,       a					,       a					,       (padded_height, padded_width)     )




    @slow
    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






       for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase_		:      Optional[Any]          =       DonutSwinModel.from_pretrained(a     )
          self.assertIsNotNone(a     )





    def 			lowerCAmelCase__			(     self					:    Tuple     ):






       '''simple docstring'''






       lowercase_      ,						lowercase_		:      str          =       self.model_tester.prepare_config_and_inputs_for_common()

       lowercase_		:      List[str]          =       _config_zero_init(a     )
       for model_class in self.all_model_classes:
          lowercase_		:      List[str]          =       model_class(config=a     )
          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"""					,       )












'''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 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase  ,						_UpperCamelCase							):


   """simple docstring"""




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

      lowercase_		:      List[str]          =       BASE_URL.format(_UpperCamelCase  ,						_UpperCamelCase							)
      lowercase_		:      Union[str, Any]          =       get(_UpperCamelCase							)

      # Is the response ok?
      response.raise_for_status()

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

      # This list will store the name and price.
      lowercase_		:      List[str]          =       []

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

            # Get price of the drug.
            lowercase_		:      List[str]          =       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}""")




