





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             =							{
    '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		(      SCREAMING_SNAKE_CASE		:Dict   )      ->   Tuple:
 __lowerCAmelCase					:	Union[str, Any]      =       {}
 state_dict.pop("""pixel_mean"""   ,   SCREAMING_SNAKE_CASE   )
 state_dict.pop("""pixel_std"""   ,   SCREAMING_SNAKE_CASE   )

 __lowerCAmelCase					:	Optional[Any]      =       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					:	Dict      =       key.replace(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

  if re.match(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ):
   __lowerCAmelCase					:	Any      =       int(re.match(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ).group(2   )   )
   if layer_nb == 0:
    __lowerCAmelCase					:	Optional[Any]      =       key.replace("""layers.0"""   ,   """proj_in"""   )
   elif layer_nb == 1:
    __lowerCAmelCase					:	int      =       key.replace("""layers.1"""   ,   """layers.0"""   )
   elif layer_nb == 2:
    __lowerCAmelCase					:	List[str]      =       key.replace("""layers.2"""   ,   """proj_out"""   )

  __lowerCAmelCase					:	Optional[Any]      =       value

 __lowerCAmelCase					:	str      =       model_state_dict[
     """prompt_encoder.shared_embedding.positional_embedding"""
 ]

 return model_state_dict






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:List[str]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:List[str]="ybelkada/segment-anything"   )      ->   int:
 __lowerCAmelCase					:	Dict      =       hf_hub_download(SCREAMING_SNAKE_CASE   ,   F'''checkpoints/{model_name}.pth'''   )

 if "sam_vit_b" in model_name:
  __lowerCAmelCase					:	Optional[int]      =       SamConfig()
 elif "sam_vit_l" in model_name:
  __lowerCAmelCase					:	int      =       SamVisionConfig(
      hidden_size=1_024   ,   num_hidden_layers=24   ,   num_attention_heads=16   ,   global_attn_indexes=[5, 11, 17, 23]   ,   )

  __lowerCAmelCase					:	List[str]      =       SamConfig(
      vision_config=SCREAMING_SNAKE_CASE   ,   )
 elif "sam_vit_h" in model_name:
  __lowerCAmelCase					:	List[Any]      =       SamVisionConfig(
      hidden_size=1_280   ,   num_hidden_layers=32   ,   num_attention_heads=16   ,   global_attn_indexes=[7, 15, 23, 31]   ,   )

  __lowerCAmelCase					:	str      =       SamConfig(
      vision_config=SCREAMING_SNAKE_CASE   ,   )

 __lowerCAmelCase					:	Union[str, Any]      =       torch.load(SCREAMING_SNAKE_CASE   ,   map_location="""cpu"""   )
 __lowerCAmelCase					:	Optional[Any]      =       replace_keys(SCREAMING_SNAKE_CASE   )

 __lowerCAmelCase					:	List[str]      =       SamImageProcessor()

 __lowerCAmelCase					:	List[Any]      =       SamProcessor(image_processor=SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	Any      =       SamModel(SCREAMING_SNAKE_CASE   )

 hf_model.load_state_dict(SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	List[str]      =       hf_model.to("""cuda"""   )

 __lowerCAmelCase					:	Dict      =       """https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"""
 __lowerCAmelCase					:	Optional[int]      =       Image.open(requests.get(SCREAMING_SNAKE_CASE   ,   stream=SCREAMING_SNAKE_CASE   ).raw   ).convert("""RGB"""   )

 __lowerCAmelCase					:	Tuple      =       [[[400, 650]]]
 __lowerCAmelCase					:	List[str]      =       [[1]]

 __lowerCAmelCase					:	Optional[int]      =       processor(images=np.array(SCREAMING_SNAKE_CASE   )   ,   return_tensors="""pt"""   ).to("""cuda"""   )

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

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

  __lowerCAmelCase					:	Optional[int]      =       processor(
      images=np.array(SCREAMING_SNAKE_CASE   )   ,   input_points=SCREAMING_SNAKE_CASE   ,   input_labels=SCREAMING_SNAKE_CASE   ,   return_tensors="""pt"""   ).to("""cuda"""   )

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

  assert scores[-1].item() == 0.97_12_60_30_92_19_36_04

  __lowerCAmelCase					:	Dict      =       ((75, 275, 1_725, 850),)

  __lowerCAmelCase					:	str      =       processor(images=np.array(SCREAMING_SNAKE_CASE   )   ,   input_boxes=SCREAMING_SNAKE_CASE   ,   return_tensors="""pt"""   ).to("""cuda"""   )

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

  assert scores[-1].item() == 0.86_86_01_56_05_92_65_14

  # Test with 2 points and 1 image.
  __lowerCAmelCase					:	List[Any]      =       [[[400, 650], [800, 650]]]
  __lowerCAmelCase					:	Optional[Any]      =       [[1, 1]]

  __lowerCAmelCase					:	Union[str, Any]      =       processor(
      images=np.array(SCREAMING_SNAKE_CASE   )   ,   input_points=SCREAMING_SNAKE_CASE   ,   input_labels=SCREAMING_SNAKE_CASE   ,   return_tensors="""pt"""   ).to("""cuda"""   )

  with torch.no_grad():
   __lowerCAmelCase					:	Tuple      =       hf_model(**SCREAMING_SNAKE_CASE   )
  __lowerCAmelCase					:	Any      =       output.iou_scores.squeeze()

  assert scores[-1].item() == 0.99_36_04_77_92_43_46_92


if __name__ == "__main__":
      _UpperCAmelCase             =							argparse.ArgumentParser()
      _UpperCAmelCase             =							['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             =							parser.parse_args()

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






import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


_UpperCAmelCase             =							'\\n@inproceedings{snover-etal-2006-study,\n    title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n    author = "Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John",\n    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n    month = aug # " 8-12",\n    year = "2006",\n    address = "Cambridge, Massachusetts, USA",\n    publisher = "Association for Machine Translation in the Americas",\n    url = "https://aclanthology.org/2006.amta-papers.25",\n    pages = "223--231",\n}\n@inproceedings{post-2018-call,\n    title = "A Call for Clarity in Reporting {BLEU} Scores",\n    author = "Post, Matt",\n    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n    month = oct,\n    year = "2018",\n    address = "Belgium, Brussels",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/W18-6319",\n    pages = "186--191",\n}\n'

_UpperCAmelCase             =							'\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n'

_UpperCAmelCase             =							'\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n    \'num_edits\' (int): The cumulative number of edits\n    \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?",\n        ...                     "What did the TER metric user say to the developer?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n        ...             ["Your jokes are...", "...TERrible"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n    Example 2:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n    Example 3:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n    Example 4:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n    Example 5:\n        >>> predictions = ["does this sentence match??",\n        ...                    "what about this sentence?",\n        ...                    "What did the TER metric user say to the developer?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n        ...             ["Your jokes are...", "...TERrible"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,_KWARGS_DESCRIPTION						)
class        snake_case_    (		datasets.Metric						):






  def 				UpperCAmelCase__						(							self			:					Tuple      )->str:






   '''simple docstring'''

   if version.parse(scb.__version__      ) < version.parse("""1.4.12"""      ):
    raise ImportWarning(
        """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
        """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""      )
   return datasets.MetricInfo(
       description=_DESCRIPTION       ,  citation=_CITATION       ,  homepage="""http://www.cs.umd.edu/~snover/tercom/"""       ,  inputs_description=_KWARGS_DESCRIPTION       ,  features=datasets.Features(
           {
               """predictions""": datasets.Value("""string"""       ,  id="""sequence"""      ),
               """references""": datasets.Sequence(datasets.Value("""string"""       ,  id="""sequence"""      )       ,  id="""references"""      ),
           }      )       ,  codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""]       ,  reference_urls=[
           """https://github.com/jhclark/tercom""",
       ]       ,  )






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					List[Any]       ,  _snake_case			:					int       ,  _snake_case			:					bool = False       ,  _snake_case			:					bool = False       ,  _snake_case			:					bool = False       ,  _snake_case			:					bool = False       ,  )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       len(references[0]      )
   if any(len(_snake_case      ) != references_per_prediction for refs in references      ):
    raise ValueError("""Sacrebleu requires the same number of references for each prediction"""      )
   __lowerCAmelCase					:	str      =       [[refs[i] for refs in references] for i in range(_snake_case      )]

   __lowerCAmelCase					:	Tuple      =       TER(
       normalized=_snake_case       ,  no_punct=_snake_case       ,  asian_support=_snake_case       ,  case_sensitive=_snake_case       ,  )
   __lowerCAmelCase					:	List[Any]      =       sb_ter.corpus_score(_snake_case       ,  _snake_case      )

   return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}