import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


__lowerCamelCase					:	List[str]       =  re.compile(R'''\b(a|an|the)\b''', re.UNICODE)

__lowerCamelCase					:	Dict       =  None




def       _snake_case	(   ):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0."	)
		parser.add_argument("data_file"   , metavar="data.json"   , help="Input data JSON file."	)
		parser.add_argument("pred_file"   , metavar="pred.json"   , help="Model predictions."	)
		parser.add_argument(
		    "--out-file"   , "-o"   , metavar="eval.json"   , help="Write accuracy metrics to file (default is stdout)."	)
		parser.add_argument(
		    "--na-prob-file"   , "-n"   , metavar="na_prob.json"   , help="Model estimates of probability of no answer."	)
		parser.add_argument(
		    "--na-prob-thresh"   , "-t"   , type=lowerCAmelCase   , default=1.0   , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)."   , )
		parser.add_argument(
		    "--out-image-dir"   , "-p"   , metavar="out_images"   , default=lowerCAmelCase   , help="Save precision-recall curves to directory."	)
		parser.add_argument("--verbose"   , "-v"   , action="store_true"	)
		if len(sys.argv	) == 1:
				parser.print_help()
				sys.exit(1	)
		return parser.parse_args()




def       _snake_case	(   lowerCAmelCase							:   Tuple	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		str				      =    {}
		for article in dataset:
				for p in article["paragraphs"]:
						for qa in p["qas"]:
								SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    bool(qa["answers"]["text"]	)
		return qid_to_has_ans




def       _snake_case	(   lowerCAmelCase							:   Optional[Any]	):
		"""simple docstring"""







		def remove_articles(lowerCAmelCase							:   List[Any]	):
				return ARTICLES_REGEX.sub(" "   , lowerCAmelCase	)

		def white_space_fix(lowerCAmelCase							:   Optional[Any]	):
				return " ".join(text.split()	)

		def remove_punc(lowerCAmelCase							:   List[str]	):
				SCREAMING_SNAKE_CASE_  :		List[str]				      =    set(string.punctuation	)
				return "".join(ch for ch in text if ch not in exclude	)

		def lower(lowerCAmelCase							:   List[Any]	):
				return text.lower()

		return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase	)	)	)	)




def       _snake_case	(   lowerCAmelCase							:   str	):
		"""simple docstring"""







		if not s:
				return []
		return normalize_answer(lowerCAmelCase	).split()




def       _snake_case	(   lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   int	):
		"""simple docstring"""







		return int(normalize_answer(lowerCAmelCase	) == normalize_answer(lowerCAmelCase	)	)




