


import argparse
import re

import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    SamConfig,
    SamImageProcessor,
    SamModel,
    SamProcessor,
    SamVisionConfig,
)


UpperCAmelCase_      : List[Any]  					=       {
    'iou_prediction_head.layers.0': 'iou_prediction_head.proj_in',
    'iou_prediction_head.layers.1': 'iou_prediction_head.layers.0',
    'iou_prediction_head.layers.2': 'iou_prediction_head.proj_out',
    'mask_decoder.output_upscaling.0': 'mask_decoder.upscale_conv1',
    'mask_decoder.output_upscaling.1': 'mask_decoder.upscale_layer_norm',
    'mask_decoder.output_upscaling.3': 'mask_decoder.upscale_conv2',
    'mask_downscaling.0': 'mask_embed.conv1',
    'mask_downscaling.1': 'mask_embed.layer_norm1',
    'mask_downscaling.3': 'mask_embed.conv2',
    'mask_downscaling.4': 'mask_embed.layer_norm2',
    'mask_downscaling.6': 'mask_embed.conv3',
    'point_embeddings': 'point_embed',
    'pe_layer.positional_encoding_gaussian_matrix': 'shared_embedding.positional_embedding',
    'image_encoder': 'vision_encoder',
    'neck.0': 'neck.conv1',
    'neck.1': 'neck.layer_norm1',
    'neck.2': 'neck.conv2',
    'neck.3': 'neck.layer_norm2',
    'patch_embed.proj': 'patch_embed.projection',
    '.norm': '.layer_norm',
    'blocks': 'layers',
}







def        SCREAMING_SNAKE_CASE_						(			__A :			List[str]				)	->		Any:

       """simple docstring"""

       a_					:		Optional[int]							=  {}
       state_dict.pop('pixel_mean'  ,    __A				)
       state_dict.pop('pixel_std'  ,    __A				)

       a_					:		Dict							=  R'.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*'

       for key, value in state_dict.items():
              for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
                     if key_to_modify in key:
                            a_					:		Tuple							=  key.replace(__A  ,    __A				)

              if re.match(__A  ,    __A				):
                     a_					:		int							=  int(re.match(__A  ,    __A				).group(2				)				)
                     if layer_nb == 0:
                            a_					:		Dict							=  key.replace('layers.0'  ,    'proj_in'				)
                     elif layer_nb == 1:
                            a_					:		List[str]							=  key.replace('layers.1'  ,    'layers.0'				)
                     elif layer_nb == 2:
                            a_					:		int							=  key.replace('layers.2'  ,    'proj_out'				)

              a_					:		List[Any]							=  value

       a_					:		Optional[int]							=  model_state_dict[
           'prompt_encoder.shared_embedding.positional_embedding'
       ]

       return model_state_dict







def        SCREAMING_SNAKE_CASE_						(			__A :			Any  ,    __A :			int  ,    __A :			List[Any]  ,    __A :			Tuple="ybelkada/segment-anything"				)	->		str:

       """simple docstring"""

       a_					:		Tuple							=  hf_hub_download(__A  ,    F"""checkpoints/{model_name}.pth"""				)

       if "sam_vit_b" in model_name:
              a_					:		Optional[int]							=  SamConfig()
       elif "sam_vit_l" in model_name:
              a_					:		Union[str, Any]							=  SamVisionConfig(
                  hidden_size=10_24  ,    num_hidden_layers=24  ,    num_attention_heads=16  ,    global_attn_indexes=[5, 11, 17, 23]  ,    )

              a_					:		Optional[int]							=  SamConfig(
                  vision_config=__A  ,    )
       elif "sam_vit_h" in model_name:
              a_					:		List[str]							=  SamVisionConfig(
                  hidden_size=12_80  ,    num_hidden_layers=32  ,    num_attention_heads=16  ,    global_attn_indexes=[7, 15, 23, 31]  ,    )

              a_					:		int							=  SamConfig(
                  vision_config=__A  ,    )

       a_					:		str							=  torch.load(__A  ,    map_location='cpu'				)
       a_					:		Tuple							=  replace_keys(__A				)

       a_					:		Optional[Any]							=  SamImageProcessor()

       a_					:		Any							=  SamProcessor(image_processor=__A				)
       a_					:		List[Any]							=  SamModel(__A				)

       hf_model.load_state_dict(__A				)
       a_					:		Dict							=  hf_model.to('cuda'				)

       a_					:		Optional[Any]							=  'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'
       a_					:		List[Any]							=  Image.open(requests.get(__A  ,    stream=__A				).raw				).convert('RGB'				)

       a_					:		Dict							=  [[[4_00, 6_50]]]
       a_					:		str							=  [[1]]

       a_					:		Optional[Any]							=  processor(images=np.array(__A				)  ,    return_tensors='pt'				).to('cuda'				)

       with torch.no_grad():
              a_					:		str							=  hf_model(**__A				)
       a_					:		List[str]							=  output.iou_scores.squeeze()

       if model_name == "sam_vit_h_4b8939":
              assert scores[-1].item() == 0.579890251159668

              a_					:		List[str]							=  processor(
                  images=np.array(__A				)  ,    input_points=__A  ,    input_labels=__A  ,    return_tensors='pt'				).to('cuda'				)

              with torch.no_grad():
                     a_					:		Optional[Any]							=  hf_model(**__A				)
              a_					:		str							=  output.iou_scores.squeeze()

              assert scores[-1].item() == 0.9712603092193604

              a_					:		Any							=  ((75, 2_75, 17_25, 8_50),)

              a_					:		Optional[int]							=  processor(images=np.array(__A				)  ,    input_boxes=__A  ,    return_tensors='pt'				).to('cuda'				)

              with torch.no_grad():
                     a_					:		str							=  hf_model(**__A				)
              a_					:		Dict							=  output.iou_scores.squeeze()

              assert scores[-1].item() == 0.8686015605926514

              # Test with 2 points and 1 image.
              a_					:		Union[str, Any]							=  [[[4_00, 6_50], [8_00, 6_50]]]
              a_					:		Optional[int]							=  [[1, 1]]

              a_					:		Any							=  processor(
                  images=np.array(__A				)  ,    input_points=__A  ,    input_labels=__A  ,    return_tensors='pt'				).to('cuda'				)

              with torch.no_grad():
                     a_					:		Optional[int]							=  hf_model(**__A				)
              a_					:		List[str]							=  output.iou_scores.squeeze()

              assert scores[-1].item() == 0.9936047792434692


