


'''simple docstring'''







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,
)


lowerCAmelCase     :  Dict											=    {
    """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       lowercase					(_A       ):







       """simple docstring"""







       _lowerCAmelCase     :				Any       =							{}
       state_dict.pop('pixel_mean' ,    _A       )
       state_dict.pop('pixel_std' ,    _A       )

       _lowerCAmelCase     :				Tuple       =							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:
                            _lowerCAmelCase     :				int       =							key.replace(_A ,    _A       )

              if re.match(_A ,    _A       ):
                     _lowerCAmelCase     :				str       =							int(re.match(_A ,    _A       ).group(2       )       )
                     if layer_nb == 0:
                            _lowerCAmelCase     :				Tuple       =							key.replace('layers.0' ,    'proj_in'       )
                     elif layer_nb == 1:
                            _lowerCAmelCase     :				Tuple       =							key.replace('layers.1' ,    'layers.0'       )
                     elif layer_nb == 2:
                            _lowerCAmelCase     :				str       =							key.replace('layers.2' ,    'proj_out'       )

              _lowerCAmelCase     :				Optional[Any]       =							value

       _lowerCAmelCase     :				Tuple       =							model_state_dict[
           'prompt_encoder.shared_embedding.positional_embedding'
       ]

       return model_state_dict






def       lowercase					(_A ,    _A ,    _A ,    _A="ybelkada/segment-anything"       ):







       """simple docstring"""







       _lowerCAmelCase     :				str       =							hf_hub_download(_A ,    f'checkpoints/{model_name}.pth'       )

       if "sam_vit_b" in model_name:
              _lowerCAmelCase     :				int       =							SamConfig()
       elif "sam_vit_l" in model_name:
              _lowerCAmelCase     :				Optional[int]       =							SamVisionConfig(
                  hidden_size=1_0_2_4 ,    num_hidden_layers=2_4 ,    num_attention_heads=1_6 ,    global_attn_indexes=[5, 1_1, 1_7, 2_3] ,    )

              _lowerCAmelCase     :				Union[str, Any]       =							SamConfig(
                  vision_config=_A ,    )
       elif "sam_vit_h" in model_name:
              _lowerCAmelCase     :				int       =							SamVisionConfig(
                  hidden_size=1_2_8_0 ,    num_hidden_layers=3_2 ,    num_attention_heads=1_6 ,    global_attn_indexes=[7, 1_5, 2_3, 3_1] ,    )

              _lowerCAmelCase     :				Any       =							SamConfig(
                  vision_config=_A ,    )

       _lowerCAmelCase     :				str       =							torch.load(_A ,    map_location='cpu'       )
       _lowerCAmelCase     :				Dict       =							replace_keys(_A       )

       _lowerCAmelCase     :				Optional[int]       =							SamImageProcessor()

       _lowerCAmelCase     :				Tuple       =							SamProcessor(image_processor=_A       )
       _lowerCAmelCase     :				Optional[Any]       =							SamModel(_A       )

       hf_model.load_state_dict(_A       )
       _lowerCAmelCase     :				Optional[Any]       =							hf_model.to('cuda'       )

       _lowerCAmelCase     :				int       =							'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'
       _lowerCAmelCase     :				Union[str, Any]       =							Image.open(requests.get(_A ,    stream=_A       ).raw       ).convert('RGB'       )

       _lowerCAmelCase     :				Any       =							[[[4_0_0, 6_5_0]]]
       _lowerCAmelCase     :				str       =							[[1]]

       _lowerCAmelCase     :				List[Any]       =							processor(images=np.array(_A       ) ,    return_tensors='pt'       ).to('cuda'       )

       with torch.no_grad():
              _lowerCAmelCase     :				Optional[int]       =							hf_model(**_A       )
       _lowerCAmelCase     :				Optional[Any]       =							output.iou_scores.squeeze()

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

              _lowerCAmelCase     :				str       =							processor(
                  images=np.array(_A       ) ,    input_points=_A ,    input_labels=_A ,    return_tensors='pt'       ).to('cuda'       )

              with torch.no_grad():
                     _lowerCAmelCase     :				int       =							hf_model(**_A       )
              _lowerCAmelCase     :				Optional[Any]       =							output.iou_scores.squeeze()

              assert scores[-1].item() == 0.9_712_603_092_193_604

              _lowerCAmelCase     :				Dict       =							((7_5, 2_7_5, 1_7_2_5, 8_5_0),)

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

              with torch.no_grad():
                     _lowerCAmelCase     :				Optional[Any]       =							hf_model(**_A       )
              _lowerCAmelCase     :				Tuple       =							output.iou_scores.squeeze()

              assert scores[-1].item() == 0.8_686_015_605_926_514

              # Test with 2 points and 1 image.
              _lowerCAmelCase     :				str       =							[[[4_0_0, 6_5_0], [8_0_0, 6_5_0]]]
              _lowerCAmelCase     :				Union[str, Any]       =							[[1, 1]]

              _lowerCAmelCase     :				Union[str, Any]       =							processor(
                  images=np.array(_A       ) ,    input_points=_A ,    input_labels=_A ,    return_tensors='pt'       ).to('cuda'       )

              with torch.no_grad():
                     _lowerCAmelCase     :				Union[str, Any]       =							hf_model(**_A       )
              _lowerCAmelCase     :				str       =							output.iou_scores.squeeze()

              assert scores[-1].item() == 0.9_936_047_792_434_692


if __name__ == "__main__":
       lowerCAmelCase     :  str											=    argparse.ArgumentParser()
       lowerCAmelCase     :  Tuple											=    ["""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""",
       )

       lowerCAmelCase     :  int											=    parser.parse_args()

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





'''simple docstring'''







import argparse
from collections import defaultdict

import yaml


lowerCAmelCase     :  Dict											=    """docs/source/en/_toctree.yml"""






def       lowercase					(_A       ):







       """simple docstring"""







       _lowerCAmelCase     :				Optional[int]       =							defaultdict(_A       )
       _lowerCAmelCase     :				Tuple       =							[]
       _lowerCAmelCase     :				Dict       =							[]
       for doc in doc_list:
              if "local" in doc:
                     counts[doc["local"]] += 1

              if doc["title"].lower() == "overview":
                     overview_doc.append({'local': doc['local'], 'title': doc['title']}       )
              else:
                     new_doc_list.append(_A       )

       _lowerCAmelCase     :				str       =							new_doc_list
       _lowerCAmelCase     :				List[Any]       =							[key for key, value in counts.items() if value > 1]

       _lowerCAmelCase     :				List[str]       =							[]
       for duplicate_key in duplicates:
              _lowerCAmelCase     :				Any       =							list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key}       )
              if len(_A       ) > 1:
                     raise ValueError(
                         f'{duplicate_key} is present several times in the documentation table of content at '
                         '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
                         'others.'       )
              # Only add this once
              new_doc.append({'local': duplicate_key, 'title': titles[0]}       )

       # Add none duplicate-keys
       new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1]       )
       _lowerCAmelCase     :				Any       =							sorted(_A ,    key=lambda _A       : s["title"].lower()       )

       # "overview" gets special treatment and is always first
       if len(_A       ) > 1:
              raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.'       )

       overview_doc.extend(_A       )

       # Sort
       return overview_doc






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Union[str, Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Tuple       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				str       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Dict       =							0
       while api_doc[scheduler_idx]["title"] != "Schedulers":
              scheduler_idx += 1

       _lowerCAmelCase     :				Optional[int]       =							api_doc[scheduler_idx]['sections']
       _lowerCAmelCase     :				Any       =							clean_doc_toc(_A       )

       _lowerCAmelCase     :				int       =							False
       if new_scheduler_doc != scheduler_doc:
              _lowerCAmelCase     :				str       =							True
              if overwrite:
                     _lowerCAmelCase     :				int       =							new_scheduler_doc

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				Dict       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Optional[Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Optional[Any]       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				Union[str, Any]       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Optional[int]       =							0
       while api_doc[pipeline_idx]["title"] != "Pipelines":
              pipeline_idx += 1

       _lowerCAmelCase     :				List[Any]       =							False
       _lowerCAmelCase     :				List[Any]       =							api_doc[pipeline_idx]['sections']
       _lowerCAmelCase     :				Union[str, Any]       =							[]

       # sort sub pipeline docs
       for pipeline_doc in pipeline_docs:
              if "section" in pipeline_doc:
                     _lowerCAmelCase     :				Tuple       =							pipeline_doc['section']
                     _lowerCAmelCase     :				Optional[int]       =							clean_doc_toc(_A       )
                     if overwrite:
                            _lowerCAmelCase     :				str       =							new_sub_pipeline_doc
              new_pipeline_docs.append(_A       )

       # sort overall pipeline doc
       _lowerCAmelCase     :				str       =							clean_doc_toc(_A       )

       if new_pipeline_docs != pipeline_docs:
              _lowerCAmelCase     :				Any       =							True
              if overwrite:
                     _lowerCAmelCase     :				Optional[int]       =							new_pipeline_docs

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				str       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )


if __name__ == "__main__":
       lowerCAmelCase     :  Tuple											=    argparse.ArgumentParser()
       parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
       lowerCAmelCase     :  List[Any]											=    parser.parse_args()

       check_scheduler_doc(args.fix_and_overwrite)
       check_pipeline_doc(args.fix_and_overwrite)