def       _snake_case	(   lowerCAmelCase							:   Union[str, Any]   , lowerCAmelCase							:   Any	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Tuple				      =    get_tokens(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    get_tokens(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		str				      =    collections.Counter(lowerCAmelCase	) & collections.Counter(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    sum(common.values()	)
		if len(lowerCAmelCase	) == 0 or len(lowerCAmelCase	) == 0:
				# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
				return int(gold_toks == pred_toks	)
		if num_same == 0:
				return 0
		SCREAMING_SNAKE_CASE_  :		str				      =    1.0 * num_same / len(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    1.0 * num_same / len(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    (2 * precision * recall) / (precision + recall)
		return fa




def       _snake_case	(   lowerCAmelCase							:   int   , lowerCAmelCase							:   List[str]	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Any				      =    {}
		SCREAMING_SNAKE_CASE_  :		Dict				      =    {}
		for article in dataset:
				for p in article["paragraphs"]:
						for qa in p["qas"]:
								SCREAMING_SNAKE_CASE_  :		Tuple				      =    qa["id"]
								SCREAMING_SNAKE_CASE_  :		Dict				      =    [t for t in qa["answers"]["text"] if normalize_answer(lowerCAmelCase	)]
								if not gold_answers:
										# For unanswerable questions, only correct answer is empty string
										SCREAMING_SNAKE_CASE_  :		Any				      =    [""]
								if qid not in preds:
										print(f'Missing prediction for {qid}'	)
										continue
								SCREAMING_SNAKE_CASE_  :		str				      =    preds[qid]
								# Take max over all gold answers
								SCREAMING_SNAKE_CASE_  :		str				      =    max(compute_exact(lowerCAmelCase   , lowerCAmelCase	) for a in gold_answers	)
								SCREAMING_SNAKE_CASE_  :		int				      =    max(compute_fa(lowerCAmelCase   , lowerCAmelCase	) for a in gold_answers	)
		return exact_scores, fa_scores




def       _snake_case	(   lowerCAmelCase							:   List[str]   , lowerCAmelCase							:   Dict   , lowerCAmelCase							:   List[str]   , lowerCAmelCase							:   Dict	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    {}
		for qid, s in scores.items():
				SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    na_probs[qid] > na_prob_thresh
				if pred_na:
						SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    float(not qid_to_has_ans[qid]	)
				else:
						SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    s
		return new_scores




def       _snake_case	(   lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   Dict   , lowerCAmelCase							:   Optional[Any]=None	):
		"""simple docstring"""







		if not qid_list:
				SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    len(lowerCAmelCase	)
				return collections.OrderedDict(
				    [
				        ("exact", 100.0 * sum(exact_scores.values()	) / total),
				        ("f1", 100.0 * sum(fa_scores.values()	) / total),
				        ("total", total),
				    ]	)
		else:
				SCREAMING_SNAKE_CASE_  :		Any				      =    len(lowerCAmelCase	)
				return collections.OrderedDict(
				    [
				        ("exact", 100.0 * sum(exact_scores[k] for k in qid_list	) / total),
				        ("f1", 100.0 * sum(fa_scores[k] for k in qid_list	) / total),
				        ("total", total),
				    ]	)




def       _snake_case	(   lowerCAmelCase							:   Union[str, Any]   , lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   List[Any]	):
		"""simple docstring"""







		for k in new_eval:
				SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    new_eval[k]




def       _snake_case	(   lowerCAmelCase							:   str   , lowerCAmelCase							:   Any   , lowerCAmelCase							:   str   , lowerCAmelCase							:   Union[str, Any]	):
		"""simple docstring"""







		plt.step(lowerCAmelCase   , lowerCAmelCase   , color="b"   , alpha=0.2   , where="post"	)
		plt.fill_between(lowerCAmelCase   , lowerCAmelCase   , step="post"   , alpha=0.2   , color="b"	)
		plt.xlabel("Recall"	)
		plt.ylabel("Precision"	)
		plt.xlim([0.0, 1.05]	)
		plt.ylim([0.0, 1.05]	)
		plt.title(lowerCAmelCase	)
		plt.savefig(lowerCAmelCase	)
		plt.clf()




def       _snake_case	(   lowerCAmelCase							:   Optional[Any]   , lowerCAmelCase							:   int   , lowerCAmelCase							:   int   , lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   List[Any]=None   , lowerCAmelCase							:   Union[str, Any]=None	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    sorted(lowerCAmelCase   , key=lambda lowerCAmelCase	: na_probs[k]	)
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    0.0
		SCREAMING_SNAKE_CASE_  :		int				      =    1.0
		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    0.0
		SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    [1.0]
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    [0.0]
		SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    0.0
		for i, qid in enumerate(lowerCAmelCase	):
				if qid_to_has_ans[qid]:
						true_pos += scores[qid]
				SCREAMING_SNAKE_CASE_  :		Tuple				      =    true_pos / float(i + 1	)
				SCREAMING_SNAKE_CASE_  :		List[str]				      =    true_pos / float(lowerCAmelCase	)
				if i == len(lowerCAmelCase	) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
						# i.e., if we can put a threshold after this point
						avg_prec += cur_p * (cur_r - recalls[-1])
						precisions.append(lowerCAmelCase	)
						recalls.append(lowerCAmelCase	)
		if out_image:
				plot_pr_curve(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase	)
		return {"ap": 100.0 * avg_prec}




def       _snake_case	(   lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   Any   , lowerCAmelCase							:   List[Any]   , lowerCAmelCase							:   str   , lowerCAmelCase							:   Optional[Any]   , lowerCAmelCase							:   Optional[int]	):
		"""simple docstring"""







		if out_image_dir and not os.path.exists(lowerCAmelCase	):
				os.makedirs(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		int				      =    sum(1 for v in qid_to_has_ans.values() if v	)
		if num_true_pos == 0:
				return
		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    make_precision_recall_eval(
		    lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , out_image=os.path.join(lowerCAmelCase   , "pr_exact.png"	)   , title="Precision-Recall curve for Exact Match score"   , )
		SCREAMING_SNAKE_CASE_  :		int				      =    make_precision_recall_eval(
		    lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , out_image=os.path.join(lowerCAmelCase   , "pr_f1.png"	)   , title="Precision-Recall curve for F1 score"   , )
		SCREAMING_SNAKE_CASE_  :		Dict				      =    {k: float(lowerCAmelCase	) for k, v in qid_to_has_ans.items()}
		SCREAMING_SNAKE_CASE_  :		Any				      =    make_precision_recall_eval(
		    lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , out_image=os.path.join(lowerCAmelCase   , "pr_oracle.png"	)   , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"   , )
		merge_eval(lowerCAmelCase   , lowerCAmelCase   , "pr_exact"	)
		merge_eval(lowerCAmelCase   , lowerCAmelCase   , "pr_f1"	)
		merge_eval(lowerCAmelCase   , lowerCAmelCase   , "pr_oracle"	)




def       _snake_case	(   lowerCAmelCase							:   Optional[int]   , lowerCAmelCase							:   Tuple   , lowerCAmelCase							:   Optional[Any]   , lowerCAmelCase							:   List[Any]	):
		"""simple docstring"""







		if not qid_list:
				return
		SCREAMING_SNAKE_CASE_  :		int				      =    [na_probs[k] for k in qid_list]
		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    np.ones_like(lowerCAmelCase	) / float(len(lowerCAmelCase	)	)
		plt.hist(lowerCAmelCase   , weights=lowerCAmelCase   , bins=2_0   , range=(0.0, 1.0)	)
		plt.xlabel("Model probability of no-answer"	)
		plt.ylabel("Proportion of dataset"	)
		plt.title(f'Histogram of no-answer probability: {name}'	)
		plt.savefig(os.path.join(lowerCAmelCase   , f'na_prob_hist_{name}.png'	)	)
		plt.clf()




def       _snake_case	(   lowerCAmelCase							:   Dict   , lowerCAmelCase							:   Union[str, Any]   , lowerCAmelCase							:   int   , lowerCAmelCase							:   Tuple	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]	)
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    num_no_ans
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    cur_score
		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    0.0
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    sorted(lowerCAmelCase   , key=lambda lowerCAmelCase	: na_probs[k]	)
		for i, qid in enumerate(lowerCAmelCase	):
				if qid not in scores:
						continue
				if qid_to_has_ans[qid]:
						SCREAMING_SNAKE_CASE_  :		Tuple				      =    scores[qid]
				else:
						if preds[qid]:
								SCREAMING_SNAKE_CASE_  :		int				      =    -1
						else:
								SCREAMING_SNAKE_CASE_  :		str				      =    0
				cur_score += diff
				if cur_score > best_score:
						SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    cur_score
						SCREAMING_SNAKE_CASE_  :		str				      =    na_probs[qid]
		return 100.0 * best_score / len(lowerCAmelCase	), best_thresh




def       _snake_case	(   lowerCAmelCase							:   Any   , lowerCAmelCase							:   str   , lowerCAmelCase							:   List[str]   , lowerCAmelCase							:   str   , lowerCAmelCase							:   Union[str, Any]   , lowerCAmelCase							:   Any	):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Dict				      =    find_best_thresh(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    find_best_thresh(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		List[Any]				      =    best_exact
		SCREAMING_SNAKE_CASE_  :		Dict				      =    exact_thresh
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    best_fa
		SCREAMING_SNAKE_CASE_  :		int				      =    fa_thresh




def       _snake_case	(   ):
		"""simple docstring"""







		with open(OPTS.data_file	) as f:
				SCREAMING_SNAKE_CASE_  :		int				      =    json.load(lowerCAmelCase	)
				SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    dataset_json["data"]
		with open(OPTS.pred_file	) as f:
				SCREAMING_SNAKE_CASE_  :		int				      =    json.load(lowerCAmelCase	)
		if OPTS.na_prob_file:
				with open(OPTS.na_prob_file	) as f:
						SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    json.load(lowerCAmelCase	)
		else:
				SCREAMING_SNAKE_CASE_  :		str				      =    {k: 0.0 for k in preds}
		SCREAMING_SNAKE_CASE_  :		str				      =    make_qid_to_has_ans(lowerCAmelCase	)  # maps qid to True/False
		SCREAMING_SNAKE_CASE_  :		int				      =    [k for k, v in qid_to_has_ans.items() if v]
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    [k for k, v in qid_to_has_ans.items() if not v]
		SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    get_raw_scores(lowerCAmelCase   , lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		Tuple				      =    apply_no_ans_threshold(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , OPTS.na_prob_thresh	)
		SCREAMING_SNAKE_CASE_  :		Any				      =    apply_no_ans_threshold(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , OPTS.na_prob_thresh	)
		SCREAMING_SNAKE_CASE_  :		List[str]				      =    make_eval_dict(lowerCAmelCase   , lowerCAmelCase	)
		if has_ans_qids:
				SCREAMING_SNAKE_CASE_  :		int				      =    make_eval_dict(lowerCAmelCase   , lowerCAmelCase   , qid_list=lowerCAmelCase	)
				merge_eval(lowerCAmelCase   , lowerCAmelCase   , "HasAns"	)
		if no_ans_qids:
				SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    make_eval_dict(lowerCAmelCase   , lowerCAmelCase   , qid_list=lowerCAmelCase	)
				merge_eval(lowerCAmelCase   , lowerCAmelCase   , "NoAns"	)
		if OPTS.na_prob_file:
				find_all_best_thresh(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase	)
		if OPTS.na_prob_file and OPTS.out_image_dir:
				run_precision_recall_analysis(lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , lowerCAmelCase   , OPTS.out_image_dir	)
				histogram_na_prob(lowerCAmelCase   , lowerCAmelCase   , OPTS.out_image_dir   , "hasAns"	)
				histogram_na_prob(lowerCAmelCase   , lowerCAmelCase   , OPTS.out_image_dir   , "noAns"	)
		if OPTS.out_file:
				with open(OPTS.out_file   , "w"	) as f:
						json.dump(lowerCAmelCase   , lowerCAmelCase	)
		else:
				print(json.dumps(lowerCAmelCase   , indent=2	)	)


if __name__ == "__main__":
		__lowerCamelCase					:	List[Any]       =  parse_args()
		if OPTS.out_image_dir:
				import matplotlib

				matplotlib.use('''Agg''')
				import matplotlib.pyplot as plt
		main()

"""simple docstring"""






import hashlib
import unittest
from typing import Dict

import numpy as np

from transformers import (
    MODEL_FOR_MASK_GENERATION_MAPPING,
    TF_MODEL_FOR_MASK_GENERATION_MAPPING,
    is_vision_available,
    pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)


if is_vision_available():
						from PIL import Image
else:
						class 				snake_case       :




											"""simple docstring"""

											@staticmethod
											def 		__lowerCAmelCase						(				*lowerCamelCase__   :	List[Any]    ,**lowerCamelCase__   :	Union[str, Any]			):
															pass



def   a_						(					lowerCamelCase       ):
				UpperCAmelCase__             =							hashlib.mda(image.tobytes()       )
				return m.hexdigest()[:1_0]



def   a_						(					lowerCamelCase       ):
				UpperCAmelCase__             =							np.array(lowerCamelCase       )
				UpperCAmelCase__             =							npimg.shape
				return {"hash": hashimage(lowerCamelCase       ), "shape": shape}







@is_pipeline_test
@require_vision
@require_torch
class 				snake_case       ( unittest.TestCase				):




					"""simple docstring"""

					snake_case__				    = dict(
					    (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()				) if MODEL_FOR_MASK_GENERATION_MAPPING else [])				)
					snake_case__				    = dict(
					    (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()				) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else [])				)







					def 		__lowerCAmelCase						(				self   :	List[Any]    ,lowerCamelCase__   :	Dict    ,lowerCamelCase__   :	Optional[int]    ,lowerCamelCase__   :	str			):
									UpperCAmelCase__             =							MaskGenerationPipeline(model=lowerCamelCase__    ,image_processor=lowerCamelCase__			)
									return image_segmenter, [
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									]







					def 		__lowerCAmelCase						(				self   :	Union[str, Any]    ,lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	str			):
									pass







					@require_tf
					@unittest.skip('Image segmentation not implemented in TF'			)
					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									pass







					@slow
					@require_torch
					def 		__lowerCAmelCase						(				self   :	List[str]			):
									UpperCAmelCase__             =							pipeline('mask-generation'    ,model='facebook/sam-vit-huge'			)

									UpperCAmelCase__             =							image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg'    ,points_per_batch=256			)

									# Shortening by hashing
									UpperCAmelCase__             =							[]
									for i, o in enumerate(outputs['masks']			):
													new_outupt += [{"mask": mask_to_test_readable(lowerCamelCase__			), "scores": outputs["scores"][i]}]

									# fmt: off
									self.assertEqual(
									    nested_simplify(lowerCamelCase__    ,decimals=4			)    ,[
									        {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4},
									        {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1},
									        {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7},
									        {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2},
									        {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3},
									        {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7},
									        {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3},
									        {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9},
									        {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9},
									        {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4},
									        {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6},
									        {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2},
									        {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9},
									        {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2},
									        {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2},
									        {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6},
									        {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9},
									        {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3},
									        {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4},
									        {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3},
									        {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3},
									        {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8},
									        {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5},
									        {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6},
									        {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2},
									        {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9},
									        {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6},
									        {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4},
									        {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3},
									        {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1}
									    ]    ,)
									# fmt: on







					@require_torch
					@slow
					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									UpperCAmelCase__             =							'facebook/sam-vit-huge'
									UpperCAmelCase__             =							pipeline('mask-generation'    ,model=lowerCamelCase__			)

									UpperCAmelCase__             =							image_segmenter(
									    'http://images.cocodataset.org/val2017/000000039769.jpg'    ,pred_iou_thresh=1    ,points_per_batch=256			)

									# Shortening by hashing
									UpperCAmelCase__             =							[]
									for i, o in enumerate(outputs['masks']			):
													new_outupt += [{"mask": mask_to_test_readable(lowerCamelCase__			), "scores": outputs["scores"][i]}]

									self.assertEqual(
									    nested_simplify(lowerCamelCase__    ,decimals=4			)    ,[
									        {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4},
									        {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0},
									        {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7},
									        {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2},
									        {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3},
									    ]    ,)