if __name__ == "__main__":
   UpperCAmelCase_      : Tuple  					=       argparse.ArgumentParser()
   UpperCAmelCase_      : Optional[int]  					=       ['sam_vit_b_01ec64', 'sam_vit_h_4b8939', 'sam_vit_l_0b3195']
   parser.add_argument(
       '--model_name',
       default='sam_vit_h_4b8939',
       choices=choices,
       type=str,
       help='Path to hf config.json of model to convert',
   )
   parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
   parser.add_argument(
       '--push_to_hub',
       action='store_true',
       help='Whether to push the model and processor to the hub after converting',
   )
   parser.add_argument(
       '--model_hub_id',
       default='ybelkada/segment-anything',
       choices=choices,
       type=str,
       help='Path to hf config.json of model to convert',
   )

   UpperCAmelCase_      : Union[str, Any]  					=       parser.parse_args()

   convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)






from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

UpperCAmelCase_      : Any  					=       {'UserAgent': UserAgent().random}







def        SCREAMING_SNAKE_CASE_						(			__A :			Optional[int]				)	->		dict:

       """simple docstring"""

       a_					:		Tuple							=  script.contents[0]
       a_					:		int							=  json.loads(data[data.find('{"config"'				) : -1]				)
       return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class  SCREAMING_SNAKE_CASE__  :
      def __init__(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Dict     )		->			Optional[Any]:
             a_					:		Tuple							=  F"""https://www.instagram.com/{username}/"""
             a_					:		Optional[Any]							=  self.get_json()
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			dict:
             a_					:		Any							=  requests.get(self.url     ,							headers=SCREAMING_SNAKE_CASE__     ).text
             a_					:		Dict							=  BeautifulSoup(SCREAMING_SNAKE_CASE__     ,							'html.parser'     ).find_all('script'     )
             try:
                    return extract_user_profile(scripts[4]     )
             except (json.decoder.JSONDecodeError, KeyError):
                    return extract_user_profile(scripts[3]     )
      def __repr__(       self				:       Union[str, Any]     )		->			str:
             return F"""{self.__class__.__name__}('{self.username}')"""
      def __str__(       self				:       Optional[int]     )		->			str:
             return F"""{self.fullname} ({self.username}) is {self.biography}"""
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			str:
             return self.user_data["username"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			str:
             return self.user_data["full_name"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			str:
             return self.user_data["biography"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			str:
             return self.user_data["business_email"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     )		->			str:
             return self.user_data["external_url"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Dict     )		->			int:
             return self.user_data["edge_followed_by"]["count"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			int:
             return self.user_data["edge_follow"]["count"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			int:
             return self.user_data["edge_owner_to_timeline_media"]["count"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			str:
             return self.user_data["profile_pic_url_hd"]
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     )		->			bool:
             return self.user_data["is_verified"]

      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			bool:
             return self.user_data["is_private"]







def        SCREAMING_SNAKE_CASE_						(			__A :			str = "github"				)	->		None:

       """simple docstring"""

       import os

       if os.environ.get('CI'				):
              return  # test failing on GitHub Actions
       a_					:		int							=  InstagramUser(__A				)
       assert instagram_user.user_data
       assert isinstance(instagram_user.user_data  ,    __A				)
       assert instagram_user.username == username
       if username != "github":
              return
       assert instagram_user.fullname == "GitHub"
       assert instagram_user.biography == "Built for developers."
       assert instagram_user.number_of_posts > 1_50
       assert instagram_user.number_of_followers > 12_00_00
       assert instagram_user.number_of_followings > 15
       assert instagram_user.email == "support@github.com"
       assert instagram_user.website == "https://github.com/readme"
       assert instagram_user.profile_picture_url.startswith('https://instagram.'				)
       assert instagram_user.is_verified is True
       assert instagram_user.is_private is False


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   UpperCAmelCase_      : Union[str, Any]  					=       InstagramUser('github')
   print(instagram_user)
   print(F'{instagram_user.number_of_posts = }')
   print(F'{instagram_user.number_of_followers = }')
   print(F'{instagram_user.number_of_followings = }')
   print(F'{instagram_user.email = }')
   print(F'{instagram_user.website = }')
   print(F'{instagram_user.profile_picture_url = }')
   print(F'{instagram_user.is_verified = }')
   print(F'{instagram_user.is_private = }')


