


import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase					:       List[str]			    =     logging.get_logger(__name__)



def UpperCamelCase_				(				__a			,				__a=False      )	->   str:
      a__	:  Optional[int]     =   []
      for i in range(config.num_hidden_layers      ):
            # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
            rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''')      )
            rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''')      )
            rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''')      )
            rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''')      )
            rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''')      )
            rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''')      )
            rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''')      )
            rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''')      )
            rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''')      )
            rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''')      )

      # projection layer + position embeddings
      rename_keys.extend(
          [
              ("cls_token", "vit.embeddings.cls_token"),
              ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
              ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
              ("pos_embed", "vit.embeddings.position_embeddings"),
          ]      )

      if base_model:
            # layernorm + pooler
            rename_keys.extend(
                [
                    ("norm.weight", "layernorm.weight"),
                    ("norm.bias", "layernorm.bias"),
                ]      )

            # if just the base model, we should remove "vit" from all keys that start with "vit"
            a__	:  Any     =   [(pair[0], pair[1][4:]) if pair[1].startswith("vit"      ) else pair for pair in rename_keys]
      else:
            # layernorm + classification head
            rename_keys.extend(
                [
                    ("norm.weight", "vit.layernorm.weight"),
                    ("norm.bias", "vit.layernorm.bias"),
                    ("head.weight", "classifier.weight"),
                    ("head.bias", "classifier.bias"),
                ]      )

      return rename_keys



def UpperCamelCase_				(				__a			,				__a			,				__a=False      )	->   List[str]:
      for i in range(config.num_hidden_layers      ):
            if base_model:
                  a__	:  Union[str, Any]     =   ""
            else:
                  a__	:  str     =   "vit."
            # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
            a__	:  Tuple     =   state_dict.pop(f'''blocks.{i}.attn.qkv.weight'''      )
            a__	:  Any     =   state_dict.pop(f'''blocks.{i}.attn.qkv.bias'''      )
            # next, add query, keys and values (in that order) to the state dict
            a__	:  List[str]     =   in_proj_weight[
                : config.hidden_size, :
            ]
            a__	:  List[Any]     =   in_proj_bias[: config.hidden_size]
            a__	:  Dict     =   in_proj_weight[
                config.hidden_size : config.hidden_size * 2, :
            ]
            a__	:  Optional[int]     =   in_proj_bias[
                config.hidden_size : config.hidden_size * 2
            ]
            a__	:  str     =   in_proj_weight[
                -config.hidden_size :, :
            ]
            a__	:  Union[str, Any]     =   in_proj_bias[-config.hidden_size :]



def UpperCamelCase_				(				__a      )	->   Union[str, Any]:
      a__	:  Union[str, Any]     =   ["head.weight", "head.bias"]
      for k in ignore_keys:
            state_dict.pop(__a			,				__a      )



def UpperCamelCase_				(				__a			,				__a			,				__a      )	->   Union[str, Any]:
      a__	:  Optional[int]     =   dct.pop(__a      )
      a__	:  str     =   val



def UpperCamelCase_				(				)	->   Dict:
      a__	:  Tuple     =   "http://images.cocodataset.org/val2017/000000039769.jpg"
      a__	:  Dict     =   Image.open(requests.get(__a			,				stream=__a      ).raw      )
      return im



@torch.no_grad()
def UpperCamelCase_				(				__a			,				__a			,				__a=True      )	->   str:
      a__	:  Tuple     =   ViTConfig()
      # patch_size
      if model_name[-1] == "8":
            a__	:  Any     =   8
      # set labels if required
      if not base_model:
            a__	:  str     =   1_000
            a__	:  Tuple     =   "huggingface/label-files"
            a__	:  int     =   "imagenet-1k-id2label.json"
            a__	:  Dict     =   json.load(open(hf_hub_download(__a			,				__a			,				repo_type="dataset"      )			,				"r"      )      )
            a__	:  List[Any]     =   {int(__a      ): v for k, v in idalabel.items()}
            a__	:  Tuple     =   idalabel
            a__	:  Any     =   {v: k for k, v in idalabel.items()}
      # size of the architecture
      if model_name in ["dino_vits8", "dino_vits16"]:
            a__	:  Dict     =   384
            a__	:  Tuple     =   1_536
            a__	:  str     =   12
            a__	:  Union[str, Any]     =   6

      # load original model from torch hub
      a__	:  List[Any]     =   torch.hub.load("facebookresearch/dino:main"			,				__a      )
      original_model.eval()

      # load state_dict of original model, remove and rename some keys
      a__	:  Dict     =   original_model.state_dict()
      if base_model:
            remove_classification_head_(__a      )
      a__	:  Any     =   create_rename_keys(__a			,				base_model=__a      )
      for src, dest in rename_keys:
            rename_key(__a			,				__a			,				__a      )
      read_in_q_k_v(__a			,				__a			,				__a      )

      # load HuggingFace model
      if base_model:
            a__	:  List[str]     =   ViTModel(__a			,				add_pooling_layer=__a      ).eval()
      else:
            a__	:  List[str]     =   ViTForImageClassification(__a      ).eval()
      model.load_state_dict(__a      )

      # Check outputs on an image, prepared by ViTImageProcessor
      a__	:  Optional[int]     =   ViTImageProcessor()
      a__	:  List[Any]     =   image_processor(images=prepare_img()			,				return_tensors="pt"      )
      a__	:  List[str]     =   encoding["pixel_values"]
      a__	:  List[Any]     =   model(__a      )

      if base_model:
            a__	:  List[Any]     =   original_model(__a      )
            assert torch.allclose(__a			,				outputs.last_hidden_state[:, 0, :]			,				atol=1e-1      )
      else:
            a__	:  List[str]     =   original_model(__a      )
            assert logits.shape == outputs.logits.shape
            assert torch.allclose(__a			,				outputs.logits			,				atol=1e-3      )

      Path(__a      ).mkdir(exist_ok=__a      )
      print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''      )
      model.save_pretrained(__a      )
      print(f'''Saving image processor to {pytorch_dump_folder_path}'''      )
      image_processor.save_pretrained(__a      )


if __name__ == "__main__":
    UpperCamelCase					:       Any			    =     argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--model_name""",
        default="""dino_vitb16""",
        type=str,
        help="""Name of the model trained with DINO you'd like to convert.""",
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
    )
    parser.add_argument(
        """--base_model""",
        action="""store_true""",
        help="""Whether to only convert the base model (no projection head weights).""",
    )

    parser.set_defaults(base_model=True)
    UpperCamelCase					:       int			    =     parser.parse_args()
    convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)






import requests
from bsa import BeautifulSoup

def 	SCREAMING_SNAKE_CASE_							(	_snake_case	:str = "AAPL"				)  ->     str:
   _A      =       F'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}'''
   _A      =       BeautifulSoup(requests.get(_snake_case				).text	,   '''html.parser'''				)
   _A      =       '''My(6px) Pos(r) smartphone_Mt(6px)'''
   return soup.find('''div'''	,   class_=class_				).find('''span'''				).text


if __name__ == "__main__":
   for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
      print(f'Current {symbol:<4} stock price is {stock_price(symbol):>8}')



